<?php
declare(strict_types=1);

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

class Admin extends Controller {
    
    private $jobcardModel;

    public function __construct() {
        if (!isLoggedIn()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }

        $url = isset($_GET['url']) ? rtrim($_GET['url'], '/') : '';

        if (!isAdmin() && $url !== 'admin/leaveImpersonation') {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }

        // Initialize the Jobcard model for dashboard analytics
        $this->jobcardModel = $this->model('Jobcard');
    }

    // ==========================================
    // DASHBOARD & PROFILE METHODS
    // ==========================================

    public function index(): void {
        $userModel = $this->model('User');
        $logModel = $this->model('Log');

        $data = [
            'title' => 'Admin Dashboard',
            'description' => 'System overview and quick statistics.',
            'stats' => $userModel->getUserStats(),
            'jobcard_stats' => $this->jobcardModel->getTotalStats(), // Analytics injection
            'analytics' => $this->jobcardModel->getDashboardAnalytics(), // Analytics injection
            'recent_users' => $userModel->getRecentUsers(),
            'recent_logs' => $logModel->getRecentLogs(),
            
            'help_title' => 'Admin Dashboard Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Overview</h4>
                <p>The Admin Dashboard acts as your central command hub. It provides an immediate, high-level summary of your system\'s health, user onboarding rates, and recent activity logs.</p>
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-4">Understanding Key Metrics</h4>
                <ul class="list-disc pl-5 space-y-2">
                    <li><strong>Total Users:</strong> The total number of registered accounts existing in the database (including inactive accounts).</li>
                    <li><strong>Jobcard Volume:</strong> View real-time distributions of your operational pipeline.</li>
                    <li><strong>Active Accounts:</strong> Users who are fully verified and have not been suspended or locked out by brute-force protections.</li>
                    <li><strong>System Health:</strong> A quick indicator of your platform\'s operational status.</li>
                </ul>
            '
        ];

        $this->view('admin/index', $data);
    }

    public function profile(): void {
        $userModel = $this->model('User');
        $user = $userModel->getUserById((int)$_SESSION['user_id']);

        $data = [
            'title' => 'Admin Profile',
            'user' => $user,
            'name' => $user->name,
            'email' => $user->email,
            'contact_number' => $user->contact_number ?? '',
            'address_street' => $user->address_street ?? '',
            'address_suburb' => $user->address_suburb ?? '',
            'address_city' => $user->address_city ?? '',
            'address_state' => $user->address_state ?? '',
            'address_zip' => $user->address_zip ?? '',
            'address_country' => $user->address_country ?? '',
            'totp_enabled' => $user->totp_enabled,
            'name_err' => '',
            'email_err' => '',
            'qr_code_url' => '',
            'setup_secret' => '',
            'help_title' => 'Managing Your Profile',
            'help_content' => '<p>Update your personal administrator details here. We highly recommend activating <strong>Two-Factor Authentication (2FA)</strong> to secure this high-level account. Once activated, ensure you copy your single-use backup codes and store them safely.</p>'
        ];

        if (isset($_GET['setup2fa']) && $user->totp_enabled == 0) {
            $data['setup_secret'] = generateTOTPSecret();
            $appName = getSettings()['app_name'] ?? SITENAME;
            $data['qr_code_url'] = getTOTPQRCodeUrl($appName, $user->email, $data['setup_secret']);
        }

        if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_info'])) {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

            $data['name'] = trim($_POST['name']);
            $data['email'] = trim($_POST['email']);
            $data['contact_number'] = trim($_POST['contact_number'] ?? '');
            $data['address_street'] = trim($_POST['address_street'] ?? '');
            $data['address_suburb'] = trim($_POST['address_suburb'] ?? '');
            $data['address_city'] = trim($_POST['address_city'] ?? '');
            $data['address_state'] = trim($_POST['address_state'] ?? '');
            $data['address_zip'] = trim($_POST['address_zip'] ?? '');
            $data['address_country'] = trim($_POST['address_country'] ?? '');

            if (empty($data['email'])) {
                $data['email_err'] = 'Please enter an email address';
            } elseif ($data['email'] != $user->email && $userModel->findUserByEmail($data['email'])) {
                $data['email_err'] = 'This email is already taken by another account';
            }

            if (empty($data['name'])) {
                $data['name_err'] = 'Please enter your name';
            }

            if (empty($data['email_err']) && empty($data['name_err'])) {
                $updateData = [
                    'id' => $_SESSION['user_id'], 
                    'name' => $data['name'], 
                    'email' => $data['email'],
                    'contact_number' => $data['contact_number'],
                    'address_street' => $data['address_street'],
                    'address_suburb' => $data['address_suburb'],
                    'address_city' => $data['address_city'],
                    'address_state' => $data['address_state'],
                    'address_zip' => $data['address_zip'],
                    'address_country' => $data['address_country']
                ];
                
                if ($userModel->updateProfile($updateData)) {
                    $_SESSION['user_name'] = $data['name'];
                    $_SESSION['user_email'] = $data['email'];

                    systemLog('ADMIN_PROFILE_UPDATED', 'Administrator updated their personal profile.');
                    flash('system_msg', 'Admin profile updated successfully!', 'success');
                    
                    header('Location: ' . URLROOT . '/admin/profile');
                    exit;
                }
            }
        }

