<?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');

// Security
$firewall = new Firewall();
$firewall->protect();
$firewall->logVisit('index');

$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'];
    }
}

// Track visitor (only during broadcast as per task)
if ($ongoingBroadcast) {
    $stmt = $db->prepare("INSERT INTO visitors (ip_address, user_agent, broadcast_id) VALUES (:ip, :ua, :bid)");
    $stmt->execute([
        ':ip' => $_SERVER['REMOTE_ADDR'],
        ':ua' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        ':bid' => $broadcast['id']
    ]);
}

// Site Settings
$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="https://vjs.zencdn.net/8.16.1/video-js.css" rel="stylesheet" />
    <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" class="video-js vjs-default-skin" controls preload="auto" width="600" height="300" data-setup='{}' muted>
        <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="player-container"></div>

<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");
        $hasSchedule = false;
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $hasSchedule = true;
            $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>";
        }
        if (!$hasSchedule) {
            echo "<li><em>Расписание скоро появится...</em></li>";
        }
        ?>
    </ul>
</div>

<?php
$stmt = $db->prepare("SELECT * FROM info_blocks WHERE page_name = 'index' 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 src="https://vjs.zencdn.net/8.16.1/video.min.js"></script>
<script>
    if (/iPhone|iPad/i.test(navigator.userAgent)) {
        window.location.href = "i.php";
    }

    var timeDifference = <?php echo $timeDifference; ?>;
    var countdownTime = <?php echo $countdownTime; ?>;
    var videoHasStarted = false;
    var videoPlayer = null;
    
    <?php if ($broadcast): ?>
    videoPlayer = videojs('videoPlayer');
    <?php endif; ?>

    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) {
                startVideo();
            }
        }
    }

    function startVideo() {
        videoPlayer.ready(function() {
            this.currentTime(timeDifference);
            this.play();
            document.getElementById("videoPlayer").style.display = 'block';
            document.getElementById("soundMessage").style.display = 'block';
            document.getElementById("cnt").style.display = 'block';
            this.controlBar.progressControl.disable();
            videoHasStarted = true;
        });
    }

    if (countdownTime > 0) {
        setInterval(updateCountdown, 1000);
    } else if (videoPlayer) {
        startVideo();
    }

    if (videoPlayer) {
        videoPlayer.on('ended', function() {
            this.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);
        document.getElementById("soundMessage").style.display = 'none';
    });

    function updateOnlineCount() {
        document.getElementById('onlineCount').innerText = getRandomNumber(22, 66);
    }
    setInterval(updateOnlineCount, 30000);
    updateOnlineCount();

    // No JS time shifts needed as per request
    console.log("Schedule loaded");
</script>
</body>
</html>
