<?php
session_start();
require_once 'db.php';

if (isset($_GET['logout'])) {
    session_unset();
    session_destroy();
    header('Location: admin.php');
    exit;
}

$isAdmin = false;
$message = '';
$messageType = '';

if (isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $stmt = $pdo->prepare("SELECT * FROM `imators-users` WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['admin'] = true;
        $_SESSION['admin_id'] = $user['id'];
        $_SESSION['admin_role'] = $user['role'];
        $_SESSION['admin_username'] = $user['username'];
        header('Location: admin.php');
        exit;
    } else {
        $message = 'Invalid credentials';
        $messageType = 'error';
    }
}

if (isset($_SESSION['admin']) && $_SESSION['admin'] === true) {
    $isAdmin = true;
}

if ($isAdmin && isset($_POST['stop_billboard'])) {
    $serial = $_POST['serial'];
    $stopMessage = $_POST['stop_message'];
    
    $stmt = $pdo->prepare("UPDATE `imators-systems-billboard` SET status = 'stopped', stop_message = ? WHERE serial = ?");
    $stmt->execute([$stopMessage, $serial]);
    
    $message = 'Billboard stopped successfully';
    $messageType = 'success';
    
    file_get_contents("https://imators.systems/video/inter/broadcast.php?serial=$serial&status=stopped&message=" . urlencode($stopMessage));
}

if ($isAdmin && isset($_POST['restart_billboard'])) {
    $serial = $_POST['serial'];
    
    $stmt = $pdo->prepare("UPDATE `imators-systems-billboard` SET status = 'active', stop_message = NULL WHERE serial = ?");
    $stmt->execute([$serial]);
    
    $message = 'Billboard restarted successfully';
    $messageType = 'success';
    
    file_get_contents("https://imators.systems/video/inter/broadcast.php?serial=$serial&status=active");
}

$billboards = [];
if ($isAdmin) {
    $stmt = $pdo->query("SELECT * FROM `imators-systems-billboard` ORDER BY last_seen DESC");
    $billboards = $stmt->fetchAll();
    
    foreach ($billboards as &$billboard) {
        $config = json_decode($billboard['config'], true);
        $billboard['latitude'] = $config['location']['latitude'] ?? 0;
        $billboard['longitude'] = $config['location']['longitude'] ?? 0;
        
        $lastSeen = new DateTime($billboard['last_seen']);
        $now = new DateTime();
        $diff = $now->diff($lastSeen);
        
        if ($diff->days > 0) {
            $billboard['connection_status'] = 'offline';
        } elseif ($diff->h > 0) {
            $billboard['connection_status'] = 'inactive';
        } else {
            $billboard['connection_status'] = 'online';
        }
    }
}

