<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin FAQ Controller
 *
 * CRUD operations for frequently asked questions.
 */
class AdminFaqController extends AdminController
{
    /**
     * List all FAQs.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query('SELECT * FROM `faqs` ORDER BY `sort_order` ASC, `created_at` DESC');
        $faqs = $stmt->fetchAll() ?: [];

        $this->adminView('faqs', [
            'title'       => 'Manage FAQs',
            'currentPage' => 'faqs',
            'faqs'        => $faqs,
            'editFaq'     => null,
        ]);
    }

    /**
     * Show the create FAQ form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function create(array $params = []): void
    {
        requireAdmin();

        $this->adminView('faqs', [
            'title'       => 'Add New FAQ',
            'currentPage' => 'faqs',
            'faqs'        => [],
            'editFaq'     => null,
            'showForm'    => true,
        ]);
    }

    /**
     * Store a new FAQ.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function store(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $question   = sanitize($_POST['question'] ?? '');
        $answer     = $_POST['answer'] ?? '';
        $category   = sanitize($_POST['category'] ?? '');
        $sortOrder  = (int) ($_POST['sort_order'] ?? 0);
        $showOnHome = isset($_POST['show_on_home']) ? 1 : 0;
        $active     = isset($_POST['active']) ? 1 : 0;

        if (empty($question) || empty($answer)) {
            flash('error', 'Question and answer are required.');
            redirect(BASE_PATH . '/admin/faqs/create');
        }

        $stmt = $this->db->prepare(
            'INSERT INTO `faqs` (`question`, `answer`, `category`, `sort_order`, `show_on_home`, `active`)
             VALUES (:question, :answer, :category, :sort_order, :show_on_home, :active)'
        );

        $stmt->execute([
            ':question'    => $question,
            ':answer'      => $answer,
            ':category'    => $category,
            ':sort_order'  => $sortOrder,
            ':show_on_home' => $showOnHome,
            ':active'      => $active,
        ]);

        flash('success', 'FAQ created successfully.');
        redirect(BASE_PATH . '/admin/faqs');
    }

    /**
     * Show the edit FAQ form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function edit(array $params = []): void
    {
        requireAdmin();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('SELECT * FROM `faqs` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $editFaq = $stmt->fetch() ?: null;

        if ($editFaq === null) {
            flash('error', 'FAQ not found.');
            redirect(BASE_PATH . '/admin/faqs');
        }

        $this->adminView('faqs', [
            'title'       => 'Edit FAQ',
            'currentPage' => 'faqs',
            'faqs'        => [],
            'editFaq'     => $editFaq,
            'showForm'    => true,
        ]);
    }

    /**
     * Update an existing FAQ.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $question   = sanitize($_POST['question'] ?? '');
        $answer     = $_POST['answer'] ?? '';
        $category   = sanitize($_POST['category'] ?? '');
        $sortOrder  = (int) ($_POST['sort_order'] ?? 0);
        $showOnHome = isset($_POST['show_on_home']) ? 1 : 0;
        $active     = isset($_POST['active']) ? 1 : 0;

        if (empty($question) || empty($answer)) {
            flash('error', 'Question and answer are required.');
            redirect(BASE_PATH . '/admin/faqs/' . $id . '/edit');
        }

        $stmt = $this->db->prepare(
            'UPDATE `faqs` SET `question` = :question, `answer` = :answer, `category` = :category,
             `sort_order` = :sort_order, `show_on_home` = :show_on_home, `active` = :active WHERE `id` = :id'
        );

        $stmt->execute([
            ':question'    => $question,
            ':answer'      => $answer,
            ':category'    => $category,
            ':sort_order'  => $sortOrder,
            ':show_on_home' => $showOnHome,
            ':active'      => $active,
            ':id'          => $id,
        ]);

        flash('success', 'FAQ updated successfully.');
        redirect(BASE_PATH . '/admin/faqs');
    }

    /**
     * Delete a FAQ.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('DELETE FROM `faqs` WHERE `id` = :id');
        $stmt->execute([':id' => $id]);

        if ($stmt->rowCount() > 0) {
            flash('success', 'FAQ deleted successfully.');
        } else {
            flash('warning', 'FAQ not found or already deleted.');
        }
        redirect(BASE_PATH . '/admin/faqs');
    }
}
