<?php
declare(strict_types=1);

// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

class App {
    protected $currentController = 'Pages';
    protected string $currentMethod = 'index';
    protected array $params = [];

    public function __construct() {
        
        // --- TAMPER PROTECTION: LAYER 2 ---
        $expectedToken = md5('ChristoDev_Secure_Valid_' . date('Y-m-d'));
        if (!defined('RC_CORE_SECURE') || RC_CORE_SECURE !== $expectedToken) {
            $this->tamperLock();
        }

        // --- REMEMBER ME: AUTO-LOGIN ---
        if (!isset($_SESSION['user_id']) && isset($_COOKIE['remember_me'])) {
            require_once '../app/Models/User.php';
            $userModel = new User();
            $user = $userModel->findByRememberToken($_COOKIE['remember_me']);
            
            if ($user && $user->is_active == 1 && $user->email_verified == 1) {
                $_SESSION['user_id'] = $user->id;
                $_SESSION['user_email'] = $user->email;
                $_SESSION['user_name'] = $user->name;
                $_SESSION['user_role'] = $user->role;
            }
        }

        $url = $this->getUrl();

        // --- MAINTENANCE MODE INTERCEPT ---
        $settings = getSettings();
        $isMaintenance = isset($settings['maintenance_mode']) && $settings['maintenance_mode'] === '1';
        $isAdmin = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
        $requestedController = strtolower($url[0] ?? 'pages');

        // Allow Admins and Auth routes (login/logout) through the maintenance block
        if ($isMaintenance && !$isAdmin && $requestedController !== 'users') {
            require_once '../app/Controllers/Pages.php';
            $pagesController = new Pages();
            $pagesController->maintenance();
            exit;
        }

        // --- MODULAR ROUTING PROXY ---
        if (isset($url[0]) && isset($url[1])) {
            $controllerPrefix = strtolower($url[0]);
            $method = strtolower($url[1]);
            
            // Admin Routes
            if ($controllerPrefix === 'admin') {
                $adminModules = [
                    'users' => 'AdminUsers',
                    'clients' => 'AdminUsers',
                    'adduser' => 'AdminUsers',
                    'edituser' => 'AdminUsers',
                    'viewuser' => 'AdminUsers', // <-- FIXED: Added routing for viewUser
                    'deleteuser' => 'AdminUsers',
                    'impersonate' => 'AdminUsers',
                    'leaveimpersonation' => 'AdminUsers', 
                    'roles' => 'AdminRoles',
                    'addrole' => 'AdminRoles',
                    'editrole' => 'AdminRoles',
                    'deleterole' => 'AdminRoles',
                    'partners' => 'AdminPartners',
                    'addpartner' => 'AdminPartners',
                    'editpartner' => 'AdminPartners',
                    'deletepartner' => 'AdminPartners',
                    'settings' => 'AdminSettings',
                    'backups' => 'AdminBackups',
                    'createbackup' => 'AdminBackups',
                    'downloadbackup' => 'AdminBackups',
                    'deletebackup' => 'AdminBackups',
                    'logs' => 'AdminLogs',
                    'clearlogs' => 'AdminLogs',
                    'cron' => 'AdminCron',
                    'runcron' => 'AdminCron',
                    'emailqueue' => 'AdminCron',
                    'previewemail' => 'AdminCron',
                    'jobcards' => 'AdminJobcards',
                    'createjobcard' => 'AdminJobcards',
                    'viewjobcard' => 'AdminJobcards',
                    'assigntechnician' => 'AdminJobcards',
                    'downloadpdf' => 'AdminJobcards'
                ];
                
                if (array_key_exists($method, $adminModules)) {
                    $url[0] = $adminModules[$method]; 
                }
            }
            
            // Staff Routes
            if ($controllerPrefix === 'staff') {
                $staffModules = [
                    'jobcards' => 'StaffJobcards',
                    'viewjobcard' => 'StaffJobcards',
                    'starttimer' => 'StaffJobcards',
                    'addmaterial' => 'StaffJobcards',
                    'deletematerial' => 'StaffJobcards',
                    'completejobcard' => 'StaffJobcards',
                    'signoff' => 'StaffJobcards',
                    'downloadpdf' => 'StaffJobcards',
                    'history' => 'StaffJobcards' 
                ];
                
                if (array_key_exists($method, $staffModules)) {
                    $url[0] = $staffModules[$method]; 
                }
            }
        }

        // 1. Find the Controller
        if (isset($url[0]) && file_exists('../app/Controllers/' . ucwords($url[0]) . '.php')) {
            $this->currentController = ucwords($url[0]);
            unset($url[0]);
        }

        // Require and instantiate the controller
        require_once '../app/Controllers/' . $this->currentController . '.php';
        $this->currentController = new $this->currentController;

        // 2. Find the Method
        if (isset($url[1])) {
            if (method_exists($this->currentController, $url[1])) {
                $this->currentMethod = $url[1];
                unset($url[1]);
            }
        }

        // 3. Get the Parameters
        $this->params = $url ? array_values($url) : [];

        // 4. Execute the Controller method
        call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
    }

