<?php
// Filename: booking/process.php
include_once '../config.php';

// Ensure user is logged in
requireLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_booking'])) {

    // 1. CSRF Security Check
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== ($_SESSION['csrf_token'] ?? '')) {
        die("Security Validation Failed (CSRF). Please go back and refresh the page.");
    }

    // 2. Retrieve & Sanitize Inputs
    $room_id = filter_var($_POST['room_id'], FILTER_SANITIZE_NUMBER_INT);
    $date    = $_POST['booking_date'];
    $start   = $_POST['start_time'];
    $end     = $_POST['end_time'];
    $purpose = trim(htmlspecialchars($_POST['purpose']));
    
    $user_id = $_SESSION['user_id'];
    $user_fullname = $_SESSION['full_name'];

    // Basic Validation
    if (empty($room_id) || empty($date) || empty($start) || empty($end) || empty($purpose)) {
        header("Location: index.php?date=$date&error=" . urlencode("Please fill in all required fields."));
        exit;
    }

    try {
        // 3. Double Check Availability (Prevent Race Conditions)
        $check_stmt = $pdo->prepare("SELECT COUNT(*) FROM bookings WHERE room_id = ? AND booking_date = ? AND status != 'rejected' AND (
            (start_time < ? AND end_time > ?) OR
            (start_time >= ? AND end_time <= ?)
        )");
        $check_stmt->execute([$room_id, $date, $end, $start, $start, $end]);
        
        if ($check_stmt->fetchColumn() > 0) {
            header("Location: index.php?date=$date&error=" . urlencode("Slot already taken! Please choose another time."));
            exit;
        }

        // 4. Insert Booking
        $sql = "INSERT INTO bookings (room_id, teacher_id, teacher_name, booking_date, start_time, end_time, purpose, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, 'pending')";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$room_id, $user_id, $user_fullname, $date, $start, $end, $purpose]);

        // =========================================================
        // --- NOTIFICATION SYSTEM START ---
        // =========================================================

        // A. Get Room Name for the message
        $room_stmt = $pdo->prepare("SELECT name FROM rooms WHERE id = ?");
        $room_stmt->execute([$room_id]);
        $room_name = $room_stmt->fetchColumn() ?: "Unknown Room";

        // B. Construct Messages
        // Bell Notification Message (Short)
        $bell_message = "New Booking: $room_name by $user_fullname on " . date('d M', strtotime($date));
        $link_url = "admin_bookings.php"; // Change this to your admin booking management page

        // Telegram Message (Detailed with HTML)
        $tg_message = "?? <b>New Booking Request</b>\n\n" .
                      "?? <b>Name:</b> " . $user_fullname . "\n" .
                      "?? <b>Room:</b> " . $room_name . "\n" .
                      "?? <b>Date:</b> " . date('d M Y', strtotime($date)) . "\n" .
                      "? <b>Time:</b> " . $start . " - " . $end . "\n" .
                      "?? <b>Purpose:</b> " . $purpose;

        // C. Fetch Admins (Users with 'admin' or 'admin_booking' role)
        // Using LIKE because roles might be stored as "teacher,admin"
        $admin_query = "SELECT id, telegram_chat_id FROM users 
                        WHERE role LIKE '%admin%' 
                           OR role LIKE '%admin_booking%' 
                           OR role LIKE '%principal%'"; // Optional: Include Principal
        $admins = $pdo->query($admin_query)->fetchAll(PDO::FETCH_ASSOC);

        // D. Loop through Admins and Send
        foreach ($admins as $admin) {
            
            // 1. Insert Bell Notification (Database)
            $notif_sql = "INSERT INTO notifications (user_id, message, link, type, is_read, created_at) 
                          VALUES (?, ?, ?, 'booking', 0, NOW())";
            $pdo->prepare($notif_sql)->execute([$admin['id'], $bell_message, $link_url]);

            // 2. Send Telegram Notification
            // Using the helper function from config.php. 
            // 'urgent' type bypasses holiday checks if you implemented that logic.
            if (!empty($admin['telegram_chat_id'])) {
                sendTelegram($tg_message, $admin['telegram_chat_id'], 'urgent');
            }
        }

        // =========================================================
        // --- NOTIFICATION SYSTEM END ---
        // =========================================================

        header("Location: index.php?date=$date&success=" . urlencode("Booking submitted successfully! Waiting for approval."));
        exit;

    } catch (PDOException $e) {
        header("Location: index.php?date=$date&error=" . urlencode("Database Error: " . $e->getMessage()));
        exit;
    }
} else {
    // Direct access fallback
    header("Location: index.php");
    exit;
}
?>