        $this->view('admin/profile', $data);
    }

    public function manage2FA(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $userId = (int)$_SESSION['user_id'];

            $db = new Database();

            if (isset($_POST['disable_2fa'])) {
                $db->query("UPDATE users SET totp_enabled = 0, totp_secret = NULL WHERE id = :id");
                $db->bind(':id', $userId);
                $db->execute();
                
                systemLog('2FA_DISABLED', 'Admin disabled Two-Factor Authentication.');
                flash('system_msg', 'Two-Factor Authentication has been disabled.', 'success');
            } 
            elseif (isset($_POST['verify_2fa']) && isset($_POST['setup_secret'])) {
                $secret = trim($_POST['setup_secret']);
                $code = trim($_POST['auth_code']);

                if (verifyTOTPCode($secret, $code)) {
                    $db->query("UPDATE users SET totp_enabled = 1, totp_secret = :secret WHERE id = :id");
                    $db->bind(':secret', $secret);
                    $db->bind(':id', $userId);
                    $db->execute();

                    $userModel = $this->model('User');
                    $_SESSION['new_backup_codes'] = $userModel->generateBackupCodes($userId);

                    systemLog('2FA_ENABLED', 'Admin successfully enabled Two-Factor Authentication and generated Backup Codes.');
                    flash('system_msg', 'Two-Factor Authentication successfully activated! Please save your backup codes below.', 'success');
                } else {
                    flash('system_msg', 'Invalid authentication code. Please try scanning the QR code again.', 'error');
                }
            }

            header('Location: ' . URLROOT . '/admin/profile');
            exit;
        }
    }

    public function updatePassword(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $userModel = $this->model('User');

            $data = [
                'old_password' => trim($_POST['old_password']),
                'new_password' => trim($_POST['new_password']),
                'confirm_password' => trim($_POST['confirm_password']),
            ];

            $currentUser = $userModel->getUserById((int)$_SESSION['user_id']);
            
            if (empty($data['old_password']) || !password_verify($data['old_password'], $currentUser->password)) {
                flash('system_msg', 'Incorrect current password.', 'error');
            } elseif (empty($data['new_password']) || strlen($data['new_password']) < 6) {
                flash('system_msg', 'New password must be at least 6 characters.', 'error');
            } elseif ($data['new_password'] !== $data['confirm_password']) {
                flash('system_msg', 'New passwords do not match.', 'error');
            } else {
                $updateData = [
                    'id' => $_SESSION['user_id'],
                    'password' => password_hash($data['new_password'], PASSWORD_DEFAULT)
                ];

                if ($userModel->updatePassword($updateData)) {
                    systemLog('ADMIN_PASSWORD_CHANGED', 'Administrator successfully changed their password.');
                    flash('system_msg', 'Admin password updated successfully!', 'success');
                } else {
                    flash('system_msg', 'Something went wrong updating your password.', 'error');
                }
            }
            
            header('Location: ' . URLROOT . '/admin/profile');
            exit;
        }
    }
}