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

// --- RESTORED: CSRF HELPERS ---
if (!function_exists('csrf_token')) {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    function csrf_token(): string {
        return $_SESSION['csrf_token'] ?? '';
    }
}

date_default_timezone_set('Asia/Kuala_Lumpur'); 

// --- 1. USER & DATE DETAILS ---
$user_id = $_SESSION['user_id'] ?? 0;
$full_name = $_SESSION['full_name'] ?? 'User';

$today_date = date('Y-m-d');
$selected_date = $_GET['date'] ?? $today_date;
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $selected_date)) { $selected_date = $today_date; }
$day_num = date('N', strtotime($selected_date)); 

// ==========================================
// --- MINI CALENDAR LOGIC START ---
// ==========================================
$cal_month = isset($_GET['cal_month']) ? intval($_GET['cal_month']) : date('n', strtotime($selected_date));
$cal_year  = isset($_GET['cal_year']) ? intval($_GET['cal_year']) : date('Y', strtotime($selected_date));

// Navigator Logic
$prev_m = $cal_month - 1; $prev_y = $cal_year;
if ($prev_m < 1) { $prev_m = 12; $prev_y--; }
$next_m = $cal_month + 1; $next_y = $cal_year;
if ($next_m > 12) { $next_m = 1; $next_y++; }

$calendar_data = [];

// A. Fetch Holidays
try {
    $h_stmt = $pdo->prepare("
        SELECT description, start_date, end_date, type 
        FROM school_holidays 
        WHERE (MONTH(start_date) = ? AND YEAR(start_date) = ?) 
           OR (MONTH(end_date) = ? AND YEAR(end_date) = ?)
    ");
    $h_stmt->execute([$cal_month, $cal_year, $cal_month, $cal_year]);
    
    while ($row = $h_stmt->fetch()) {
        $curr = strtotime($row['start_date']);
        $end  = strtotime($row['end_date']);
        while ($curr <= $end) {
            if (date('n', $curr) == $cal_month && date('Y', $curr) == $cal_year) {
                $d = date('j', $curr);
                $calendar_data[$d]['holiday'] = [
                    'type' => $row['type'],
                    'desc' => $row['description']
                ];
            }
            $curr = strtotime('+1 day', $curr);
        }
    }
} catch (Exception $e) { /* Ignore */ }

// Calculation for Grid
$cal_first_day = mktime(0, 0, 0, $cal_month, 1, $cal_year);
$cal_days_in_month = date('t', $cal_first_day);
$cal_month_name = date('F Y', $cal_first_day);
$cal_start_dow = date('N', $cal_first_day); 
$cal_offset = $cal_start_dow - 1; 
// ==========================================
// --- MINI CALENDAR LOGIC END ---
// ==========================================


// --- 2. FETCH SYSTEM SETTINGS ---
$s_start = getSetting('start_time', '07:30');
$s_dur   = intval(getSetting('slot_duration', 30));
$s_end   = getSetting("end_time_$day_num", '14:30'); 

if(empty($s_end) || strlen($s_end) < 4) $s_end = '14:30';
$s_recess_lower = intval(getSetting('recess_slot', 5));
$s_recess_upper = intval(getSetting('recess_slot_upper', 6));
$s_recess_dur   = intval(getSetting('recess_duration', 20));

// --- 3. GENERATE TIME SLOTS ---
$time_slots = [];
$curr_ts = strtotime($s_start);
$cutoff_ts = strtotime($s_end);
if ($cutoff_ts <= $curr_ts) { $cutoff_ts = $curr_ts + (420 * 60); }

$period_counter = 1;
while($curr_ts < $cutoff_ts) {
    $is_recess = ($period_counter == $s_recess_lower || $period_counter == $s_recess_upper);
    $duration = $is_recess ? $s_recess_dur : $s_dur;
    $end_ts = $curr_ts + ($duration * 60);
    if ($end_ts > $cutoff_ts) $end_ts = $cutoff_ts;

    $time_slots[$period_counter] = [
        'period' => $period_counter,
        'start'  => date('H:i', $curr_ts), 
        'end'    => date('H:i', $end_ts), 
        'is_recess' => $is_recess,
        'label'  => date('h:i', $curr_ts) 
    ];
    $curr_ts = $end_ts;
    $period_counter++;
    if($period_counter > 35) break; 
}

// --- 4. DATA FETCHING ---
$booked = [];
$stmt_b = $pdo->prepare("SELECT * FROM bookings WHERE booking_date = ? AND status != 'rejected'");
$stmt_b->execute([$selected_date]);
while($b = $stmt_b->fetch()) {
    $r_id = $b['room_id'];
    $db_start = substr($b['start_time'], 0, 5);
    $db_end   = substr($b['end_time'], 0, 5);
    foreach($time_slots as $p_num => $ts) {
        if($ts['start'] < $db_end && $ts['end'] > $db_start) {
            $booked[$r_id][$p_num] = ['status' => $b['status'], 'user' => $b['teacher_name'] ?? 'Booked'];
        }
    }
}

// --- 5. LIVE VIEW DATA ---
$active_stmt = $pdo->prepare("SELECT room_id, teacher_name, end_time FROM bookings WHERE booking_date = ? AND status = 'approved' AND ? BETWEEN start_time AND end_time");
$active_stmt->execute([$today_date, date('H:i:s')]);
$live_occupied = $active_stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE);

