<?php
// Filename: booking/includes/room_map_logic.php

function getRoomAvailability($pdo) {
    $now_date = date('Y-m-d');
    $now_time = date('H:i:s');

    // Fetch all active rooms
    $rooms = $pdo->query("SELECT * FROM rooms WHERE status = 'active' ORDER BY location, name ASC")->fetchAll();
    
    // Fetch currently active bookings
    $stmt = $pdo->prepare("SELECT room_id, teacher_name, start_time, end_time FROM bookings 
                           WHERE booking_date = ? AND status = 'approved' 
                           AND ? BETWEEN start_time AND end_time");
    $stmt->execute([$now_date, $now_time]);
    $active_bookings = $stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE);

    $map_data = [];
    foreach ($rooms as $r) {
        $loc = $r['location'] ?: 'General';
        $is_occupied = isset($active_bookings[$r['id']]);
        
        $map_data[$loc][] = [
            'id' => $r['id'],
            'name' => $r['name'],
            'type' => $r['type'],
            'capacity' => $r['capacity'],
            'occupied' => $is_occupied,
            'user' => $is_occupied ? $active_bookings[$r['id']]['teacher_name'] : null,
            'until' => $is_occupied ? date('H:i', strtotime($active_bookings[$r['id']]['end_time'])) : null
        ];
    }
    return $map_data;
}