<?php

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

/**
 * Class FaqController
 *
 * Gestiona la lógica CRUD para las Preguntas Frecuentes (FAQs).
 */
class FaqController
{
    private PDO $db;
    private Faq $faq;

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

    public function index(): void
    {
        if (!isset($_SESSION['user_id'])) {
            redirect('login');
        }

        $faqs = $this->faq->readAll()->fetchAll(PDO::FETCH_ASSOC);

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

    public function create(): void
    {
        if (!isset($_SESSION['user_id'])) {
            redirect('login');
        }

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

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // CLAVE: Guardamos los datos del POST para repoblar el formulario si hay un error
            $faqData = $_POST;
            $this->faq->question = $_POST['question'] ?? '';
            $this->faq->answer = $_POST['answer'] ?? '';

            if ($this->faq->create()) {
                $_SESSION['message'] = "¡FAQ creada exitosamente!";
                redirect('admin/faqs');
            } else {
                $error = "Falló al crear la FAQ.";
            }
        }

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

    public function edit(): void
    {
        if (!isset($_SESSION['user_id'])) {
            redirect('login');
        }

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

        if (!$this->faq->readOne()) {
            $_SESSION['error'] = "FAQ no encontrada.";
            redirect('admin/faqs');
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // CLAVE: Asegurarse de pasar el ID para la consulta de actualización
            $this->faq->id = $_POST['id'];
            $this->faq->question = $_POST['question'] ?? '';
            $this->faq->answer = $_POST['answer'] ?? '';

            if ($this->faq->update()) {
                $_SESSION['message'] = "¡FAQ actualizada exitosamente!";
                redirect('admin/faqs');
            } else {
                $error = "Falló al actualizar la FAQ.";
            }
        }

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

    public function delete(): void
    {
        if (!isset($_SESSION['user_id'])) {
            redirect('login');
        }

        // CLAVE: La eliminación segura se hace por POST
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->faq->id = $_POST['id'] ?? 0;
            if ($this->faq->delete()) {
                $_SESSION['message'] = "¡FAQ eliminada exitosamente!";
            } else {
                $_SESSION['error'] = "Falló al eliminar la FAQ.";
            }
        }
        redirect('admin/faqs');
    }

    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';
    }
}