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

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

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

$pageId = (int)$data['page_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 pages permanently', 403);
}

/**
 * Check page exists + system page protection
 */
$stmt = $db->prepare("
    SELECT id, is_system_page
    FROM pages
    WHERE id = :id
");
$stmt->execute(['id' => $pageId]);
$page = $stmt->fetch();

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

if ((int)$page['is_system_page'] === 1) {
    Response::error('System pages cannot be deleted', 403);
}

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

try {

    // Delete SEO
    $db->prepare("DELETE FROM page_seo WHERE page_id = :id")
       ->execute(['id' => $pageId]);

    // Delete images (DB)
    $db->prepare("DELETE FROM page_images WHERE page_id = :id")
       ->execute(['id' => $pageId]);

    // Delete page
    $db->prepare("DELETE FROM pages WHERE id = :id")
       ->execute(['id' => $pageId]);

    $db->commit();

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

/**
 * Delete image files from disk (safe cleanup)
 */
$uploadDir = dirname(__DIR__, 3) . "/uploads/pages/$pageId";

if (is_dir($uploadDir)) {
    foreach (glob($uploadDir . '/*/*') as $file) {
        @unlink($file);
    }
    foreach (glob($uploadDir . '/*') as $folder) {
        @rmdir($folder);
    }
    @rmdir($uploadDir);
}

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