<?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();

/**
 * Query params
 */
$context  = $_GET['context'] ?? 'backend'; // backend | frontend
$page     = max(1, (int)($_GET['page'] ?? 1));
$limit    = max(1, min(50, (int)($_GET['limit'] ?? 10)));
$offset   = ($page - 1) * $limit;

$categoryId     = $_GET['category_id'] ?? null;
$status         = $_GET['status'] ?? null;
$approvalStatus = $_GET['approval_status'] ?? null;
$search         = $_GET['search'] ?? null;

$where  = [];
$params = [];

/**
 * Frontend visibility rules
 */
if ($context === 'frontend') {
    $where[] = "f.status = 'Active'";
    $where[] = "f.approval_status = 'Approved'";
    $where[] = "f.published_at <= NOW()";
}

/**
 * Filters
 */
if ($categoryId && filter_var($categoryId, FILTER_VALIDATE_INT)) {
    $where[] = "f.id IN (
        SELECT faq_id FROM faq_category_map WHERE category_id = :category_id
    )";
    $params['category_id'] = (int)$categoryId;
}

if ($status) {
    $where[]          = "f.status = :status";
    $params['status'] = $status;
}

if ($approvalStatus) {
    $where[]                   = "f.approval_status = :approval_status";
    $params['approval_status'] = $approvalStatus;
}

if ($search) {
    $where[]          = "f.question LIKE :search";
    $params['search'] = '%' . trim($search) . '%';
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

/**
 * Count total
 */
$countSql = "SELECT COUNT(*) FROM faqs f $whereSql";
$stmt = $db->prepare($countSql);
$stmt->execute($params);
$total = (int)$stmt->fetchColumn();

/**
 * Fetch FAQs (ANSWER INCLUDED)
 */
$sql = "
SELECT
    f.id,
    f.question,
    f.slug,
    f.answer,
    f.status,
    f.approval_status,
    f.published_at,
    f.created_at,

    (
        SELECT image_path
        FROM faq_images
        WHERE faq_id = f.id AND status = 'Active'
        ORDER BY is_primary DESC
        LIMIT 1
    ) AS featured_image

FROM faqs f
$whereSql
ORDER BY f.created_at DESC
LIMIT :limit OFFSET :offset
";

$stmt = $db->prepare($sql);

foreach ($params as $key => $value) {
    $stmt->bindValue(':' . $key, $value);
}

$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

$stmt->execute();
$faqs = $stmt->fetchAll();

/**
 * Response
 */
Response::success('FAQs fetched successfully', [
    'list' => $faqs,
    'pagination' => [
        'total' => $total,
        'page'  => $page,
        'limit'=> $limit,
        'pages'=> (int)ceil($total / $limit)
    ]
]);
