<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

$faqId = (int)($_GET['id'] ?? 0);
if ($faqId <= 0) {
    Response::error('Invalid FAQ ID', 422);
}

/**
 * Fetch FAQ core
 */
$stmt = $db->prepare("
    SELECT
        f.*,
        img.image_path   AS featured_image,
        img.alt_text     AS featured_image_alt,
        img.caption      AS featured_image_caption
    FROM faqs f
    LEFT JOIN faq_images img
        ON img.faq_id = f.id
       AND img.is_primary = 1
       AND img.status = 'Active'
    WHERE f.id = :id
");
$stmt->execute(['id' => $faqId]);
$faq = $stmt->fetch();

if (!$faq) {
    Response::error('FAQ not found', 404);
}

/**
 * Categories
 */
$stmt = $db->prepare("
    SELECT c.id, c.name
    FROM faq_categories c
    JOIN faq_category_map m ON m.category_id = c.id
    WHERE m.faq_id = :id
");
$stmt->execute(['id' => $faqId]);
$categories = $stmt->fetchAll();

/**
 * SEO
 */
$stmt = $db->prepare("
    SELECT *
    FROM faq_seo
    WHERE faq_id = :id
");
$stmt->execute(['id' => $faqId]);
$seo = $stmt->fetch();

Response::success('FAQ fetched successfully', [
    'faq'        => $faq,
    'categories' => $categories,
    'seo'        => $seo
]);
