<?php
// Filename: booking/admin/delete_booking.php
require_once '../../config.php';

// 1. SECURITY CHECK
requireLogin();
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'admin_booking']))) {
    die("Access Denied: You do not have permission to delete bookings.");
}

// 2. TOKEN VALIDATION (Matches the token in your link)
$token = $_GET['token'] ?? '';
if (empty($token) || !hash_equals($_SESSION['csrf_token'], $token)) {
    die("Security Error: Invalid or expired security token. Please refresh the manager and try again.");
}

// 3. INPUT VALIDATION
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    header("Location: manage.php?status=pending&msg=invalid_id");
    exit();
}

// 4. EXECUTE DELETE
try {
    // We check if the booking exists first (optional but good for debugging)
    $check = $pdo->prepare("SELECT id FROM bookings WHERE id = ?");
    $check->execute([$id]);
    
    if ($check->fetch()) {
        $stmt = $pdo->prepare("DELETE FROM bookings WHERE id = ?");
        $stmt->execute([$id]);
        
        // Redirect back with a success message
        header("Location: manage.php?status=pending&msg=deleted");
        exit();
    } else {
        die("Error: Booking record #$id not found in the database.");
    }
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}