<?php
require_once 'config.php';

// Adatbázis kapcsolat
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($db->connect_error) {
    die("Kapcsolódási hiba: " . $db->connect_error);
}
$db->set_charset("utf8mb4");

// Terem azonosító (ezt állítsd be a megfelelő értékre minden fájlban)
$terem_id = '224'; // Példa: 106.php esetén ez '106' legyen (string formátumban)

function getLessonData($db, $terem_id) {
    $current_day = date('N'); // 1 (hétfő) - 7 (vasárnap)
    
    $query = "
    SELECT o.*, 
           h.helyettesito_tanar, 
           h.jelleg,
           h.hianyzo_tanar,
           h.tantargy AS h_tantargy,
           h.osztaly AS h_osztaly
    FROM orarend o
    LEFT JOIN helyettesitesek h ON o.terem_id = h.terem 
        AND o.ora_sorszam = CAST(SUBSTRING_INDEX(h.ora_sorszam, '.', 1) AS UNSIGNED)
    WHERE o.terem_id = ? AND o.nap = ?
    ORDER BY o.ora_sorszam
    ";
    
    $stmt = $db->prepare($query);
    $stmt->bind_param("si", $terem_id, $current_day);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $orarend = [];
    while ($row = $result->fetch_assoc()) {
        // Helyettesítés kezelése
        if ($row['jelleg']) {
            $row['eredeti_tantargy'] = $row['tantargy'];
            $row['eredeti_tanar'] = $row['tanar'];
            $row['tantargy'] = $row['h_tantargy'] ?: $row['tantargy'];
            $row['tanar'] = $row['helyettesito_tanar'] ?: $row['tanar'];
            $row['osztaly'] = $row['h_osztaly'] ?: $row['osztaly'];
        }
        $orarend[] = $row;
    }
    
    // Debug: Írjuk ki az eredményt egy fájlba
    $debug_file = __DIR__ . '/debug_log.txt';
    file_put_contents($debug_file, print_r($orarend, true));
    
    return $orarend;
}

// AJAX kérés kezelése
if (isset($_GET['action'])) {
    if ($_GET['action'] == 'get_lesson_data') {
        $lesson_data = getLessonData($db, $terem_id);
        header('Content-Type: application/json');
        echo json_encode($lesson_data);
        exit;
    } elseif ($_GET['action'] == 'get_server_time') {
        $current_time = new DateTime('now', new DateTimeZone('Europe/Budapest'));
        header('Content-Type: application/json');
        echo json_encode(['server_time' => $current_time->format('Y-m-d H:i:s')]);
        exit;
    }
}

$db->close();
?>

