<?php 
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../includes/db.php';
include '../includes/header_admin.php'; 

// Fetch Stats
$totalBuses = $pdo->query("SELECT COUNT(*) FROM buses")->fetchColumn();
$totalDrivers = $pdo->query("SELECT COUNT(*) FROM drivers")->fetchColumn();
$totalStudents = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
?>

<div class="dashboard-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
    <h2>Live Bus Tracking</h2>
    <div class="user-info">
        Welcome, <strong><?= $_SESSION['admin_username'] ?? 'Admin' ?></strong>
    </div>
</div>

<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-value"><?= $totalBuses ?></div>
        <div class="stat-label">Total Buses</div>
    </div>
    <div class="stat-card" style="border-left-color: var(--secondary)">
        <div class="stat-value"><?= $totalDrivers ?></div>
        <div class="stat-label">Active Drivers</div>
    </div>
    <div class="stat-card" style="border-left-color: var(--accent)">
        <div class="stat-value"><?= $totalStudents ?></div>
        <div class="stat-label">Registered Students</div>
    </div>
</div>

<div class="card">
    <div id="map"></div>
</div>

<script>
    const map = L.map('map').setView([27.7172, 85.3240], 13); // Centered on Kathmandu as default

    L.tileLayer('https://{s}.tile.bootstrap.leafletjs.com/v1/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors'
    }).addTo(map);

    // Alternative: Use Standard OSM if above doesn't load
    L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

    let markers = {};

    async function updateMarkers() {
        try {
            const response = await fetch('../api/get_locations.php');
            const data = await response.json();
            
            if (data.success) {
                data.locations.forEach(bus => {
                    if (bus.latitude && bus.longitude) {
                        const pos = [bus.latitude, bus.longitude];
                        const popupContent = `
                            <strong>Bus: ${bus.bus_number} (${bus.route_name || 'No Route'})</strong><br>
                            Model: ${bus.model}<br>
                            Battery: ${bus.battery_level}%<br>
                            Last Update: ${new Date(bus.timestamp).toLocaleTimeString()}
                        `;

                        if (markers[bus.id]) {
                            markers[bus.id].setLatLng(pos).setPopupContent(popupContent);
                        } else {
                            const icon = L.divIcon({
                                className: 'custom-bus-icon',
                                html: '<div style="background: var(--primary); color: white; padding: 5px; border-radius: 50%; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border: 2px solid white; box-shadow: 0 0 10px rgba(0,0,0,0.2)"><i class="fas fa-bus"></i></div>',
                                iconSize: [30, 30]
                            });
                            markers[bus.id] = L.marker(pos, {icon: icon}).addTo(map).bindPopup(popupContent);
                        }
                    }
                });
            }
        } catch (err) {
            console.error('Error fetching locations:', err);
        }
    }

    // Initial load and periodic refresh
    updateMarkers();
    setInterval(updateMarkers, 5000);

</script>

<?php include '../includes/footer_admin.php'; ?>
