<?php

namespace App\Libraries;

use Config\Deployment;
use App\Models\AdminLicenseCacheModel;

class LicenseSyncService
{
    protected Deployment $config;
    protected SignatureService $signatureService;
    protected AdminLicenseCacheModel $cacheModel;

    public function __construct()
    {
        $this->config = config('Deployment');
        $this->signatureService = new SignatureService();
        $this->cacheModel = new AdminLicenseCacheModel();
    }

    public function fetchLicenseFromSuperAdmin(string $licenseCode): array
    {
        if ($this->config->isSuperAdmin()) {
            return [
                'success' => false,
                'message' => 'This function is only for Admin deployments',
            ];
        }

        $apiUrl = rtrim($this->config->superAdminApiUrl, '/') . '/api/license/fetch';
        
        if (empty($this->config->superAdminApiUrl)) {
            return [
                'success' => false,
                'message' => 'Super Admin API URL not configured',
            ];
        }

        try {
            $apiKey = env('superadmin.apiKey', '');
            $headers = [
                'Accept: application/json',
                'Content-Type: application/json',
            ];
            
            if (!empty($apiKey)) {
                $headers[] = 'X-API-Key: ' . $apiKey;
            }
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $apiUrl . '?license_code=' . urlencode($licenseCode),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => true,
                CURLOPT_HTTPHEADER => $headers,
            ]);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error = curl_error($ch);
            curl_close($ch);

            if ($error) {
                return [
                    'success' => false,
                    'message' => 'Failed to connect to Super Admin: ' . $error,
                ];
            }

            if ($httpCode !== 200) {
                return [
                    'success' => false,
                    'message' => 'Super Admin returned error (HTTP ' . $httpCode . ')',
                ];
            }

            $data = json_decode($response, true);

            if (!isset($data['success']) || !$data['success']) {
                return [
                    'success' => false,
                    'message' => $data['messages']['error'] ?? 'Unknown error from Super Admin',
                ];
            }

            return [
                'success' => true,
                'license' => $data['license'],
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Exception: ' . $e->getMessage(),
            ];
        }
    }

    public function syncLicense(int $adminId, string $licenseCode): array
    {
        $fetchResult = $this->fetchLicenseFromSuperAdmin($licenseCode);

        if (!$fetchResult['success']) {
            return $fetchResult;
        }

        $signedPayload = $fetchResult['license'];

        if (!$this->signatureService->verifySignedPayload($signedPayload)) {
            return [
                'success' => false,
                'message' => 'License signature verification failed. Data may be tampered.',
            ];
        }

        $saved = $this->cacheModel->updateOrCreate(
            $adminId,
            $licenseCode,
            $signedPayload['data'],
            $signedPayload['signature'],
            $signedPayload['signed_at']
        );

        if (!$saved) {
            return [
                'success' => false,
                'message' => 'Failed to save license data locally',
            ];
        }

        return [
            'success' => true,
            'message' => 'License synced successfully',
            'license_data' => $signedPayload['data'],
        ];
    }

    public function getCachedLicense(int $adminId): ?array
    {
        $cache = $this->cacheModel->getByAdminId($adminId);
        
        if (!$cache) {
            return null;
        }

        $licenseData = json_decode($cache['license_data'], true);

        if (!$this->signatureService->verifySignature($licenseData, $cache['signature'])) {
            return null;
        }

        return [
            'data' => $licenseData,
            'signature' => $cache['signature'],
            'signed_at' => $cache['signed_at'],
            'synced_at' => $cache['synced_at'],
        ];
    }

    public function isLicenseValid(int $adminId): array
    {
        $cached = $this->getCachedLicense($adminId);

        if (!$cached) {
            return [
                'valid' => false,
                'reason' => 'No cached license or signature invalid',
            ];
        }

        $data = $cached['data'];

        if ($data['status'] !== 'active') {
            return [
                'valid' => false,
                'reason' => 'License status is ' . $data['status'],
            ];
        }

        if (!empty($data['valid_until']) && strtotime($data['valid_until']) < time()) {
            return [
                'valid' => false,
                'reason' => 'License expired on ' . $data['valid_until'],
            ];
        }

        return [
            'valid' => true,
            'data' => $data,
            'synced_at' => $cached['synced_at'],
        ];
    }
}
