<?php

namespace App\Controllers\SuperAdmin;

use App\Controllers\BaseController;
use App\Models\LicenseKeyModel;
use App\Models\AuditLogModel;
use App\Models\ReportedSystemModel;
use App\Models\RegisteredSystemModel;

class LicenseKeys extends BaseController
{
    protected $model;
    protected $auditLog;
    protected $reportedSystemModel;
    protected $registeredSystemModel;

    public function __construct()
    {
        $this->model = new LicenseKeyModel();
        $this->auditLog = new AuditLogModel();
        $this->reportedSystemModel = new ReportedSystemModel();
        $this->registeredSystemModel = new RegisteredSystemModel();
    }

    public function index()
    {
        $data['licenses'] = $this->model->orderBy('created_at', 'DESC')->findAll();
        return view('superadmin/licenses/index', $data);
    }

    public function create()
    {
        return view('superadmin/licenses/create');
    }

    public function generateCode()
    {
        return $this->response->setJSON(['code' => $this->model->generateUniqueCode()]);
    }

    public function store()
    {
        $data = [
            'license_code' => $this->request->getPost('license_code'),
            'organization_name' => $this->request->getPost('organization_name'),
            'contact_email' => $this->request->getPost('contact_email'),
            'contact_phone' => $this->request->getPost('contact_phone'),
            'status' => $this->request->getPost('status') ?? 'active',
            'max_seats' => $this->request->getPost('max_seats') ?? 1,
            'used_seats' => 0,
            'valid_from' => $this->request->getPost('valid_from'),
            'valid_until' => $this->request->getPost('valid_until'),
            'notes' => $this->request->getPost('notes'),
            'enable_login_screen' => $this->request->getPost('enable_login_screen') === 'yes' ? 1 : 0,
            'enable_camera_detection' => $this->request->getPost('enable_camera_detection') === 'yes' ? 1 : 0,
            'enable_person_detection' => $this->request->getPost('enable_person_detection') === 'yes' ? 1 : 0,
            'screenshot_needed' => $this->request->getPost('screenshot_needed') === 'yes' ? 1 : 0,
            'lms_probe_origin' => $this->request->getPost('lms_probe_origin'),
            'sap_web_url' => $this->request->getPost('sap_web_url'),
            'created_by' => session()->get('super_admin_id'),
            'created_at' => date('Y-m-d H:i:s')
        ];

        if ($this->model->insert($data)) {
            $this->auditLog->log('super_admin', session()->get('super_admin_id'), 'Created License Key', 'license_keys', $this->model->getInsertID(), null, $data);
            return redirect()->to('/superadmin/licenses')->with('success', 'License key created successfully');
        }

        return redirect()->back()->with('error', 'Failed to create license key');
    }

    public function show($id)
    {
        $data['license'] = $this->model->find($id);
        if (!$data['license']) {
            return redirect()->to('/superadmin/licenses')->with('error', 'License not found');
        }
        $data['systemUsage'] = $this->model->getSystemUsage($id);
        $data['reportedSystems'] = $this->reportedSystemModel->getByLicense($id);
        $data['registeredSystems'] = $this->registeredSystemModel->getSystemsByLicense($id);
        return view('superadmin/licenses/show', $data);
    }

    public function edit($id)
    {
        $data['license'] = $this->model->find($id);
        if (!$data['license']) {
            return redirect()->to('/superadmin/licenses')->with('error', 'License not found');
        }
        return view('superadmin/licenses/edit', $data);
    }

    public function update($id)
    {
        $oldData = $this->model->find($id);
        
        $data = [
            'organization_name' => $this->request->getPost('organization_name'),
            'contact_email' => $this->request->getPost('contact_email'),
            'contact_phone' => $this->request->getPost('contact_phone'),
            'status' => $this->request->getPost('status'),
            'max_seats' => $this->request->getPost('max_seats'),
            'valid_from' => $this->request->getPost('valid_from'),
            'valid_until' => $this->request->getPost('valid_until'),
            'notes' => $this->request->getPost('notes'),
            'enable_login_screen' => $this->request->getPost('enable_login_screen') === 'yes' ? 1 : 0,
            'enable_camera_detection' => $this->request->getPost('enable_camera_detection') === 'yes' ? 1 : 0,
            'enable_person_detection' => $this->request->getPost('enable_person_detection') === 'yes' ? 1 : 0,
            'screenshot_needed' => $this->request->getPost('screenshot_needed') === 'yes' ? 1 : 0,
            'lms_probe_origin' => $this->request->getPost('lms_probe_origin'),
            'sap_web_url' => $this->request->getPost('sap_web_url'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        if ($this->model->update($id, $data)) {
            $this->auditLog->log('super_admin', session()->get('super_admin_id'), 'Updated License Key', 'license_keys', $id, $oldData, $data);
            return redirect()->to('/superadmin/licenses')->with('success', 'License key updated successfully');
        }

        return redirect()->back()->with('error', 'Failed to update license key');
    }

    public function delete($id)
    {
        $oldData = $this->model->find($id);
        
        if ($this->model->delete($id)) {
            $this->auditLog->log('super_admin', session()->get('super_admin_id'), 'Deleted License Key', 'license_keys', $id, $oldData, null);
            return redirect()->to('/superadmin/licenses')->with('success', 'License key deleted successfully');
        }

        return redirect()->back()->with('error', 'Failed to delete license key');
    }
}
