<?php
// Filename: booking/admin/update_status.php
include '../../config.php';

// 1. SECURITY CHECK
requireLogin();
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'admin_booking']))) {
    die("Access Denied.");
}

// CSRF TOKEN VALIDATION (From URL for GET links)
$token = $_GET['token'] ?? ($_POST['csrf_token'] ?? '');
if (!hash_equals($_SESSION['csrf_token'], $token)) {
    die("Security Error: Invalid Token.");
}

// 2. INPUT VALIDATION
$id = isset($_GET['id']) ? (int)$_GET['id'] : (isset($_POST['id']) ? (int)$_POST['id'] : 0);
$action = $_GET['act'] ?? ($_POST['action'] ?? '');

if ($id <= 0 || !in_array($action, ['approve', 'reject'])) {
    die("Invalid Request parameters.");
}

// 3. REJECT LOGIC
if ($action === 'reject') {
    $pdo->prepare("UPDATE bookings SET status = 'rejected' WHERE id = ?")->execute([$id]);
    header("Location: manage.php?status=rejected&msg=rejected");
    exit();
}

// 4. APPROVE LOGIC (Overlap Check)
$stmt = $pdo->prepare("SELECT * FROM bookings WHERE id = ?");
$stmt->execute([$id]);
$current = $stmt->fetch();

if (!$current) die("Booking not found.");

// Check Overlap: (StartA < EndB) AND (EndA > StartB)
$stmt_chk = $pdo->prepare("
    SELECT teacher_name, start_time, end_time FROM bookings 
    WHERE room_id = ? 
    AND booking_date = ? 
    AND status = 'approved' 
    AND id != ? 
    AND (start_time < ? AND end_time > ?)
    LIMIT 1
");
$stmt_chk->execute([
    $current['room_id'], 
    $current['booking_date'], 
    $id, 
    $current['end_time'], 
    $current['start_time']
]);
$conflict = $stmt_chk->fetch();

if ($conflict) {
    $msg = "CONFLICT DETECTED! Room is already approved for " . $conflict['teacher_name'] . 
           " (" . date('H:i', strtotime($conflict['start_time'])) . "-" . date('H:i', strtotime($conflict['end_time'])) . ")";
    echo "<script>alert(".json_encode($msg)."); window.location.href='manage.php?status=pending';</script>";
    exit();
}

// 5. FINAL APPROVAL
$pdo->prepare("UPDATE bookings SET status = 'approved' WHERE id = ?")->execute([$id]);
header("Location: manage.php?status=pending&msg=approved");
exit();