<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AdminModel;
use App\Models\AuditLogModel;
use App\Models\LicenseKeyModel;
use App\Models\AdminSettingsModel;
use App\Models\AdminLicenseCacheModel;
use App\Libraries\LicenseSyncService;
use Config\Deployment;

class Auth extends BaseController
{
    public function login()
    {
        if (session()->get('admin_logged_in')) {
            return redirect()->to('/admin/dashboard');
        }
        return view('admin/login');
    }

    public function register()
    {
        $deployment = config('Deployment');
        $licenseModel = new LicenseKeyModel();
        $adminModel = new AdminModel();
        $settingsModel = new AdminSettingsModel();
        $auditLog = new AuditLogModel();
        
        $licenseKey = $this->request->getPost('license_key');
        $username = $this->request->getPost('username');
        $email = $this->request->getPost('email');
        $fullName = $this->request->getPost('full_name');
        $password = $this->request->getPost('password');
        $confirmPassword = $this->request->getPost('confirm_password');
        
        if ($password !== $confirmPassword) {
            return redirect()->to('/admin/login')->with('error', 'Passwords do not match');
        }
        
        $license = null;
        $licenseData = null;
        
        if ($deployment->isAdmin()) {
            $syncService = new LicenseSyncService();
            $fetchResult = $syncService->fetchLicenseFromSuperAdmin($licenseKey);
            
            if (!$fetchResult['success']) {
                return redirect()->to('/admin/login')->with('error', 'Failed to validate license: ' . $fetchResult['message']);
            }
            
            $licenseData = $fetchResult['license']['data'];
            
            if ($licenseData['status'] !== 'active') {
                return redirect()->to('/admin/login')->with('error', 'License is not active');
            }
            
            $license = $licenseModel->where('license_code', $licenseKey)->first();
            if (!$license) {
                $licenseModel->insert([
                    'license_code' => $licenseKey,
                    'organization_name' => $licenseData['organization_name'],
                    'max_seats' => $licenseData['max_seats'],
                    'used_seats' => $licenseData['used_seats'],
                    'valid_from' => $licenseData['valid_from'],
                    'valid_until' => $licenseData['valid_until'],
                    'status' => $licenseData['status'],
                    'enable_login_screen' => $licenseData['enable_login_screen'],
                    'enable_camera_detection' => $licenseData['enable_camera_detection'],
                    'enable_person_detection' => $licenseData['enable_person_detection'],
                ]);
                $license = $licenseModel->where('license_code', $licenseKey)->first();
            }
        } else {
            $license = $licenseModel->isValidLicense($licenseKey);
            if (!$license) {
                return redirect()->to('/admin/login')->with('error', 'Invalid or expired license key');
            }
            $licenseData = [
                'enable_camera_detection' => $license['enable_camera_detection'],
                'enable_person_detection' => $license['enable_person_detection'],
            ];
        }
        
        $existingAdmin = $adminModel->where('license_id', $license['id'])->first();
        if ($existingAdmin) {
            return redirect()->to('/admin/login')->with('error', 'An admin already exists for this license key');
        }
        
        $existingUsername = $adminModel->where('username', $username)->first();
        if ($existingUsername) {
            return redirect()->to('/admin/login')->with('error', 'Username already taken');
        }
        
        $adminData = [
            'username' => $username,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'email' => $email,
            'full_name' => $fullName,
            'role' => 'admin',
            'status' => 'active',
            'license_id' => $license['id'],
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $adminModel->insert($adminData);
        $adminId = $adminModel->getInsertID();
        
        $settingsModel->insert([
            'admin_id' => $adminId,
            'license_key' => $licenseKey,
            'allow_login' => true,
            'camera_detection' => (bool)($licenseData['enable_camera_detection'] ?? false),
            'person_detection' => (bool)($licenseData['enable_person_detection'] ?? false),
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        if ($deployment->isAdmin()) {
            $syncService = new LicenseSyncService();
            $syncResult = $syncService->syncLicense($adminId, $licenseKey);
            
            if (!$syncResult['success']) {
                $auditLog->log('admin', $adminId, 'License sync failed during registration: ' . $syncResult['message'], 'admins', $adminId);
            }
        }
        
        $auditLog->log('admin', $adminId, 'Registered with License Key', 'admins', $adminId, null, ['license_key' => $licenseKey]);
        
        return redirect()->to('/admin/login')->with('success', 'Registration successful! Please login with your credentials.');
    }

    public function authenticate()
    {
        $model = new AdminModel();
        $auditLog = new AuditLogModel();
        $deployment = config('Deployment');
        
        $username = $this->request->getPost('username');
        $password = $this->request->getPost('password');
        
        $admin = $model->verifyPassword($username, $password);
        
        if ($admin) {
            session()->set([
                'admin_id' => $admin['id'],
                'admin_username' => $admin['username'],
                'admin_full_name' => $admin['full_name'],
                'admin_role' => $admin['role'],
                'admin_license_id' => $admin['license_id'],
                'admin_logged_in' => true
            ]);
            
            $auditLog->log('admin', $admin['id'], 'Login', 'admins', $admin['id']);
            
            // Auto-sync license on login
            $settingsModel = new AdminSettingsModel();
            $settings = $settingsModel->where('admin_id', $admin['id'])->first();
            
            if ($settings && !empty($settings['license_key'])) {
                $syncService = new LicenseSyncService();
                $syncResult = $syncService->syncLicense($admin['id'], $settings['license_key']);
                
                if ($syncResult['success']) {
                    $auditLog->log('admin', $admin['id'], 'Auto-synced license on login', 'admin_license_cache', $admin['id']);
                }
            }
            
            return redirect()->to('/admin/dashboard');
        }
        
        return redirect()->to('/admin/login')->with('error', 'Invalid credentials');
    }

    public function logout()
    {
        $auditLog = new AuditLogModel();
        $auditLog->log('admin', session()->get('admin_id'), 'Logout', 'admins', session()->get('admin_id'));
        
        session()->destroy();
        return redirect()->to('/admin/login');
    }

    public function changePassword()
    {
        return view('admin/change_password');
    }

    public function updatePassword()
    {
        $model = new AdminModel();
        $auditLog = new AuditLogModel();
        
        $currentPassword = $this->request->getPost('current_password');
        $newPassword = $this->request->getPost('new_password');
        $confirmPassword = $this->request->getPost('confirm_password');
        
        if ($newPassword !== $confirmPassword) {
            return redirect()->back()->with('error', 'New passwords do not match');
        }
        
        $admin = $model->find(session()->get('admin_id'));
        
        if (!password_verify($currentPassword, $admin['password'])) {
            return redirect()->back()->with('error', 'Current password is incorrect');
        }
        
        $model->update($admin['id'], [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        
        $auditLog->log('admin', $admin['id'], 'Changed Password', 'admins', $admin['id']);
        
        return redirect()->to('/admin/dashboard')->with('success', 'Password updated successfully');
    }
}