<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Órarend - <?php echo $terem_id; ?> terem</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        html, body {
            height: 100%;
            width: 100%;
            overflow: hidden;
        }
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        .header {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .logo {
            max-width: 100px;
        }
        .container {
            width: 100%;
            max-width: 1000px;
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }
        .lesson-container {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .section {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 20px;
            width: 48%;
        }
        #currentLesson {
            border-left: 10px solid #3498db;
        }
        #nextLesson {
            border-left: 10px solid #f1c40f;
        }
        h1, h2 {
            text-align: center;
            margin-bottom: 15px;
            color: #2c3e50;
        }
        h1 {
            font-size: 28px;
            margin-bottom: 30px;
        }
        h2 {
            font-size: 24px;
            border-bottom: 2px solid #ecf0f1;
            padding-bottom: 10px;
        }
        p {
            margin: 10px 0;
            font-size: 18px;
            line-height: 1.4;
        }
        .info-box {
            background-color: #ecf0f1;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }
        #currentTime {
            text-align: right;
            font-size: 1.2em;
            color: #34495e;
            background-color: white;
            padding: 10px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        @media (max-width: 768px) {
            .lesson-container {
                flex-direction: column;
            }
            .section {
                width: 100%;
                margin-bottom: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <div style="width: 150px;"></div> <!-- Üres hely a bal oldalon -->
        <img src="https://kartyaigeny.kanizsay.edu.hu/image/kanizsay.png" alt="Kanizsay logo" class="logo">
        <div id="currentTime" style="width: 150px;"></div>
    </div>
    <div class="container">
        <h1>Órarend - <?php echo $terem_id; ?> terem</h1>
        
        <div class="lesson-container">
            <div id="currentLesson" class="section">
                <h2>Jelenlegi óra/állapot</h2>
                <div id="currentLessonContent">
                    <p class="info-box">Betöltés...</p>
                </div>
            </div>
            
            <div id="nextLesson" class="section">
                <h2>Következő óra</h2>
                <div id="nextLessonContent">
                    <p class="info-box">Betöltés...</p>
                </div>
            </div>
        </div>
    </div>

    <script>
        let clientServerTimeDiff = 0;
        let lessonData = null;

        const currentScript = location.pathname.split('/').pop();

        function syncTime() {
            fetch(`${currentScript}?action=get_server_time`)
                .then(response => response.json())
                .then(data => {
                    const serverTime = new Date(data.server_time);
                    const localTime = new Date();
                    clientServerTimeDiff = serverTime - localTime;
                })
                .catch(error => console.error('Hiba az idő szinkronizálásakor:', error));
        }

        function getCurrentTime() {
            return new Date(new Date().getTime() + clientServerTimeDiff);
        }

        function updateTime() {
            const now = getCurrentTime();
            document.getElementById('currentTime').innerHTML = now.toLocaleString('hu-HU');
        }

        function fetchLessonData() {
            fetch(`${currentScript}?action=get_lesson_data`)
                .then(response => response.json())
                .then(data => {
                    lessonData = data;
                    console.log("Lekért órarendi adatok:", lessonData);
                    updateLessonData();
                })
                .catch(error => console.error('Hiba az órarend lekérdezésekor:', error));
        }

        function updateLessonData() {
            if (!lessonData) return;

            const currentTime = getCurrentTime();
            const currentStatus = getCurrentStatus(lessonData, currentTime);
            const nextLesson = findNextLesson(lessonData, currentTime);

            updateCurrentStatus(currentStatus);
            updateNextLesson(nextLesson);
        }

        function getCurrentStatus(lessons, currentTime) {
            for (let i = 0; i < lessons.length; i++) {
                const lesson = lessons[i];
                const kezdes = new Date(currentTime.toDateString() + ' ' + lesson.kezdes);
                const vege = new Date(currentTime.toDateString() + ' ' + lesson.vege);

                if (currentTime >= kezdes && currentTime < vege) {
                    return lesson.tantargy ? { type: 'lesson', lesson } : { type: 'gap', lesson };
                }

                if (i < lessons.length - 1) {
                    const nextLesson = lessons[i + 1];
                    const nextKezdes = new Date(currentTime.toDateString() + ' ' + nextLesson.kezdes);
                    if (currentTime >= vege && currentTime < nextKezdes) {
                        return { type: 'break', current: lesson, next: nextLesson };
                    }
                }
            }

            return { type: 'noLesson' };
        }

        function findNextLesson(lessons, currentTime) {
            return lessons.find(lesson => {
                const kezdes = new Date(currentTime.toDateString() + ' ' + lesson.kezdes);
                return kezdes > currentTime && lesson.tantargy;
            });
        }

        function updateCurrentStatus(status) {
            const currentLessonContent = document.getElementById('currentLessonContent');
            let content = '';

            switch (status.type) {
                case 'lesson':
                    const isSubstitution = status.lesson.jelleg;
                    content = `
                        <p class="info-box">Idő: ${status.lesson.kezdes} - ${status.lesson.vege}</p>
                        <p class="info-box">Óra sorszáma: ${status.lesson.ora_sorszam}</p>
                        <p class="info-box">Tanár: ${status.lesson.tanar}</p>
                        <p class="info-box">Tárgy: ${status.lesson.tantargy}</p>
                        <p class="info-box">Osztály: ${status.lesson.osztaly}</p>
                        ${isSubstitution ? `
                            <p class="info-box"><strong>Jelleg: ${status.lesson.jelleg}</strong></p>
                            ${status.lesson.eredeti_tanar ? `<p class="info-box">Eredeti tanár: ${status.lesson.eredeti_tanar}</p>` : ''}
                            ${status.lesson.eredeti_tantargy ? `<p class="info-box">Eredeti tárgy: ${status.lesson.eredeti_tantargy}</p>` : ''}
                        ` : ''}
                        ${status.lesson.hianyzo_tanar ? `<p class="info-box">Hiányzó tanár: ${status.lesson.hianyzo_tanar}</p>` : ''}
                    `;
                    break;
                case 'gap':
                    content = '<p class="info-box">Lyukas óra</p>';
                    break;
                case 'break':
                    content = `<p class="info-box">Jelenleg szünet van a teremben!</p>
                               <p class="info-box">Következő óra kezdete: ${status.next.kezdes}</p>`;
                    break;
                case 'noLesson':
                    content = '<p class="info-box">Ma már nincs több óra a teremben.</p>';
                    break;
            }

            currentLessonContent.innerHTML = content;
        }

        function updateNextLesson(lesson) {
            const nextLessonContent = document.getElementById('nextLessonContent');
            if (lesson) {
                const isSubstitution = lesson.jelleg;
                nextLessonContent.innerHTML = `
                    <p class="info-box">Idő: ${lesson.kezdes} - ${lesson.vege}</p>
                    <p class="info-box">Óra sorszáma: ${lesson.ora_sorszam}</p>
                    <p class="info-box">Tanár: ${lesson.tanar}</p>
                    <p class="info-box">Tárgy: ${lesson.tantargy}</p>
                    <p class="info-box">Osztály: ${lesson.osztaly}</p>
                    ${isSubstitution ? `
                        <p class="info-box"><strong>Jelleg: ${lesson.jelleg}</strong></p>
                        ${lesson.eredeti_tanar ? `<p class="info-box">Eredeti tanár: ${lesson.eredeti_tanar}</p>` : ''}
                        ${lesson.eredeti_tantargy ? `<p class="info-box">Eredeti tárgy: ${lesson.eredeti_tantargy}</p>` : ''}
                    ` : ''}
                    ${lesson.hianyzo_tanar ? `<p class="info-box">Hiányzó tanár: ${lesson.hianyzo_tanar}</p>` : ''}
                `;
            } else {
                nextLessonContent.innerHTML = `
                    <p class="info-box">Nincs több óra betervezve.</p>
                `;
            }
        }

        // Indítás
        syncTime();
        fetchLessonData();

        // Időzítők beállítása
        setInterval(updateTime, 1000);
        setInterval(updateLessonData, 5000);  // 5 másodpercenként frissít
        setInterval(syncTime, 900000);
        setInterval(fetchLessonData, 3600000);  // Óránként frissíti az órarendet

        // Kezdeti frissítések
        updateTime();
    </script>
</body>
</html>