<?php
declare(strict_types=1);

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

$db = Database::getInstance();

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

Validator::required($data, ['faq_id', 'reason']);

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

Validator::minLength($reason, 5, 'reason');

/**
 * 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 reject 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'] === 'Rejected') {
    Response::error('FAQ is already rejected', 409);
}

/**
 * Reject FAQ
 */
$stmt = $db->prepare("
    UPDATE faqs
    SET
        approval_status = 'Rejected',
        status = 'Draft',
        rejected_by = :rejected_by,
        rejected_at = NOW(),
        rejection_reason = :reason
    WHERE id = :id
");
$stmt->execute([
    'rejected_by' => $_SESSION['employee_id'],
    'reason'      => $reason,
    'id'          => $faqId
]);

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