<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\AdminSettingsModel;
use App\Models\AdminLicenseCacheModel;
use App\Models\RegisteredSystemModel;
use App\Models\LicenseKeyModel;
use App\Libraries\LicenseSyncService;
use Config\Deployment;

class Dashboard extends BaseController
{
    public function index()
    {
        $userModel = new UserModel();
        $settingsModel = new AdminSettingsModel();
        $licenseCacheModel = new AdminLicenseCacheModel();
        $systemModel = new RegisteredSystemModel();
        $licenseModel = new LicenseKeyModel();
        $deployment = config('Deployment');
        
        $adminId = session()->get('admin_id');
        $licenseId = session()->get('admin_license_id');
        
        $settings = $settingsModel->where('admin_id', $adminId)->first();
        $licenseCache = $licenseCacheModel->getByAdminId($adminId);
        $license = $licenseModel->find($licenseId);
        
        $licenseData = null;
        $signatureValid = false;
        
        if ($licenseCache) {
            $licenseData = json_decode($licenseCache['license_data'], true);
            $signatureService = new \App\Libraries\SignatureService();
            try {
                $signatureValid = $signatureService->verifySignature($licenseData, $licenseCache['signature']);
            } catch (\Exception $e) {
                $signatureValid = false;
            }
        }
        
        $registeredSystems = [];
        $activeSystemsCount = 0;
        if ($licenseId) {
            $registeredSystems = $systemModel->getSystemsByLicense($licenseId);
            $activeSystemsCount = $systemModel->countActiveByLicense($licenseId);
        }
        
        $data = [
            'totalUsers' => $userModel->where('admin_id', $adminId)->countAllResults(),
            'activeUsers' => $userModel->where('admin_id', $adminId)->where('status', 'active')->countAllResults(),
            'disabledUsers' => $userModel->where('admin_id', $adminId)->where('status', 'inactive')->countAllResults(),
            'deployment' => $deployment,
            'licenseCache' => $licenseCache,
            'licenseData' => $licenseData,
            'signatureValid' => $signatureValid,
            'license' => $license,
            'registeredSystems' => $registeredSystems,
            'activeSystemsCount' => $activeSystemsCount,
            'maxSeats' => $licenseData['max_seats'] ?? ($license['max_seats'] ?? 0),
        ];
        
        return view('admin/dashboard', $data);
    }

    public function syncLicense()
    {
        $deployment = config('Deployment');
        $settingsModel = new AdminSettingsModel();
        $licenseCacheModel = new AdminLicenseCacheModel();
        $licenseModel = new LicenseKeyModel();
        $auditLog = new \App\Models\AuditLogModel();
        
        $adminId = session()->get('admin_id');
        $settings = $settingsModel->where('admin_id', $adminId)->first();
        
        if (!$settings || empty($settings['license_key'])) {
            return redirect()->to('/admin/dashboard')->with('error', 'No license key configured. Please go to Settings to configure your license.');
        }
        
        $licenseCode = $settings['license_key'];
        
        if ($deployment->isSuperAdmin()) {
            // In superadmin mode, directly fetch from local database and sign it
            $license = $licenseModel->where('license_code', $licenseCode)->first();
            
            if (!$license) {
                return redirect()->to('/admin/dashboard')->with('error', 'License not found: ' . $licenseCode);
            }
            
            $signatureService = new \App\Libraries\SignatureService();
            
            $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 = $signatureService->createSignedPayload($licenseData);
                
                $licenseCacheModel->updateOrCreate(
                    $adminId,
                    $licenseCode,
                    $signedPayload['data'],
                    $signedPayload['signature'],
                    $signedPayload['signed_at']
                );
                
                $auditLog->log('admin', $adminId, 'License synced (local mode)', 'admin_license_cache', $adminId);
                return redirect()->to('/admin/dashboard')->with('success', 'License synced successfully');
            } catch (\Exception $e) {
                return redirect()->to('/admin/dashboard')->with('error', 'Sync failed: ' . $e->getMessage());
            }
        }
        
        // In admin mode, fetch from Super Admin API
        $syncService = new LicenseSyncService();
        $result = $syncService->syncLicense($adminId, $licenseCode);
        
        if ($result['success']) {
            $auditLog->log('admin', $adminId, 'License synced from Super Admin', 'admin_license_cache', $adminId);
            return redirect()->to('/admin/dashboard')->with('success', 'License synced successfully from Super Admin');
        }
        
        return redirect()->to('/admin/dashboard')->with('error', 'Sync failed: ' . $result['message']);
    }
}
