<?php
namespace Controllers;

use Models\Database;

class BenefitsInKindController {
    private $pdo;

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

    public function index() {
        $data['benefits'] = $this->pdo->query("
            SELECT b.*, CONCAT(e.first_name, ' ', e.last_name) AS employee_name
            FROM benefits_in_kind_settings b
            JOIN employees e ON b.employee_id = e.id
            ORDER BY b.id DESC
        ")->fetchAll();

        $this->loadInDashboard('index.php', $data);
    }

    public function create() {
        $data['employees'] = $this->pdo->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name FROM employees")->fetchAll();
        $this->loadInDashboard('form.php', $data);
    }

    public function store() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $stmt = $this->pdo->prepare("
                INSERT INTO benefits_in_kind_settings (employee_id, keyname, label, amount)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([
                $_POST['employee_id'], $_POST['keyname'], $_POST['label'], $_POST['amount']
            ]);
            header('Location: /benefits');
            exit;
        }
    }

    public function edit() {
        $id = $_GET['id'];
        $stmt = $this->pdo->prepare("SELECT * FROM benefits_in_kind_settings WHERE id = ?");
        $stmt->execute([$id]);
        $data['benefit'] = $stmt->fetch();

        $data['employees'] = $this->pdo->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name FROM employees")->fetchAll();

        $this->loadInDashboard('form.php', $data);
    }

    public function update() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $stmt = $this->pdo->prepare("
                UPDATE benefits_in_kind_settings
                SET employee_id=?, keyname=?, label=?, amount=?
                WHERE id=?
            ");
            $stmt->execute([
                $_POST['employee_id'], $_POST['keyname'], $_POST['label'], $_POST['amount'], $_POST['id']
            ]);
            header('Location: /benefits');
            exit;
        }
    }

    public function delete() {
        if (isset($_POST['id'])) {
            $stmt = $this->pdo->prepare("DELETE FROM benefits_in_kind_settings WHERE id = ?");
            $stmt->execute([$_POST['id']]);
            header('Location: /benefits');
            exit;
        }
    }

    private function loadInDashboard($viewFile, $data = []) {
        extract($data);
        $viewPath = __DIR__ . '/../views/benefits/' . $viewFile;
        if (!file_exists($viewPath)) {
            throw new \Exception("Vue $viewFile introuvable");
        }
        $view = $viewPath;
        require __DIR__ . '/../views/dashboard.php';
    }
}