<?php

namespace App\Controllers\Api;

use App\Controllers\BaseController;
use App\Models\LicenseKeyModel;
use App\Libraries\SignatureService;
use CodeIgniter\API\ResponseTrait;

class LicenseFetch extends BaseController
{
    use ResponseTrait;

    protected LicenseKeyModel $licenseModel;
    protected SignatureService $signatureService;

    public function __construct()
    {
        $this->licenseModel = new LicenseKeyModel();
        $this->signatureService = new SignatureService();
    }

    public function fetchLicense()
    {
        $deployment = config('Deployment');
        
        if (!$deployment->isSuperAdmin()) {
            return $this->failForbidden('This endpoint is only available on Super Admin deployment');
        }

        $apiKey = $this->request->getHeaderLine('X-API-Key') ?? $this->request->getVar('api_key');
        $expectedApiKey = env('license.apiKey', '');
        
        if (!empty($expectedApiKey) && $apiKey !== $expectedApiKey) {
            return $this->failUnauthorized('Invalid API key');
        }

        $licenseCode = $this->request->getVar('license_code') ?? $this->request->getVar('code');
        
        if (empty($licenseCode)) {
            return $this->fail('License code is required', 400);
        }

        $license = $this->licenseModel->where('license_code', $licenseCode)->first();

        if (!$license) {
            return $this->failNotFound('License not found');
        }

        $licenseData = [
            'license_code' => $license['license_code'],
            'organization_name' => $license['organization_name'],
            'max_seats' => (int) $license['max_seats'],
            'used_seats' => (int) $license['used_seats'],
            'valid_from' => $license['valid_from'],
            'valid_until' => $license['valid_until'],
            'status' => $license['status'],
            'enable_login_screen' => (bool) $license['enable_login_screen'],
            'enable_camera_detection' => (bool) $license['enable_camera_detection'],
            'enable_person_detection' => (bool) $license['enable_person_detection'],
            'lms_probe_origin' => $license['lms_probe_origin'] ?? '',
            'screenshot_needed' => (bool) ($license['screenshot_needed'] ?? false),
            'sap_web_url' => $license['sap_web_url'] ?? '',
            'fetched_at' => date('Y-m-d H:i:s'),
        ];

        try {
            $signedPayload = $this->signatureService->createSignedPayload($licenseData);
            
            return $this->respond([
                'success' => true,
                'license' => $signedPayload,
            ]);
        } catch (\Exception $e) {
            return $this->fail('Failed to sign license data: ' . $e->getMessage(), 500);
        }
    }

    public function syncLicense()
    {
        $deployment = config('Deployment');
        
        if (!$deployment->isSuperAdmin()) {
            return $this->failForbidden('This endpoint is only available on Super Admin deployment');
        }

        $apiKey = $this->request->getHeaderLine('X-API-Key') ?? $this->request->getVar('api_key');
        $expectedApiKey = env('license.apiKey', '');
        
        if (!empty($expectedApiKey) && $apiKey !== $expectedApiKey) {
            return $this->failUnauthorized('Invalid API key');
        }

        $licenseCode = $this->request->getVar('license_code') ?? $this->request->getVar('code');
        $currentVersion = $this->request->getVar('current_version');
        
        if (empty($licenseCode)) {
            return $this->fail('License code is required', 400);
        }

        $license = $this->licenseModel->where('license_code', $licenseCode)->first();

        if (!$license) {
            return $this->failNotFound('License not found');
        }

        $licenseData = [
            'license_code' => $license['license_code'],
            'organization_name' => $license['organization_name'],
            'max_seats' => (int) $license['max_seats'],
            'used_seats' => (int) $license['used_seats'],
            'valid_from' => $license['valid_from'],
            'valid_until' => $license['valid_until'],
            'status' => $license['status'],
            'enable_login_screen' => (bool) $license['enable_login_screen'],
            'enable_camera_detection' => (bool) $license['enable_camera_detection'],
            'enable_person_detection' => (bool) $license['enable_person_detection'],
            'lms_probe_origin' => $license['lms_probe_origin'] ?? '',
            'screenshot_needed' => (bool) ($license['screenshot_needed'] ?? false),
            'sap_web_url' => $license['sap_web_url'] ?? '',
            'version' => md5(json_encode($license)),
            'fetched_at' => date('Y-m-d H:i:s'),
        ];

        $currentVersionHash = md5(json_encode($license));
        $hasChanges = ($currentVersion !== $currentVersionHash);

        try {
            $signedPayload = $this->signatureService->createSignedPayload($licenseData);
            
            return $this->respond([
                'success' => true,
                'has_changes' => $hasChanges,
                'license' => $signedPayload,
            ]);
        } catch (\Exception $e) {
            return $this->fail('Failed to sign license data: ' . $e->getMessage(), 500);
        }
    }

    public function validateSignature()
    {
        $data = $this->request->getJSON(true);
        
        if (!isset($data['data']) || !isset($data['signature'])) {
            return $this->fail('Data and signature are required', 400);
        }

        try {
            $isValid = $this->signatureService->verifySignature($data['data'], $data['signature']);
            
            return $this->respond([
                'success' => true,
                'valid' => $isValid,
            ]);
        } catch (\Exception $e) {
            return $this->fail('Signature verification failed: ' . $e->getMessage(), 500);
        }
    }
}
