<?php

require_once ROOT_PATH . '/app/models/Differentiator.php';

/**
 * Class DifferentiatorController
 *
 * Gestiona la lógica CRUD para la tabla 'differentiators'.
 */
class DifferentiatorController
{
    private PDO $db;
    private Differentiator $differentiator;

    public function __construct(PDO $db)
    {
        $this->db = $db;
        $this->differentiator = new Differentiator($this->db);
    }

    /**
     * Muestra la lista de todos los diferenciadores.
     */
    public function index(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        $differentiators = $this->differentiator->readAll()->fetchAll(PDO::FETCH_ASSOC);

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/differentiators/index.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Gestionar Diferenciadores");
    }

    /**
     * Muestra el formulario para crear un nuevo diferenciador o procesa su creación.
     */
    public function create(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        $error = null;
        $differentiatorData = []; // Para repoblar el formulario en caso de error

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $differentiatorData = $_POST;
            $this->differentiator->title = $_POST['title'] ?? '';
            $this->differentiator->description = $_POST['description'] ?? '';
            $this->differentiator->icon = $_POST['icon'] ?? '';
            $this->differentiator->display_order = (int)($_POST['display_order'] ?? 0);

            if ($this->differentiator->create()) {
                $_SESSION['message'] = "¡Diferenciador creado exitosamente!";
                redirect('admin/differentiators');
            } else {
                $error = "Falló al crear el diferenciador.";
            }
        }

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/differentiators/create.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Crear Nuevo Diferenciador");
    }

    /**
     * Muestra el formulario para editar un diferenciador o procesa la actualización.
     */
    public function edit(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        $error = null;
        $this->differentiator->id = $_GET['id'] ?? 0;

        if (!$this->differentiator->readOne()) {
            $_SESSION['error'] = "Diferenciador no encontrado.";
            redirect('admin/differentiators');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->differentiator->id = $_POST['id'];
            $this->differentiator->title = $_POST['title'] ?? '';
            $this->differentiator->description = $_POST['description'] ?? '';
            $this->differentiator->icon = $_POST['icon'] ?? '';
            $this->differentiator->display_order = (int)($_POST['display_order'] ?? 0);

            if ($this->differentiator->update()) {
                $_SESSION['message'] = "¡Diferenciador actualizado exitosamente!";
                redirect('admin/differentiators');
            } else {
                $error = "Falló al actualizar el diferenciador.";
            }
        }

        ob_start();
        require_once ROOT_PATH . '/app/views/admin/differentiators/edit.php';
        $content = ob_get_clean();
        $this->renderAdminLayout($content, "Editar Diferenciador");
    }

    /**
     * Procesa la eliminación de un diferenciador de forma segura (vía POST).
     */
    public function delete(): void
    {
        if (!isset($_SESSION['user_id'])) { redirect('login'); }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->differentiator->id = $_POST['id'] ?? 0;
            if ($this->differentiator->delete()) {
                $_SESSION['message'] = "¡Diferenciador eliminado exitosamente!";
            } else {
                $_SESSION['error'] = "Falló al eliminar el diferenciador.";
            }
        }
        redirect('admin/differentiators');
    }

    /**
     * Renderiza el layout principal del panel de administración.
     */
    private function renderAdminLayout(string $content, string $pageTitle): void
    {
        ob_start();
        echo $content;
        $content = ob_get_clean();
        require_once ROOT_PATH . '/app/views/admin/layout.php';
    }
}