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

$config = [
    'location' => [
        'latitude' => 51.5074,
        'longitude' => -0.1278
    ],
    'screensaver' => [
        'enabled' => true,
        'start' => '19:30',
        'end' => '06:00',
        'qrCode' => 'https://imators.com/about/screen-saver'
    ],
    'weather' => [
        'enabled' => false
    ],
    'serial' => '',
    'status' => 'active'
];

$showSetup = false;
$stopMessage = '';

if (isset($_POST['saveConfig'])) {
    $latitude = filter_input(INPUT_POST, 'latitude', FILTER_VALIDATE_FLOAT);
    $longitude = filter_input(INPUT_POST, 'longitude', FILTER_VALIDATE_FLOAT);
    $serialNumber = filter_input(INPUT_POST, 'serial', FILTER_SANITIZE_STRING);
    
    $stmt = $pdo->prepare("SELECT * FROM `imators-systems-billboard` WHERE serial = ?");
    $stmt->execute([$serialNumber]);
    $existing = $stmt->fetch();
    
    if ($existing) {
        $_SESSION['config'] = json_decode($existing['config'], true);
        $_SESSION['serial'] = $serialNumber;
        $_SESSION['status'] = $existing['status'];
        $_SESSION['stop_message'] = $existing['stop_message'];
    } else {
        $config['location']['latitude'] = $latitude;
        $config['location']['longitude'] = $longitude;
        $config['serial'] = $serialNumber;
        
        $stmt = $pdo->prepare("INSERT INTO `imators-systems-billboard` (serial, config, status, last_seen) VALUES (?, ?, 'active', NOW())");
        $stmt->execute([$serialNumber, json_encode($config)]);
        
        $_SESSION['config'] = $config;
        $_SESSION['serial'] = $serialNumber;
        $_SESSION['status'] = 'active';
        $_SESSION['stop_message'] = null;
    }
    
    header('Location: index.php');
    exit;
}

if (!isset($_SESSION['config']) || !isset($_SESSION['serial'])) {
    $showSetup = true;
} else {
    $config = $_SESSION['config'];
    $serialNumber = $_SESSION['serial'];
    
    $stmt = $pdo->prepare("UPDATE `imators-systems-billboard` SET last_seen = NOW() WHERE serial = ?");
    $stmt->execute([$serialNumber]);
    
    $stmt = $pdo->prepare("SELECT status, stop_message FROM `imators-systems-billboard` WHERE serial = ?");
    $stmt->execute([$serialNumber]);
    $billboard = $stmt->fetch();
    
    if ($billboard) {
        if ($billboard['status'] === 'stopped') {
            $stopMessage = $billboard['stop_message'] ?? 'This billboard has been stopped by the administrator.';
            $_SESSION['status'] = 'stopped';
            $_SESSION['stop_message'] = $stopMessage;
        } else {
            $_SESSION['status'] = 'active';
            $_SESSION['stop_message'] = null;
        }
    }
}