$stats = [];
if ($isAdmin) {
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM `imators-systems-billboard`");
    $stats['total_billboards'] = $stmt->fetchColumn();
    
    $stmt = $pdo->query("SELECT COUNT(*) as online FROM `imators-systems-billboard` WHERE last_seen > DATE_SUB(NOW(), INTERVAL 1 HOUR)");
    $stats['online_billboards'] = $stmt->fetchColumn();
    
    $stmt = $pdo->query("SELECT COUNT(*) as stopped FROM `imators-systems-billboard` WHERE status = 'stopped'");
    $stats['stopped_billboards'] = $stmt->fetchColumn();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Imators Systems - Administration</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet" />
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        .marker-icon {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            border: 2px solid white;
        }
        .marker-green { background-color: #10B981; }
        .marker-orange { background-color: #F59E0B; }
        .marker-red { background-color: #EF4444; }
        
        .modal {
            z-index: 9999;
        }
        
        .modal-open {
            overflow: hidden;
        }
    </style>
</head>
<body class="bg-gray-100 text-gray-900 min-h-screen flex flex-col">
    <?php if (!$isAdmin): ?>
    <div class="min-h-screen flex items-center justify-center p-6 bg-gradient-to-br from-blue-900 to-gray-900">
        <div class="bg-white rounded-xl shadow-xl max-w-md w-full overflow-hidden">
            <div class="bg-gradient-to-r from-blue-600 to-indigo-600 p-6">
                <div class="flex items-center justify-center">
                    <img src="https://cdn.imators.com/logo.png" alt="Imators Logo" class="w-12 h-12 mr-3">
                    <h1 class="text-xl font-bold text-white">Imators Systems</h1>
                </div>
            </div>
            
            <div class="p-6">
                <h2 class="text-xl font-semibold mb-6 text-center text-gray-800">Admin Login</h2>
                
                <?php if (!empty($message) && $messageType === 'error'): ?>
                <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded">
                    <p><?php echo htmlspecialchars($message); ?></p>
                </div>
                <?php endif; ?>
                
                <form method="POST" action="" class="space-y-4">
                    <div>
                        <label for="username" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
                        <input type="text" name="username" id="username" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                        <input type="password" name="password" id="password" required class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    </div>
                    <button type="submit" name="login" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition duration-150 shadow-sm">
                        Login
                    </button>
                </form>
            </div>
        </div>
    </div>
    <?php else: ?>
    <div class="flex flex-col lg:flex-row min-h-screen overflow-hidden">
        <div class="bg-indigo-800 text-white w-64 flex-shrink-0 hidden lg:block">
            <div class="p-6">
                <div class="flex items-center">
                    <img src="https://cdn.imators.com/logo.png" alt="Imators Logo" class="w-10 h-10 mr-3">
                    <h1 class="text-xl font-semibold">Imators Systems</h1>
                </div>
            </div>
            <nav class="mt-6">
                <div class="px-4 py-2 text-xs uppercase tracking-wider text-indigo-400">Main</div>
                <a href="#dashboard" class="block py-2 px-4 text-white bg-indigo-900 border-l-4 border-white">Dashboard</a>
                <a href="#billboards" class="block py-2 px-4 text-white hover:bg-indigo-700">Billboards</a>
                
                <div class="px-4 py-2 mt-6 text-xs uppercase tracking-wider text-indigo-400">Account</div>
                <a href="?logout=1" class="block py-2 px-4 text-white hover:bg-indigo-700">Logout</a>
            </nav>
        </div>
        
        <div class="flex-1 flex flex-col overflow-hidden">
            <header class="bg-white shadow-sm">
                <div class="flex items-center justify-between p-4">
                    <button id="mobile-menu-button" class="lg:hidden text-gray-600 focus:outline-none">
                        <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
                        </svg>
                    </button>
                    
                    <div class="flex items-center lg:hidden ml-2">
                        <img src="https://cdn.imators.com/logo.png" alt="Imators Logo" class="w-8 h-8 mr-2">
                        <h1 class="text-lg font-semibold">Imators Systems</h1>
                    </div>
                    
                    <div class="flex items-center">
                        <span class="text-sm mr-4"><?php echo htmlspecialchars($_SESSION['admin_username']); ?></span>
                        <a href="?logout=1" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-3 py-1 rounded-lg text-sm">Logout</a>
                    </div>
                </div>
            </header>
            
            <div id="mobile-menu" class="lg:hidden bg-indigo-800 text-white hidden">
                <nav class="p-4">
                    <a href="#dashboard" class="block py-2 px-4 text-white hover:bg-indigo-700 rounded">Dashboard</a>
                    <a href="#billboards" class="block py-2 px-4 text-white hover:bg-indigo-700 rounded">Billboards</a>
                    <a href="?logout=1" class="block py-2 px-4 text-white hover:bg-indigo-700 rounded">Logout</a>
                </nav>
            </div>
            
            <main class="flex-1 overflow-y-auto p-4 md:p-6 bg-gray-100">
                <?php if (!empty($message)): ?>
                <div class="bg-<?php echo $messageType === 'success' ? 'green' : 'red'; ?>-100 border-l-4 border-<?php echo $messageType === 'success' ? 'green' : 'red'; ?>-500 text-<?php echo $messageType === 'success' ? 'green' : 'red'; ?>-700 p-4 mb-6 rounded">
                    <p><?php echo htmlspecialchars($message); ?></p>
                </div>
                <?php endif; ?>
                
                <section id="dashboard" class="mb-8">
                    <h2 class="text-2xl font-bold mb-6">Dashboard</h2>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-6 mb-6">
                        <div class="bg-white rounded-xl p-6 shadow-sm">
                            <div class="flex items-center">
                                <div class="p-3 bg-blue-100 rounded-full">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                                    </svg>
                                </div>
                                <div class="ml-4">
                                    <h3 class="text-gray-500 text-sm">Total Billboards</h3>
                                    <p class="text-2xl font-semibold text-gray-800 dashboard-stat" data-stat-key="total_billboards"><?php echo $stats['total_billboards']; ?></p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-xl p-6 shadow-sm">
                            <div class="flex items-center">
                                <div class="p-3 bg-green-100 rounded-full">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01" />
                                    </svg>
                                </div>
                                <div class="ml-4">
                                    <h3 class="text-gray-500 text-sm">Online Billboards</h3>
                                    <p class="text-2xl font-semibold text-gray-800 dashboard-stat" data-stat-key="online_billboards"><?php echo $stats['online_billboards']; ?></p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-white rounded-xl p-6 shadow-sm">
                            <div class="flex items-center">
                                <div class="p-3 bg-red-100 rounded-full">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                                    </svg>
                                </div>
                                <div class="ml-4">
                                    <h3 class="text-gray-500 text-sm">Stopped Billboards</h3>
                                    <p class="text-2xl font-semibold text-gray-800 dashboard-stat" data-stat-key="stopped_billboards"><?php echo $stats['stopped_billboards']; ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white rounded-xl shadow-sm overflow-hidden mb-6">
                        <div class="p-4 border-b border-gray-200">
                            <h3 class="text-lg font-semibold">Billboard Map</h3>
                        </div>
                        <div id="map" class="h-64 md:h-96"></div>
                    </div>
                </section>
                
                <section id="billboards" class="mb-8">
                    <h2 class="text-2xl font-bold mb-6">Billboard Management</h2>
                    
                    <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                        <div class="p-4 border-b border-gray-200">
                            <h3 class="text-lg font-semibold">All Billboards</h3>
                        </div>
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th scope="col" class="px-4 md:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Serial Number</th>
                                        <th scope="col" class="px-4 md:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                        <th scope="col" class="px-4 md:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Connection</th>
                                        <th scope="col" class="px-4 md:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider hidden md:table-cell">Last Seen</th>
                                        <th scope="col" class="px-4 md:px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                                    </tr>
                                </thead>
                                <tbody class="bg-white divide-y divide-gray-200">
                                    <?php foreach ($billboards as $billboard): ?>
                                    <tr data-serial="<?php echo htmlspecialchars($billboard['serial']); ?>">
                                        <td class="px-4 md:px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($billboard['serial']); ?></td>
                                        <td class="px-4 md:px-6 py-4 whitespace-nowrap status-cell">
                                            <?php if ($billboard['status'] === 'active'): ?>
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Active</span>
                                            <?php else: ?>
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Stopped</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-4 md:px-6 py-4 whitespace-nowrap connection-cell">
                                            <?php if ($billboard['connection_status'] === 'online'): ?>
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Online</span>
                                            <?php elseif ($billboard['connection_status'] === 'inactive'): ?>
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">Inactive</span>
                                            <?php else: ?>
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Offline</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-4 md:px-6 py-4 whitespace-nowrap text-sm text-gray-500 hidden md:table-cell last-seen-cell"><?php echo htmlspecialchars($billboard['last_seen']); ?></td>
                                        <td class="px-4 md:px-6 py-4 whitespace-nowrap text-sm font-medium actions-cell">
                                            <?php if ($billboard['status'] === 'active'): ?>
                                            <button type="button" onclick="showStopModal('<?php echo htmlspecialchars($billboard['serial']); ?>')" class="text-red-600 hover:text-red-900 mr-2">Stop</button>
                                            <?php else: ?>
                                            <form method="POST" action="" class="inline-block">
                                                <input type="hidden" name="serial" value="<?php echo htmlspecialchars($billboard['serial']); ?>">
                                                <button type="submit" name="restart_billboard" class="text-green-600 hover:text-green-900">Restart</button>
                                            </form>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </section>
            </main>
        </div>
    </div>
    
    <div id="stopModal" class="modal fixed inset-0 hidden z-50">
        <div class="absolute inset-0 bg-black bg-opacity-50" id="stopModalOverlay"></div>
        <div class="relative min-h-screen flex items-center justify-center p-4">
            <div class="bg-white p-6 rounded-xl shadow-lg max-w-md w-full relative">
                <button type="button" onclick="hideStopModal()" class="absolute top-3 right-3 text-gray-400 hover:text-gray-500">
                    <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
                <h3 class="text-xl font-semibold mb-4 text-gray-900 pr-8">Stop Billboard</h3>
                <form method="POST" action="" id="stopForm">
                    <input type="hidden" name="serial" id="stopModalSerial">
                    <div class="mb-4">
                        <label for="stop_message" class="block text-sm font-medium text-gray-700 mb-1">Stop Message</label>
                        <textarea name="stop_message" id="stop_message" rows="3" class="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent" placeholder="Message to display on the billboard">This billboard has been stopped by the administrator.</textarea>
                    </div>
                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="hideStopModal()" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-4 py-2 rounded-lg">Cancel</button>
                        <button type="submit" name="stop_billboard" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg">Confirm Stop</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        const mobileMenuButton = document.getElementById('mobile-menu-button');
        const mobileMenu = document.getElementById('mobile-menu');
        
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.toggle('hidden');
        });
        
        document.querySelectorAll('#mobile-menu a').forEach(link => {
            link.addEventListener('click', () => {
                mobileMenu.classList.add('hidden');
            });
        });
        
        const map = L.map('map').setView([51.5074, -0.1278], 5);
        
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
        }).addTo(map);
        
        const billboards = <?php echo json_encode($billboards); ?>;
        const markers = [];
        
        billboards.forEach(billboard => {
            if (billboard.latitude && billboard.longitude) {
                let markerColor;
                
                if (billboard.status === 'active') {
                    if (billboard.connection_status === 'online') {
                        markerColor = 'green';
                    } else if (billboard.connection_status === 'inactive') {
                        markerColor = 'orange';
                    } else {
                        markerColor = 'red';
                    }
                } else {
                    markerColor = 'red';
                }
                
                const markerHtml = `<div class="marker-icon marker-${markerColor}"></div>`;
                
                const customIcon = L.divIcon({
                    html: markerHtml,
                    className: '',
                    iconSize: [12, 12]
                });
                
                const marker = L.marker([billboard.latitude, billboard.longitude], {
                    icon: customIcon
                }).addTo(map);
                
                const statusText = billboard.status === 'active' ? 'Active' : 'Stopped';
                const connectionText = {
                    'online': 'Online',
                    'inactive': 'Inactive',
                    'offline': 'Offline'
                }[billboard.connection_status];
                
                marker.bindPopup(`
                    <div style="color: black; min-width: 200px;">
                        <div style="font-weight: bold; margin-bottom: 5px;">${billboard.serial}</div>
                        <div style="margin-bottom: 3px;"><strong>Status:</strong> ${statusText}</div>
                        <div style="margin-bottom: 3px;"><strong>Connection:</strong> ${connectionText}</div>
                        <div style="margin-bottom: 5px;"><strong>Last seen:</strong><br>${billboard.last_seen}</div>
                        <div style="display: flex; justify-center; gap: 5px; margin-top: 8px;">
                            ${billboard.status === 'active' ? 
                                `<button onclick="showStopModal('${billboard.serial}')" style="background-color: #EF4444; color: white; padding: 4px 8px; border-radius: 6px; font-size: 12px;">Stop</button>` : 
                                `<form method="POST" action="">
                                    <input type="hidden" name="serial" value="${billboard.serial}">
                                    <button type="submit" name="restart_billboard" style="background-color: #10B981; color: white; padding: 4px 8px; border-radius: 6px; font-size: 12px;">Restart</button>
                                </form>`
                            }
                        </div>
                    </div>
                `, { closeButton: true });
                
                markers.push(marker);
            }
        });
        
        if (markers.length > 0) {
            const group = new L.featureGroup(markers);
            map.fitBounds(group.getBounds().pad(0.1));
        }
        
        window.addEventListener('resize', () => {
            map.invalidateSize();
        });
        
        const stopModal = document.getElementById('stopModal');
        const stopModalOverlay = document.getElementById('stopModalOverlay');
        
        function showStopModal(serial) {
            document.getElementById('stopModalSerial').value = serial;
            stopModal.classList.remove('hidden');
            document.body.classList.add('modal-open');
        }
        
        function hideStopModal() {
            stopModal.classList.add('hidden');
            document.body.classList.remove('modal-open');
        }
        
        stopModalOverlay.addEventListener('click', hideStopModal);
        
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && !stopModal.classList.contains('hidden')) {
                hideStopModal();
            }
        });
        
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                
                const targetId = this.getAttribute('href');
                const targetElement = document.querySelector(targetId);
                
                if (targetElement) {
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                    
                    history.pushState(null, null, targetId);
                }
            });
        });
        
        function refreshData() {
            fetch('admin-api.php?action=get_billboards', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.querySelectorAll('.dashboard-stat').forEach(stat => {
                        const key = stat.getAttribute('data-stat-key');
                        if (data.stats[key]) {
                            stat.textContent = data.stats[key];
                        }
                    });
                    
                    data.billboards.forEach(billboard => {
                        const row = document.querySelector(`tr[data-serial="${billboard.serial}"]`);
                        if (row) {
                            const statusCell = row.querySelector('.status-cell');
                            if (statusCell) {
                                statusCell.innerHTML = billboard.status === 'active' 
                                    ? '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Active</span>'
                                    : '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Stopped</span>';
                            }
                            
                            const connectionCell = row.querySelector('.connection-cell');
                            if (connectionCell) {
                                let connectionHTML = '';
                                if (billboard.connection_status === 'online') {
                                    connectionHTML = '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Online</span>';
                                } else if (billboard.connection_status === 'inactive') {
                                    connectionHTML = '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">Inactive</span>';
                                } else {
                                    connectionHTML = '<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Offline</span>';
                                }
                                connectionCell.innerHTML = connectionHTML;
                            }
                            
                            const lastSeenCell = row.querySelector('.last-seen-cell');
                            if (lastSeenCell) {
                                lastSeenCell.textContent = billboard.last_seen;
                            }
                            
                            const actionsCell = row.querySelector('.actions-cell');
                            if (actionsCell) {
                                if (billboard.status === 'active') {
                                    actionsCell.innerHTML = `<button type="button" onclick="showStopModal('${billboard.serial}')" class="text-red-600 hover:text-red-900 mr-2">Stop</button>`;
                                } else {
                                    actionsCell.innerHTML = `
                                        <form method="POST" action="" class="inline-block">
                                            <input type="hidden" name="serial" value="${billboard.serial}">
                                            <button type="submit" name="restart_billboard" class="text-green-600 hover:text-green-900">Restart</button>
                                        </form>
                                    `;
                                }
                            }
                        }
                    });
                    
                    updateMapMarkers(data.billboards);
                }
            })
            .catch(error => console.error('Error refreshing data:', error));
        }
        
        function updateMapMarkers(billboards) {
            markers.forEach(marker => map.removeLayer(marker));
            markers.length = 0;
            
            billboards.forEach(billboard => {
                if (billboard.latitude && billboard.longitude) {
                    let markerColor;
                    
                    if (billboard.status === 'active') {
                        if (billboard.connection_status === 'online') {
                            markerColor = 'green';
                        } else if (billboard.connection_status === 'inactive') {
                            markerColor = 'orange';
                        } else {
                            markerColor = 'red';
                        }
                    } else {
                        markerColor = 'red';
                    }
                    
                    const markerHtml = `<div class="marker-icon marker-${markerColor}"></div>`;
                    
                    const customIcon = L.divIcon({
                        html: markerHtml,
                        className: '',
                        iconSize: [12, 12]
                    });
                    
                    const marker = L.marker([billboard.latitude, billboard.longitude], {
                        icon: customIcon
                    }).addTo(map);
                    
                    const statusText = billboard.status === 'active' ? 'Active' : 'Stopped';
                    const connectionText = {
                        'online': 'Online',
                        'inactive': 'Inactive',
                        'offline': 'Offline'
                    }[billboard.connection_status];
                    
                    marker.bindPopup(`
                        <div style="color: black; min-width: 200px;">
                            <div style="font-weight: bold; margin-bottom: 5px;">${billboard.serial}</div>
                            <div style="margin-bottom: 3px;"><strong>Status:</strong> ${statusText}</div>
                            <div style="margin-bottom: 3px;"><strong>Connection:</strong> ${connectionText}</div>
                            <div style="margin-bottom: 5px;"><strong>Last seen:</strong><br>${billboard.last_seen}</div>
                            <div style="display: flex; justify-center; gap: 5px; margin-top: 8px;">
                                ${billboard.status === 'active' ? 
                                    `<button onclick="showStopModal('${billboard.serial}')" style="background-color: #EF4444; color: white; padding: 4px 8px; border-radius: 6px; font-size: 12px;">Stop</button>` : 
                                    `<form method="POST" action="">
                                        <input type="hidden" name="serial" value="${billboard.serial}">
                                        <button type="submit" name="restart_billboard" style="background-color: #10B981; color: white; padding: 4px 8px; border-radius: 6px; font-size: 12px;">Restart</button>
                                    </form>`
                                }
                            </div>
                        </div>
                    `, { closeButton: true });
                    
                    markers.push(marker);
                }
            });
        }
        
        setInterval(refreshData, 30000);
    </script>
    <?php endif; ?>
</body>
</html>