$rooms = $pdo->query("SELECT * FROM rooms WHERE status='active' ORDER BY location, name ASC")->fetchAll();
$grouped_map = [];
foreach ($rooms as $r) { $grouped_map[$r['location'] ?: 'General Block'][] = $r; }

$room_facs = [];
try {
    $fac_stmt = $pdo->query("SELECT rf.room_id, f.name, f.icon FROM room_facilities rf JOIN facilities f ON rf.facility_id = f.id WHERE f.status = 'active'");
    if($fac_stmt) $room_facs = $fac_stmt->fetchAll(PDO::FETCH_GROUP);
} catch (Exception $e) {}

function getNextWorkDay($date, $direction = '+1 day') {
    $new_date = strtotime($date . ' ' . $direction);
    if (date('N', $new_date) == 6) { $new_date = strtotime(date('Y-m-d', $new_date) . ($direction == '+1 day' ? ' +2 days' : ' -1 day')); }
    if (date('N', $new_date) == 7) { $new_date = strtotime(date('Y-m-d', $new_date) . ($direction == '+1 day' ? ' +1 day' : ' -2 days')); }
    return date('Y-m-d', $new_date);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Room Booking</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 120px; }
        .app-header { background: var(--primary-grad); padding: 18px 18px 70px 18px; border-radius: 0 0 30px 35px; color: white; }
        .floating-card { background: white; margin: -60px 18px 18px 18px; border-radius: 24px; padding: 15px; box-shadow: 0 15px 25px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .table-container { overflow: auto; max-height: 400px; background: white; border-radius: 15px; border: 1px solid #eee; }
        table thead th { position: sticky; top: 0; z-index: 11; background: #f8f9fa !important; border-bottom: 2px solid #eee; }
        table td:first-child { position: sticky; left: 0; background-color: #fff; z-index: 12; border-right: 2px solid #f1f5f9; min-width: 130px; font-weight: 600; }
        .slot { height: 40px; min-width: 65px; border-radius: 8px; display: flex; align-items: center; justify-content: center; cursor: pointer; border: 1px solid transparent; }
        .slot-free { background-color: #f0fdf4; color: #16a34a; border-color: #dcfce7; }
        .slot-booked { background-color: #fef2f2; color: #ef4444; border-color: #fee2e2; cursor: not-allowed; }
        .slot-recess-free { background-color: #f1f5f9; color: #64748b; }
        .map-room-box { background: white; border-radius: 12px; padding: 10px; border-left: 4px solid #10b981; margin-bottom: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.03); }
        .map-room-box.occupied { border-left-color: #ef4444; }

        /* MINI CALENDAR STYLES */
        .mini-cal-card { 
            background: white; border-radius: 16px; padding: 12px; margin-bottom: 15px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.02); border: 1px solid #f1f5f9; 
            touch-action: pan-y pinch-zoom; /* Allow vertical scroll but capture horizontal */
        }
        .mini-cal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
        .mini-cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; text-align: center; }
        .mini-day-name { font-size: 0.6rem; font-weight: 700; color: #94a3b8; text-transform: uppercase; margin-bottom: 2px; }
        .mini-day { 
            aspect-ratio: 1/1; border-radius: 8px; font-size: 0.8rem; font-weight: 600; color: #334155; 
            display: flex; flex-direction: column; align-items: center; justify-content: center; 
            position: relative; background: #f8fafc; cursor: pointer; transition: 0.2s;
        }
        .mini-day:hover { background: #e2e8f0; }
        .mini-day.is-selected { background: #334155; color: white; border: 2px solid #94a3b8; }
        .mini-holiday-national { background-color: #fee2e2; color: #ef4444; }
        .mini-holiday-term { background-color: #e0f2fe; color: #0ea5e9; }
        .mini-holiday-cuti_peristiwa { background-color: #ffedd5; color: #f97316; }
        .mini-holiday-cuti_ganti { background-color: #dcfce7; color: #10b981; }
        .mini-holiday-school_event { background-color: #f3e8ff; color: #8B5CF6; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
             <a href="../dashboard.php" class="text-white opacity-75 text-decoration-none"><i class="bi bi-arrow-left fs-4"></i></a>
             <div class="fw-bold">Room Booking</div>
             <div style="width:24px"></div>
        </div>
        <div class="d-flex align-items-center justify-content-between">
            <h6 class="mb-0 fw-bold"><?= htmlspecialchars($full_name) ?></h6>
            <div class="small opacity-75">Ends at: <?= $s_end ?></div>
        </div>
    </div>

    <div class="floating-card">
        
        <div class="mini-cal-card" id="swipeCal">
            <div class="mini-cal-header">
                <div class="small fw-bold text-uppercase text-muted"><i class="bi bi-calendar-check me-1"></i> Availability</div>
                <div class="d-flex align-items-center gap-2">
                    <a href="?cal_month=<?= $prev_m ?>&cal_year=<?= $prev_y ?>&date=<?= $selected_date ?>" id="btn-prev-month" class="btn btn-sm btn-light border rounded-circle py-0 px-1"><i class="bi bi-chevron-left small"></i></a>
                    
                    <span class="small fw-bold" style="min-width: 80px; text-align: center;"><?= $cal_month_name ?></span>
                    
                    <a href="?cal_month=<?= $next_m ?>&cal_year=<?= $next_y ?>&date=<?= $selected_date ?>" id="btn-next-month" class="btn btn-sm btn-light border rounded-circle py-0 px-1"><i class="bi bi-chevron-right small"></i></a>
                </div>
            </div>
            <div class="mini-cal-grid">
                <?php foreach(['M','T','W','T','F','S','S'] as $dn): ?><div class="mini-day-name"><?= $dn ?></div><?php endforeach; ?>
                <?php for($i=0; $i<$cal_offset; $i++): ?><div class="mini-day" style="background:transparent; cursor:default;"></div><?php endfor; ?>
                <?php for($d=1; $d<=$cal_days_in_month; $d++): 
                    $data = $calendar_data[$d] ?? [];
                    $is_holiday = isset($data['holiday']);
                    
                    $cell_date_str = sprintf("%04d-%02d-%02d", $cal_year, $cal_month, $d);
                    $is_selected = ($cell_date_str === $selected_date);
                    
                    $classes = "mini-day";
                    if ($is_holiday) $classes .= " mini-holiday-" . $data['holiday']['type'];
                    if ($is_selected) $classes .= " is-selected";
                    
                    $tooltip = ($is_holiday ? $data['holiday']['desc'] : "Available");
                ?>
                    <a href="?date=<?= $cell_date_str ?>&cal_month=<?= $cal_month ?>&cal_year=<?= $cal_year ?>" class="text-decoration-none">
                        <div class="<?= $classes ?>" title="<?= htmlspecialchars($tooltip) ?>" data-bs-toggle="tooltip">
                            <?= $d ?>
                        </div>
                    </a>
                <?php endfor; ?>
            </div>
        </div>
        <div class="mb-3">
             <button class="btn btn-dark w-100 rounded-pill py-2 fw-bold" data-bs-toggle="modal" data-bs-target="#floorPlanModal">
                <i class="bi bi-map-fill me-2 text-warning"></i> VIEW LIVE MAP
             </button>
        </div>
        
        <form method="GET" class="d-flex justify-content-between align-items-center bg-light rounded-pill p-1 border">
            <a href="?date=<?= getNextWorkDay($selected_date, '-1 day') ?>" class="btn btn-white rounded-circle shadow-sm"><i class="bi bi-chevron-left"></i></a>
            <div class="fw-bold text-dark small">
                <?= date('l, d M Y', strtotime($selected_date)) ?>
            </div>
            <a href="?date=<?= getNextWorkDay($selected_date, '+1 day') ?>" class="btn btn-white rounded-circle shadow-sm"><i class="bi bi-chevron-right"></i></a>
        </form>
    </div>

    <div class="px-3">
        <div class="table-container shadow-sm">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th class="ps-3">Room</th>
                        <?php foreach($time_slots as $ts): ?>
                            <th class="text-center small">#<?= $ts['period'] ?><br><?= $ts['label'] ?></th>
                        <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($rooms as $room): ?>
                    <tr>
                        <td class="ps-3">
                            <div class="small fw-bold"><?= htmlspecialchars($room['name']) ?></div>
                            <div class="text-muted" style="font-size:0.6rem"><?= htmlspecialchars($room['capacity'] ?? '0') ?> Pax • <?= htmlspecialchars($room['type'] ?? 'Room') ?></div>
                        </td>
                        <?php foreach($time_slots as $p_num => $ts): ?>
                            <td>
                                <?php if(isset($booked[$room['id']][$p_num])): ?>
                                    <div class="slot slot-booked"><i class="bi bi-lock-fill"></i></div>
                                <?php else: ?>
                                    <div class="slot <?= $ts['is_recess'] ? 'slot-recess-free' : 'slot-free' ?>" 
                                         onclick="openModal('<?= $room['id'] ?>', '<?= htmlspecialchars($room['name'], ENT_QUOTES) ?>', '<?= $ts['start'] ?>')">
                                        <i class="bi <?= $ts['is_recess'] ? 'bi-cup-hot' : 'bi-plus' ?>"></i>
                                    </div>
                                <?php endif; ?>
                            </td>
                        <?php endforeach; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="container mt-4 px-3">
        <div class="row g-2">
            <div class="col-6">
                <a href="view_schedule.php" class="btn btn-light w-100 shadow-sm text-primary py-2 fw-bold" style="border-radius:40px; font-size:0.85rem;">
                    <i class="bi bi-list-ul me-1"></i> Daily List
                </a>
            </div>
            <div class="col-6">
                <a href="my_bookings.php" class="btn btn-primary w-100 shadow-sm py-2 fw-bold" style="border-radius:40px; font-size:0.85rem;">
                    <i class="bi bi-calendar-check me-1"></i> My Bookings
                </a>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="floorPlanModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered mx-2">
            <div class="modal-content border-0 shadow-lg" style="border-radius: 24px;">
                <div class="modal-header border-0 pb-0"><h6 class="fw-bold mb-0">Live Availability</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body p-3">
                    <div style="max-height: 60vh; overflow-y: auto;">
                        <?php foreach($grouped_map as $block => $mrooms): ?>
                            <div class="mb-3">
                                <div class="fw-bold text-muted small mb-2 text-uppercase" style="font-size: 0.6rem;"><?= htmlspecialchars($block) ?></div>
                                <div class="row g-2">
                                    <?php foreach($mrooms as $rm): 
                                        $is_busy = isset($live_occupied[$rm['id']]);
                                        $occ = $is_busy ? $live_occupied[$rm['id']] : null;
                                    ?>
                                        <div class="col-6">
                                            <div class="map-room-box <?= $is_busy ? 'occupied' : '' ?>">
                                                <div class="fw-bold text-truncate pe-1" style="font-size: 0.75rem;"><?= htmlspecialchars($rm['name']) ?></div>
                                                <div class="small <?= $is_busy ? 'text-danger' : 'text-success' ?> fw-bold">
                                                    <?= $is_busy ? 'BUSY' : 'FREE' ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="bookingModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered px-3">
            <div class="modal-content border-0 rounded-4 shadow">
                <form action="process.php" method="POST">
                    <div class="modal-body p-4">
                        <h5 class="fw-bold mb-1">Book <span id="mRoomName" class="text-primary"></span></h5>
                        <div id="mFacList" class="mb-3 d-flex flex-wrap gap-1"></div>
                        
                        <input type="hidden" name="room_id" id="mRoomId">
                        <input type="hidden" name="booking_date" value="<?= htmlspecialchars($selected_date) ?>">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token()) ?>">
                        
                        <div class="row g-2 mb-3">
                            <div class="col-6"><label class="small text-muted">Start</label><input type="time" name="start_time" id="mStart" class="form-control" readonly></div>
                            <div class="col-6"><label class="small text-muted">Book Until</label><select name="end_time" id="mEndSelect" class="form-select fw-bold"></select></div>
                        </div>
                        <div class="mb-4"><label class="small text-muted">Purpose</label><textarea name="purpose" class="form-control" required placeholder="Workshop, Meeting..."></textarea></div>
                        <button type="submit" name="submit_booking" class="btn btn-primary w-100 rounded-pill py-3 fw-bold">Confirm Booking</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const allSlots = <?= json_encode(array_values($time_slots)) ?>;
        const roomFacs = <?= json_encode($room_facs) ?>;

        function openModal(id, name, start) {
            document.getElementById('mRoomId').value = id;
            document.getElementById('mRoomName').innerText = name;
            document.getElementById('mStart').value = start;

            const endSelect = document.getElementById('mEndSelect');
            endSelect.innerHTML = '';
            const startIdx = allSlots.findIndex(s => s.start === start);
            
            if (startIdx !== -1) {
                for (let i = startIdx; i < allSlots.length; i++) {
                    const slot = allSlots[i];
                    const opt = document.createElement('option');
                    opt.value = slot.end;
                    const count = (i - startIdx) + 1;
                    opt.text = `${slot.end} (${count} period${count > 1 ? 's' : ''})`;
                    endSelect.appendChild(opt);
                }
            }

            const facContainer = document.getElementById('mFacList');
            facContainer.innerHTML = '';
            if(roomFacs[id]) {
                roomFacs[id].forEach(f => {
                    facContainer.innerHTML += `<span class="badge bg-light text-secondary border fw-normal" style="font-size:0.6rem"><i class="bi ${f.icon} me-1"></i>${f.name}</span>`;
                });
            }
            new bootstrap.Modal(document.getElementById('bookingModal')).show();
        }
        
        // Tooltip initialization
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
          return new bootstrap.Tooltip(tooltipTriggerEl)
        });

        // --- SWIPE GESTURE LOGIC FOR MINI CALENDAR ---
        const calElement = document.getElementById('swipeCal');
        let touchStartX = 0;
        let touchStartY = 0;

        if(calElement){
            calElement.addEventListener('touchstart', function(e) {
                touchStartX = e.changedTouches[0].screenX;
                touchStartY = e.changedTouches[0].screenY;
            }, {passive: true});

            calElement.addEventListener('touchend', function(e) {
                let touchEndX = e.changedTouches[0].screenX;
                let touchEndY = e.changedTouches[0].screenY;
                handleSwipe(touchStartX, touchEndX, touchStartY, touchEndY);
            }, {passive: true});
        }

        function handleSwipe(sX, eX, sY, eY) {
            const xDiff = eX - sX;
            const yDiff = eY - sY;
            
            // Logic: Horizontal swipe must be significantly larger than vertical movement
            // Threshold: 50px
            if (Math.abs(xDiff) > Math.abs(yDiff) + 30 && Math.abs(xDiff) > 50) {
                if (xDiff > 0) {
                    // Right swipe -> Previous Month
                    document.getElementById('btn-prev-month')?.click();
                } else {
                    // Left swipe -> Next Month
                    document.getElementById('btn-next-month')?.click();
                }
            }
        }
    </script>
    <?php include '../menu.php'; ?>
</body>
</html>