    private function tamperLock() {
        http_response_code(403);
        $reason = "The core validation protocol in the router has been bypassed or tampered with.";
        $code = "SEC_TAMPER_0x2";
        
        echo <<<HTML
        <!DOCTYPE html>
        <html lang="en" class="dark">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>System Locked - Security Alert</title>
            <script src="https://cdn.tailwindcss.com"></script>
            <script>
                tailwind.config = { darkMode: 'class', theme: { extend: { colors: { primary: '#1c70b4', danger: '#ef4444' } } } }
            </script>
        </head>
        <body class="bg-gray-900 text-gray-100 min-h-screen flex items-center justify-center p-4 font-sans selection:bg-danger selection:text-white">
            <div class="max-w-lg w-full bg-gray-800 rounded-2xl shadow-2xl border border-red-900/50 p-8 relative overflow-hidden">
                <div class="absolute top-0 left-0 w-full h-1 bg-red-600 shadow-[0_0_15px_rgba(220,38,38,0.8)]"></div>
                <div class="text-center mb-6">
                    <div class="mx-auto flex items-center justify-center h-20 w-20 rounded-full bg-red-900/30 mb-6 border border-red-500/30 shadow-[0_0_20px_rgba(220,38,38,0.2)]">
                        <svg class="h-10 w-10 text-red-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
                    </div>
                    <h1 class="text-3xl font-extrabold text-white tracking-tight mb-2">System Locked</h1>
                    <p class="text-red-400 font-bold tracking-widest uppercase text-xs">Critical Security Violation</p>
                </div>
                <div class="bg-gray-900/80 rounded-xl p-5 border border-gray-700/50 mb-8 shadow-inner">
                    <p class="text-gray-300 text-sm leading-relaxed text-center font-medium">
                        {$reason}
                    </p>
                </div>
                
                <div class="flex flex-col gap-4">
                    <a href="https://support.christodev.co.za" target="_blank" class="w-full bg-red-600 hover:bg-red-500 text-white font-bold py-3 px-4 rounded-xl shadow-lg transition-all text-center flex items-center justify-center focus:ring-4 focus:ring-red-600/30">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>
                        Need help? Contact Support
                    </a>
                </div>
                <div class="mt-8 pt-5 border-t border-gray-700/50 flex justify-between items-center text-xs text-gray-500 font-mono">
                    <span class="bg-gray-900 px-2 py-1 rounded border border-gray-800">ERR: {$code}</span>
                    <span class="flex items-center"><svg class="w-3 h-3 mr-1 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path></svg> ChristoDev Engine</span>
                </div>
            </div>
        </body>
        </html>
HTML;
        exit;
    }

    public function getUrl(): array {
        if (isset($_GET['url'])) {
            $url = rtrim($_GET['url'], '/');
            $url = filter_var($url, FILTER_SANITIZE_URL);
            return explode('/', $url);
        }
        return [];
    }
}