<?php
namespace Controllers;

use Models\Database;

class ModerationSettingsController {
    private $pdo;

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

    public function index() {
        $data['moderations'] = $this->pdo->query("
            SELECT m.*, CONCAT(e.first_name, ' ', e.last_name) AS employee_name
            FROM moderation_settings m
            JOIN employees e ON m.employee_id = e.id
            ORDER BY m.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 moderation_settings (employee_id, keyname, label, amount)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([
                $_POST['employee_id'], $_POST['keyname'], $_POST['label'], $_POST['amount']
            ]);
            header('Location: /moderation-settings');
            exit;
        }
    }

    public function edit() {
        $id = $_GET['id'];
        $stmt = $this->pdo->prepare("SELECT * FROM moderation_settings WHERE id = ?");
        $stmt->execute([$id]);
        $data['moderation'] = $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 moderation_settings
                SET employee_id=?, keyname=?, label=?, amount=?
                WHERE id=?
            ");
            $stmt->execute([
                $_POST['employee_id'], $_POST['keyname'], $_POST['label'], $_POST['amount'], $_POST['id']
            ]);
            header('Location: /moderation-settings');
            exit;
        }
    }

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

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