<?php
declare(strict_types=1);

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

class Dashboard extends Controller {

    private $jobcardModel;

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

        // Lock clients out of the staff dashboard
        if (isClient()) {
            header('Location: ' . URLROOT . '/clientdashboard/index');
            exit;
        }

        $this->jobcardModel = $this->model('Jobcard');
    }

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

        // Fetch jobcards to calculate stats
        $jobcards = $this->jobcardModel->getJobcards('staff', (int)$_SESSION['user_id']);
        
        $stats = [
            'active' => 0,
            'completed' => 0,
            'total' => count($jobcards)
        ];

        foreach ($jobcards as $jc) {
            if (in_array($jc->status, ['Assigned', 'Started'])) {
                $stats['active']++;
            } elseif (in_array($jc->status, ['Completed', 'Signed Off'])) {
                $stats['completed']++;
            }
        }

        $data = [
            'title' => 'My Dashboard',
            'description' => 'Welcome to your internal staff workspace.',
            'user' => $user,
            'stats' => $stats,
            
            // Contextual Help
            'help_title' => 'Staff Workspace Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Internal Workspace</h4>
                <p>Welcome to your staff dashboard. From here, you can monitor your performance metrics and manage your assignments.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>My Details:</strong> A quick overview of your account information. Click "Edit Profile" to update your email, password, or Two-Factor Authentication (2FA) settings.</li>
                    <li><strong>Jobcard Stats:</strong> Track your current active workload and your lifetime completed tasks.</li>
                </ul>
            '
        ];

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