<?php
namespace Controllers;
// /home/advanck/salaires/controllers/DashboardController.php

require_once __DIR__.'/../models/Employee.php';
require_once __DIR__.'/../models/Payslip.php';
require_once __DIR__.'/../models/User.php';
require_once __DIR__.'/../models/ActivityLog.php';

use Models\Employee;
use Models\Payslip;
use Models\User;
// require_once ROOT_PATH . '/utils/Auth.php';
use Utils\Auth;
use Controllers\ActivityLogController;
use Models\ActivityLog;


class DashboardController {
    private $employeeModel;
    private $payslipModel;
    private $userModel;

     public function __construct() {
        $this->employeeModel = new Employee();
        $this->payslipModel = new Payslip();
        $this->userModel = new User();
    }

    public function index() {
        // Test forcé
        if (!class_exists('Utils\Auth')) {
            die("ERREUR: La classe Auth n'est toujours pas chargée. Dernier chemin: " 
                . __DIR__ . '/../utils/Auth.php');
        }
        $activityLog = new \Models\ActivityLog();

        // Vérifier l'authentification
        Auth::checkPermission(['admin', 'chef_comptable', 'comptable']);

        // Récupération de la dernière date
        $lastActivityDate = $activityLog->getLastDate($_SESSION['user_id'] ?? null);

        // Récupérer les données pour le dashboard
        $data = [
            'employeeCount' => $this->employeeModel->count(),//Employee::count(),
            'payslipCount' => $this->payslipModel->countThisMonth(),//'payslipCount' => Payslip::countThisMonth(),
            'lastActivity' => ActivityLog::getLastDate(),
            'lastActivityDate' => $lastActivityDate,
            'recentActivities' => ActivityLog::getRecent(5)
        ];
        extract($data); // Convertit les clés du tableau en variables
        // Charger la vue
        $this->loadView('dashboard', $data);
    }

    private function loadView($viewName, $data = []) {
        $viewPath = __DIR__.'/../views/'.$viewName.'.php';
        if (file_exists($viewPath)) {
            extract($data);
            //$view = "";//$viewPath;
            require $viewPath;
        } else {
            throw new \Exception("La vue $viewName n'existe pas");
        }
    }
}
?>