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

$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 — 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 ($role !== 'Super Admin') {
    Response::error('Only Super Admin can delete FAQs permanently', 403);
}

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

if (!$stmt->fetch()) {
    Response::error('FAQ not found', 404);
}

/**
 * Transaction
 */
$db->beginTransaction();

try {

    // Delete SEO
    $db->prepare("DELETE FROM faq_seo WHERE faq_id = :id")
       ->execute(['id' => $faqId]);

    // Delete category mapping
    $db->prepare("DELETE FROM faq_category_map WHERE faq_id = :id")
       ->execute(['id' => $faqId]);

    // Delete images records
    $db->prepare("DELETE FROM faq_images WHERE faq_id = :id")
       ->execute(['id' => $faqId]);

    // Delete FAQ
    $db->prepare("DELETE FROM faqs WHERE id = :id")
       ->execute(['id' => $faqId]);

    $db->commit();

} catch (Throwable $e) {
    $db->rollBack();
    Response::error('Failed to delete FAQ', 500);
}

/**
 * OPTIONAL: delete files physically (safe)
 */
$uploadDir = dirname(__DIR__, 3) . "/uploads/faqs/$faqId";
if (is_dir($uploadDir)) {
    array_map('unlink', glob("$uploadDir/*/*"));
    array_map('rmdir', glob("$uploadDir/*"));
    @rmdir($uploadDir);
}

Response::success('FAQ deleted permanently');
