<?php
namespace Controllers;

use Models\Database;
use Models\Employee;
use PDO;

class EmployeeController
{
    private $pdo;
    private $employeeModel;

    public function __construct()
    {
        $this->pdo = Database::getInstance()->getConnection();
        $this->employeeModel = new Employee();
    }

    public function index()
    {
        $stmt = $this->pdo->query("SELECT * FROM employees ORDER BY last_name, first_name");
        $employees = $stmt->fetchAll();

        require_once '/../views/employees/index.php';
    }

        private function loadInDashboard($viewFile, $data = []) {
        // Si $data n'est pas vide, extraire les variables du tableau
        if (!empty($data)) {
            extract($data); // Convertit les clés du tableau en variables
        }
        $viewPath = __DIR__ . '/../views/employees/' . $viewFile;

        if (!file_exists($viewPath)) {
            throw new \Exception("Vue $viewFile introuvable");
        }

        $view = $viewPath;
        require __DIR__ . '/../views/dashboard.php';
    }

    public function create()
    {
        //require_once __DIR__ . '/../views/employees/create.php';
        $this->loadInDashboard('create.php');
    }

    public function store()
    {
        require_once __DIR__ . '/../views/employees/store.php';
    }

    public function edit($id)
    {
        $stmt = $this->pdo->prepare("SELECT * FROM employees WHERE id = ?");
        $stmt->execute([$id]);
        $employee = $stmt->fetch();

        if (!$employee) {
            echo "Employé introuvable";
            return;
        }
        $data = [
            'employees' => $this->employeeModel->viewAllEmployees()
        ];
        extract($data);
        //require_once __DIR__ . '/../views/employees/edit.php';
        $this->loadInDashboard('edit.php',$data);
    }

    public function update($id)
    {
        require_once __DIR__ . '/../views/employees/update.php';

    }

    public function delete($id)
    {
        $stmt = $this->pdo->prepare("DELETE FROM employees WHERE id = ?");
        $stmt->execute([$id]);
        header('Location: /employees/view');
        exit();
    }
    public function view(){
        // Récupérer les données pour le dashboard
        $data = [
            'employees' => $this->employeeModel->viewAllEmployees()
        ];
        extract($data); // Convertit les clés du tableau en variables
        $this->loadInDashboard('index.php',$data);
    }
}
