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

/**
 * Parse JSON
 */
$data = json_decode(file_get_contents('php://input'), true);

if (
    empty($data['faq_id']) ||
    !filter_var($data['faq_id'], FILTER_VALIDATE_INT)
) {
    Response::error('Valid faq_id is required', 422);
}

if (empty($data['status'])) {
    Response::error('Status is required', 422);
}

$faqId  = (int) $data['faq_id'];
$status = trim($data['status']);

/**
 * Allowed statuses only
 */
$allowedStatuses = ['Active', 'InActive', 'Draft'];

if (!in_array($status, $allowedStatuses, true)) {
    Response::error('Invalid status value', 422);
}

/**
 * Role check — Admin & Super Admin only
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$role = $stmt->fetchColumn();

if (!in_array($role, ['Admin', 'Super Admin'], true)) {
    Response::error('You are not authorized to update FAQ status', 403);
}

/**
 * Check FAQ exists
 */
$stmt = $db->prepare("
    SELECT id, status
    FROM faqs
    WHERE id = :id
");
$stmt->execute(['id' => $faqId]);
$faq = $stmt->fetch();

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

/**
 * Prevent redundant updates
 */
if ($faq['status'] === $status) {
    Response::error('FAQ already has this status', 409);
}

/**
 * Update status only
 */
$stmt = $db->prepare("
    UPDATE faqs
    SET status = :status
    WHERE id = :id
");
$stmt->execute([
    'status' => $status,
    'id'     => $faqId
]);

Response::success('FAQ status updated successfully');
