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

/**
 * Validate input
 */
$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);
}

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

/**
 * 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, ['Super Admin', 'Admin'], true)) {
    Response::error('You are not authorized to approve FAQs', 403);
}

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

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

if ($faq['approval_status'] === 'Approved') {
    Response::error('FAQ is already approved', 409);
}

/**
 * Approve FAQ
 */
$stmt = $db->prepare("
    UPDATE faqs
    SET
        approval_status = 'Approved',
        status = 'Active',
        published_at = NOW(),
        approved_by = :approved_by,
        approved_at = NOW(),
        rejected_by = NULL,
        rejected_at = NULL,
        rejection_reason = NULL
    WHERE id = :id
");
$stmt->execute([
    'approved_by' => $_SESSION['employee_id'],
    'id'          => $faqId
]);

Response::success('FAQ approved successfully');
