<?php
/**
 * Admin - Delete CMS Page
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(BASE_URL . 'admin/pages.php', 'error', 'Invalid request');
}

if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
    redirect(BASE_URL . 'admin/pages.php', 'error', 'Invalid security token');
}

$page_id = intval($_POST['page_id'] ?? 0);

if (!$page_id) {
    redirect(BASE_URL . 'admin/pages.php', 'error', 'Invalid page ID');
}

try {
    // Check if page exists
    $stmt = db()->prepare("SELECT title FROM pages WHERE id = ?");
    $stmt->execute([$page_id]);
    $page = $stmt->fetch();
    
    if (!$page) {
        redirect(BASE_URL . 'admin/pages.php', 'error', 'Page not found');
    }
    
    // Delete page
    $stmt = db()->prepare("DELETE FROM pages WHERE id = ?");
    $stmt->execute([$page_id]);
    
    // Log activity
    log_activity('page_deleted', "Deleted CMS page: {$page['title']}", $_SESSION['admin_id'], 'admin');
    
    redirect(BASE_URL . 'admin/pages.php', 'success', 'Page deleted successfully');
    
} catch (PDOException $e) {
    error_log("Delete page error: " . $e->getMessage());
    redirect(BASE_URL . 'admin/pages.php', 'error', 'Failed to delete page');
}
