<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/firewall.php';
require_once __DIR__ . '/../includes/helpers.php';

date_default_timezone_set('Europe/Moscow');

$firewall = new Firewall();
$firewall->protect();
$firewall->logVisit('sacrali');

$database = new Database();
$db = $database->getConnection();

// Fetch current or next broadcast
$broadcast = getCurrentBroadcast($db);

$ongoingBroadcast = false;
$timeDifference = 0;
$countdownTime = 0;

if ($broadcast) {
    if ($broadcast['is_ongoing']) {
        $ongoingBroadcast = true;
        $timeDifference = $broadcast['time_elapsed'];
    } else {
        $countdownTime = $broadcast['countdown_seconds'];
    }
}

$bgColor = getSetting($db, 'site_bg_color', '#4B0082');
$textColor = getSetting($db, 'site_text_color', '#FFFFFF');
$snowEffect = getSetting($db, 'snow_effect', '1');
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>МИРИАДОНИКА</title>
    <link href="css/site.css" rel="stylesheet" />
    <style>
        body { background-color: <?php echo $bgColor; ?>; color: <?php echo $textColor; ?>; }
        #countdown, #startButton, #videoPlayer, #message, #soundMessage, #transdescription, #cnt, .schedule-block, .info-block {
            background-color: <?php echo $bgColor; ?>;
        }
    </style>
    <script src="js/tools.js"></script>
</head>
<body>
<?php if ($snowEffect == '1'): ?>
    <script src="js/snow.js"></script>
<?php endif; ?>

<div id="header">
    <img src="img/logo.png" border=0 width="10%" height="10%">&nbsp;
    <b>МИРИАДОНИКА</b>
</div>

<div id="countdown"></div>

<?php if ($broadcast): ?>
<video id="videoPlayer" controls preload="auto" muted playsinline>
    <source src="<?php echo $broadcast['cdn_url'] . '/' . $broadcast['video_path']; ?>" type="application/x-mpegURL" />
    <source src="<?php echo $broadcast['cdn_url'] . '/' . str_replace('master.m3u8', 'video.mp4', $broadcast['video_path']); ?>" type="video/mp4" />
    Ваш браузер не поддерживает воспроизведение видео.
</video>
<?php endif; ?>

<div id="cnt" style="display: none;">
    <p><svg width="20" height="20" viewBox="0 0 20 20" aria-hidden="true"><path fill-rule="evenodd" d="M5 7a5 5 0 1 1 6.192 4.857A2 2 0 0 0 13 13h1a3 3 0 0 1 3 3v2h-2v-2a1 1 0 0 0-1-1h-1a3.99 3.99 0 0 1-3-1.354A3.99 3.99 0 0 1 7 15H6a1 1 0 0 0-1 1v2H3v-2a3 3 0 0 1 3-3h1a2 2 0 0 0 1.808-1.143A5.002 5.002 0 0 1 5 7zm5 3a3 3 0 1 1 0-6 3 3 0 0 1 0 6z" clip-rule="evenodd" fill="white"></path></svg>
    <span id="onlineCount">0</span></p>
</div>

<div id="soundMessage" style="display: none;">
    <button id="soundButton">Включить звук</button>
</div>

<div id="message">Сеанс завершен.<br>Благодарим Вас за участие!❤️</div>

<?php if ($broadcast): ?>
<div id="transdescription">
    <h3><?php echo $broadcast['title']; ?></h3>
    <div class="description-content"><?php echo $broadcast['description']; ?></div>
</div>
<?php endif; ?>

<div class="schedule-block">
    <h3>Расписание сеансов</h3>
    <ul>
        <?php
        $stmt = $db->query("SELECT * FROM schedule WHERE is_active = 1 ORDER BY FIELD(day_of_week, 1, 2, 3, 4, 5, 6, 7), start_time ASC");
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $time = date('H:i', strtotime($row['start_time']) + 600);
            $day = getDayNameRu($row['day_of_week']);
            echo "<li><strong>$day в $time</strong>:<br>{$row['title']}</li>";
        }
        ?>
    </ul>
</div>

<?php
$stmt = $db->prepare("SELECT * FROM info_blocks WHERE page_name = 'sacrali' ORDER BY id ASC");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<div class='info-block'>";
    echo "<h3>{$row['title']}</h3>";
    echo $row['content'];
    echo "</div><br><br>";
}
?>

<script>
    var timeDifference = <?php echo $timeDifference; ?>;
    var countdownTime = <?php echo $countdownTime; ?>;
    var videoPlayer = document.getElementById('videoPlayer');
    var videoHasStarted = false;

    function updateCountdown() {
        if (countdownTime > 0) {
            document.getElementById("countdown").style.display = 'block';
            var hours = Math.floor(countdownTime / 3600);
            var minutes = Math.floor((countdownTime % 3600) / 60);
            var seconds = countdownTime % 60;
            var text = "До начала трансляции:<br>";
            if (hours > 0) text += hours + " часов ";
            if (minutes > 0 || hours > 0) text += minutes + " минут ";
            text += seconds + " секунд";
            document.getElementById("countdown").innerHTML = text;
            countdownTime--;
        } else {
            document.getElementById("countdown").style.display = 'none';
            document.getElementById("countdown").innerText = "";
            if (!videoHasStarted && videoPlayer) {
                videoPlayer.play();
                videoPlayer.currentTime = timeDifference;
                document.getElementById("videoPlayer").style.display = 'block';
                document.getElementById("soundMessage").style.display = 'block';
                document.getElementById("cnt").style.display = 'block';
                videoHasStarted = true;
            }
        }
    }

    if (countdownTime > 0) {
        setInterval(updateCountdown, 1000);
    } else if (videoPlayer) {
        videoPlayer.play();
        videoPlayer.currentTime = timeDifference;
        document.getElementById("videoPlayer").style.display = 'block';
        document.getElementById("soundMessage").style.display = 'block';
        document.getElementById("cnt").style.display = 'block';
        videoHasStarted = true;
    }

    if (videoPlayer) {
        videoPlayer.addEventListener('ended', () => {
            videoPlayer.pause();
            document.getElementById("videoPlayer").style.display = 'none';
            document.getElementById("soundMessage").style.display = 'none';
            document.getElementById("message").style.display = 'block';
            document.getElementById("cnt").style.display = 'none';
        });
    }

    document.getElementById("soundButton").addEventListener('click', function() {
        if (videoPlayer) {
            videoPlayer.muted = false;
            videoPlayer.volume = 1.0;
        }
        document.getElementById("soundMessage").style.display = 'none';
    });

    function updateOnlineCount() {
        document.getElementById('onlineCount').innerText = getRandomNumber(22, 66);
    }
    setInterval(updateOnlineCount, 30000);
    updateOnlineCount();
</script>
</body>
</html>