$videos = [
    [
        'src' => 'https://cdn.imators.com/imators_systems_ads2.mp4',
        'link' => 'https://academ.my',
        'showElements' => true,
        'showQR' => true,
        'showHour' => ['show' => true, 'color' => 'white'],
        'showDate' => ['show' => true, 'color' => 'white'],
        'showWeather' => true,
        'timeSlot' => ['start' => '00:00', 'end' => '00:00'],
        'loop' => true
    ],
    [
        'src' => 'https://cdn.imators.com/imators_systems_ads1.mp4',
        'link' => 'https://imators.com/about/daywithimators',
        'showElements' => true,
        'showQR' => true,
        'showHour' => ['show' => true, 'color' => 'black'],
        'showDate' => ['show' => true, 'color' => 'black'],
        'showWeather' => false,
        'timeSlot' => ['start' => '00:00', 'end' => '00:00'],
        'loop' => true
    ],
    [
        'src' => 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/TearsOfSteel.mp4',
        'link' => 'https://example.com/link3',
        'showElements' => true,
        'showQR' => true,
        'showHour' => ['show' => true, 'color' => 'white'],
        'showDate' => ['show' => true, 'color' => 'white'],
        'showWeather' => true,
        'timeSlot' => ['start' => '00:00', 'end' => '00:00'],
        'loop' => true
    ],
    [
        'src' => 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4',
        'link' => 'https://example.com/link4',
        'showElements' => true,
        'showQR' => false,
        'showHour' => ['show' => true, 'color' => 'white'],
        'showDate' => ['show' => true, 'color' => 'white'],
        'showWeather' => false,
        'timeSlot' => ['start' => '00:00', 'end' => '00:00'],
        'loop' => true
    ]
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Imators Systems</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <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 type="text/css">
        body {
            font-family: 'Inter', sans-serif;
        }
        .hidden {
            display: none !important;
        }
    </style>
</head>
<body class="bg-black text-white h-screen overflow-hidden">
    <?php if ($showSetup): ?>
    <div class="bg-gray-900 min-h-screen flex flex-col items-center justify-center p-6">
        <div class="bg-gray-800 p-8 rounded-xl shadow-xl max-w-md w-full">
            <img src="https://cdn.imators.com/logo.png" alt="Imators Logo" class="w-24 h-24 mx-auto mb-6">
            <h1 class="text-2xl font-bold text-center mb-6">Billboard Configuration</h1>
            <form method="POST" action="" class="space-y-6">
                <div class="space-y-2">
                    <label class="block text-sm font-medium">Location</label>
                    <div id="map" class="h-64 rounded-lg mb-2"></div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-xs mb-1">Latitude</label>
                            <input type="text" name="latitude" id="latitude" value="<?php echo $config['location']['latitude']; ?>" class="w-full bg-gray-700 border border-gray-600 rounded-lg px-3 py-2 text-white">
                        </div>
                        <div>
                            <label class="block text-xs mb-1">Longitude</label>
                            <input type="text" name="longitude" id="longitude" value="<?php echo $config['location']['longitude']; ?>" class="w-full bg-gray-700 border border-gray-600 rounded-lg px-3 py-2 text-white">
                        </div>
                    </div>
                </div>
                <div class="space-y-2">
                    <label for="serial" class="block text-sm font-medium">Billboard Serial Number</label>
                    <input type="text" name="serial" id="serial" required class="w-full bg-gray-700 border border-gray-600 rounded-lg px-3 py-2 text-white">
                </div>
                <button type="submit" name="saveConfig" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition duration-150">
                    Confirm and Start
                </button>
            </form>
        </div>
    </div>
    <script>
        const latInput = document.getElementById('latitude');
        const lngInput = document.getElementById('longitude');
        
        const map = L.map('map').setView([<?php echo $config['location']['latitude']; ?>, <?php echo $config['location']['longitude']; ?>], 13);
        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);
        
        let marker = L.marker([<?php echo $config['location']['latitude']; ?>, <?php echo $config['location']['longitude']; ?>], {
            draggable: true
        }).addTo(map);
        
        marker.on('dragend', function(e) {
            const position = marker.getLatLng();
            latInput.value = position.lat.toFixed(6);
            lngInput.value = position.lng.toFixed(6);
        });
        
        map.on('click', function(e) {
            marker.setLatLng(e.latlng);
            latInput.value = e.latlng.lat.toFixed(6);
            lngInput.value = e.latlng.lng.toFixed(6);
        });
    </script>
    <?php else: ?>
    
    <?php if ($_SESSION['status'] === 'stopped'): ?>
    <div class="fixed inset-0 z-50 flex items-center justify-center bg-red-600">
        <div class="text-center p-8">
            <h1 class="text-4xl font-bold mb-4">STOPPED</h1>
            <p class="text-2xl"><?php echo htmlspecialchars($_SESSION['stop_message']); ?></p>
        </div>
    </div>
    <?php else: ?>
    <div class="absolute inset-0 w-full h-full" id="video-container">
        <video autoplay="" class="object-cover w-full h-full" id="background-video" muted=""></video>
    </div>
    
    <div class="hidden absolute inset-0 w-full h-full bg-black" id="screensaver">
        <div class="absolute top-4 left-4" id="datetime-screensaver">
            <div class="text-4xl font-light" id="time-screensaver"></div>
            <div class="text-lg font-light mt-1 opacity-80" id="date-screensaver"></div>
            <div class="text-lg font-light mt-2" id="weather-screensaver"></div>
        </div>
        
        <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-center">
            <div class="flex items-center gap-8">
                <img alt="Logo" class="w-48 h-48" src="https://cdn.imators.com/logo.png" />
                <div class="text-left">
                    <h1 class="text-4xl mb-2">Good Night everyone!</h1>
                    <p class="text-xl text-gray-300">We wish you a pleasant evening and see you tomorrow!</p>
                </div>
            </div>
        </div>
        
        <div class="absolute bottom-6 right-6 bg-white p-2 rounded-md shadow-lg">
            <div id="qrcode-screensaver"></div>
        </div>
    </div>
    
    <div class="absolute bottom-6 right-6 bg-white p-2 rounded-md shadow-lg" id="qr-container">
        <div id="qrcode"></div>
    </div>
    
    <div class="absolute top-4 left-4 text-white" id="datetime-container">
        <div class="text-4xl font-light" id="time"></div>
        <div class="text-lg font-light mt-1 opacity-80" id="date"></div>
        <div class="text-lg font-light mt-2" id="weather"></div>
    </div>
    
    <script>
    const CONFIG = <?php echo json_encode($config); ?>;
    const SERIAL = "<?php echo $serialNumber; ?>";
    
    const videos = <?php echo json_encode($videos); ?>;
    
    let currentVideoIndex = 0;
    let wsConnection = null;
    const timeElementScreensaver = document.getElementById('time-screensaver');
    const dateElementScreensaver = document.getElementById('date-screensaver');
    const weatherElementScreensaver = document.getElementById('weather-screensaver');
    const qrcodeScreensaver = document.getElementById('qrcode-screensaver');
    const video = document.getElementById('background-video');
    const qrcode = document.getElementById('qrcode');
    const qrContainer = document.getElementById('qr-container');
    const datetimeContainer = document.getElementById('datetime-container');
    const timeElement = document.getElementById('time');
    const dateElement = document.getElementById('date');
    const screensaver = document.getElementById('screensaver');
    const weather = document.getElementById('weather');
    
    function getWeatherDescription(code) {
        const weatherCodes = {
            0: 'Clear sky',
            1: 'Mainly clear',
            2: 'Partly cloudy',
            3: 'Overcast',
            45: 'Fog',
            48: 'Depositing rime fog',
            51: 'Light drizzle',
            53: 'Moderate drizzle',
            55: 'Dense drizzle',
            61: 'Slight rain',
            63: 'Moderate rain',
            65: 'Heavy rain',
            71: 'Slight snow fall',
            73: 'Moderate snow fall',
            75: 'Heavy snow fall',
            77: 'Snow grains',
            80: 'Slight rain showers',
            81: 'Moderate rain showers',
            82: 'Violent rain showers',
            95: 'Thunderstorm',
            96: 'Thunderstorm with slight hail',
            99: 'Thunderstorm with heavy hail'
        };
        return weatherCodes[code] || 'Unknown';
    }
    
    async function updateWeather() {
        if (!CONFIG.weather.enabled) {
            weather.textContent = '';
            weatherElementScreensaver.textContent = '';
            weather.classList.add('hidden');
            return;
        }
    
        try {
            const response = await fetch(
                `https://api.open-meteo.com/v1/forecast?latitude=${CONFIG.location.latitude}&longitude=${CONFIG.location.longitude}&current=temperature_2m,weather_code&timezone=auto`
            );
            const data = await response.json();
            
            const temp = Math.round(data.current.temperature_2m);
            const weatherCode = data.current.weather_code;
            const description = getWeatherDescription(weatherCode);
            
            weather.textContent = `${temp}°C - ${description}`;
            weatherElementScreensaver.textContent = `${temp}°C - ${description}`;
        } catch (error) {
            console.error('Weather error:', error);
            weather.textContent = '';
            weatherElementScreensaver.textContent = '';
            weather.classList.add('hidden');
        }
    }
    
    function isScreensaverTime() {
        if (!CONFIG.screensaver.enabled) return false;
    
        const now = new Date();
        const currentTime = now.getHours().toString().padStart(2, '0') + ':' + 
                          now.getMinutes().toString().padStart(2, '0');
        
        if (CONFIG.screensaver.start <= CONFIG.screensaver.end) {
            return currentTime >= CONFIG.screensaver.start && currentTime < CONFIG.screensaver.end;
        } else {
            return currentTime >= CONFIG.screensaver.start || currentTime < CONFIG.screensaver.end;
        }
    }
    
    function isInTimeSlot(video) {
        if (video.timeSlot.start === '00:00' && video.timeSlot.end === '00:00') {
            return true;
        }
    
        const now = new Date();
        const currentTime = now.getHours().toString().padStart(2, '0') + ':' + 
                          now.getMinutes().toString().padStart(2, '0');
        
        const start = video.timeSlot.start;
        const end = video.timeSlot.end;
        
        if (start <= end) {
            return currentTime >= start && currentTime < end;
        } else {
            return currentTime >= start || currentTime < end;
        }
    }
    
    function getNextValidVideoIndex() {
        let checkedVideos = 0;
        let nextIndex = currentVideoIndex;
    
        while (checkedVideos < videos.length) {
            nextIndex = (nextIndex + 1) % videos.length;
            const video = videos[nextIndex];
            
            if (video.loop && isInTimeSlot(video)) {
                return nextIndex;
            }
            
            checkedVideos++;
        }
    
        return -1;
    }
    
    function playVideo() {
        if (CONFIG.screensaver.enabled && isScreensaverTime()) {
            video.src = '';
            screensaver.classList.remove('hidden');
            qrContainer.classList.add('hidden');
            
            qrcodeScreensaver.innerHTML = '';
            new QRCode(qrcodeScreensaver, {
                text: CONFIG.screensaver.qrCode,
                width: 128,
                height: 128,
                colorDark: "#000000",
                colorLight: "#ffffff"
            });
            return;
        }
        
        screensaver.classList.add('hidden');
        
        const currentVideo = videos[currentVideoIndex];
        
        if (!currentVideo.loop || !isInTimeSlot(currentVideo)) {
            const nextValidIndex = getNextValidVideoIndex();
            if (nextValidIndex === -1) {
                video.src = '';
                qrContainer.classList.add('hidden');
                datetimeContainer.classList.add('hidden');
                return;
            }
            currentVideoIndex = nextValidIndex;
        }
    
        const videoToPlay = videos[currentVideoIndex];
        video.src = videoToPlay.src;
        video.play();
    
        if (videoToPlay.showElements) {
            datetimeContainer.classList.remove('hidden');
            
            if (videoToPlay.showQR) {
                qrContainer.classList.remove('hidden');
                qrcode.innerHTML = '';
                new QRCode(qrcode, {
                    text: videoToPlay.link,
                    width: 128,
                    height: 128,
                    colorDark: "#000000",
                    colorLight: "#ffffff"
                });
            } else {
                qrContainer.classList.add('hidden');
            }
            
            timeElement.classList.toggle('hidden', !videoToPlay.showHour.show);
            timeElement.style.color = videoToPlay.showHour.color;
            
            dateElement.classList.toggle('hidden', !videoToPlay.showDate.show);
            dateElement.style.color = videoToPlay.showDate.color;
    
            if (CONFIG.weather.enabled && videoToPlay.showWeather) {
                weather.classList.remove('hidden');
            } else {
                weather.classList.add('hidden');
            }
        } else {
            qrContainer.classList.add('hidden');
            datetimeContainer.classList.add('hidden');
        }
    }
    
    video.addEventListener('ended', () => {
        const nextValidIndex = getNextValidVideoIndex();
        if (nextValidIndex !== -1) {
            currentVideoIndex = nextValidIndex;
            playVideo();
        }
    });
    
    function updateDateTime() {
        const now = new Date();
        const timeString = now.toLocaleTimeString('en-GB', { 
            hour: '2-digit', 
            minute: '2-digit'
        });
        const dateString = now.toLocaleDateString('en-GB', { 
            weekday: 'long',
            day: 'numeric',
            month: 'long'
        });
        
        const formattedDate = dateString.charAt(0).toUpperCase() + dateString.slice(1);
        
        timeElement.textContent = timeString;
        dateElement.textContent = formattedDate;
        
        timeElementScreensaver.textContent = timeString;
        dateElementScreensaver.textContent = formattedDate;
    
        if (!isInTimeSlot(videos[currentVideoIndex]) || isScreensaverTime()) {
            playVideo();
        }
    }
    
    function connectWebSocket() {
        if (wsConnection && (wsConnection.readyState === WebSocket.CONNECTING || wsConnection.readyState === WebSocket.OPEN)) {
            return;
        }
        
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${protocol}//${window.location.host}/ws-server.php`;
        
        wsConnection = new WebSocket(wsUrl);
        
        wsConnection.onopen = function() {
            console.log('WebSocket connected');
            wsConnection.send(JSON.stringify({
                type: 'register',
                serial: SERIAL
            }));
        };
        
        wsConnection.onmessage = function(event) {
            const data = JSON.parse(event.data);
            
            if (data.type === 'status_update') {
                if (data.status === 'stopped' && data.serial === SERIAL) {
                    window.location.reload();
                }
            }
        };
        
        wsConnection.onclose = function() {
            console.log('WebSocket connection closed');
            setTimeout(connectWebSocket, 5000);
        };
        
        wsConnection.onerror = function(error) {
            console.error('WebSocket error:', error);
            wsConnection.close();
        };
    }
    
    function updateStatus() {
        fetch('api/status.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                serial: SERIAL,
                action: 'check'
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'stopped' && data.reloadNeeded) {
                window.location.reload();
            }
        })
        .catch(error => console.error('Status check error:', error));
    }
    
    setInterval(updateStatus, 10000);
    setInterval(updateWeather, 15 * 60 * 1000);
    updateWeather();
    
    setInterval(updateDateTime, 1000);
    updateDateTime();
    playVideo();
    
    // Try to use WebSocket if supported
    if ('WebSocket' in window) {
        connectWebSocket();
    }
    </script>
    <?php endif; ?>
    <?php endif; ?>
</body>
</html>