<?php
require_once __DIR__ . "/../MaintenanceCheck.php";
session_start();
require "../Auth/db.php";

$isLoggedIn = isset($_SESSION["user"]);

$ppvId = $_GET["id"] ?? null;

if (!$ppvId) {
    die("Missing PPV ID.");
}

$stmt = $pdo->prepare("SELECT * FROM media_ppv WHERE id = ?");
$stmt->execute([$ppvId]);
$ppv = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$ppv) {
    die("PPV Not Found.");
}

$avatar = "../Assets/Logo.png";

if (!empty($_SESSION["user"]["avatar"]) && !empty($_SESSION["user"]["discord_id"])) {
    $avatar = "https://cdn.discordapp.com/avatars/" .
        $_SESSION["user"]["discord_id"] . "/" .
        $_SESSION["user"]["avatar"] . ".png";
}

$streamUrl = $ppv["stream_url"] ?? "";

$sessionId = session_id();

$pdo->prepare("
    DELETE FROM active_ppv_viewers
    WHERE last_seen < NOW() - INTERVAL 30 SECOND
")->execute();

$stmt = $pdo->prepare("
    SELECT id
    FROM active_ppv_viewers
    WHERE ppv_id = ?
    AND session_id = ?
");

$stmt->execute([$ppvId, $sessionId]);

$viewerExists = $stmt->fetch();

if ($viewerExists) {

    $pdo->prepare("
        UPDATE active_ppv_viewers
        SET last_seen = NOW()
        WHERE id = ?
    ")->execute([$viewerExists["id"]]);

} else {

    $pdo->prepare("
        INSERT INTO active_ppv_viewers
        (ppv_id, session_id)
        VALUES (?, ?)
    ")->execute([$ppvId, $sessionId]);
}

/* GET LIVE VIEWERS */
$stmt = $pdo->prepare("
    SELECT COUNT(*)
    FROM active_ppv_viewers
    WHERE ppv_id = ?
");

$stmt->execute([$ppvId]);

$liveViewers = (int)$stmt->fetchColumn();

$isLoggedIn = isset($_SESSION["user"]);

$username = "Guest" . rand(1000, 9999);

$badges = [];

if ($isLoggedIn) {

    if (!empty($_SESSION["user"]["username"])) {
        $username = $_SESSION["user"]["username"];
    }

    $userId = $_SESSION["user"]["id"];

    $badgeStmt = $pdo->prepare("
        SELECT ub.*
        FROM user_assigned_badges uab
        INNER JOIN user_badges ub
            ON uab.badge_id = ub.id
        WHERE uab.user_id = ?
        ORDER BY uab.id DESC
    ");

    $badgeStmt->execute([$userId]);

    $badges = $badgeStmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo htmlspecialchars($ppv["title"]); ?> - Rewire</title>
<link rel="icon" type="image/png" href="../Assets/Logo.png">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/lucide@latest"></script>
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: Arial, sans-serif;
}

body {
    background: #000;
    color: white;
    overflow: hidden;
}

/* HEADER */
.header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 82px;
    padding: 0 25px;

    display: flex;
    align-items: center;
    justify-content: space-between;

    z-index: 9999;

    background: #000;

    border-bottom: 1px solid rgba(255,255,255,0.06);

    backdrop-filter: blur(18px);

    overflow: visible;
}

.logo-img {
    height: 70px;
}

.right {
    display: flex;
    align-items: center;
    gap: 30px;

    position: relative;
    z-index: 10000;
}

.nav {
    display: flex;
    align-items: center;
    gap: 25px;
}

.home-btn,
.browse-btn {
    background: none;
    border: none;
    color: #b5b5b5;
    cursor: pointer;

    display: flex;
    align-items: center;
    justify-content: center;

    text-decoration: none;

    transition: 0.25s ease;

    position: relative;
    z-index: 10001;
}

.home-btn:hover,
.browse-btn:hover {
    color: #fff;
    transform: scale(1.08);
}

.home-btn i {
    width: 22px;
    height: 22px;
}

.browse-btn {
    gap: 6px;
}

.browse-btn i {
    width: 21px;
    height: 21px;
}

.browse-arrow {
    width: 16px !important;
    height: 16px !important;
}

/* BROWSE */
.browse-dropdown {
    position: relative;
    display: flex;
    align-items: center;
    z-index: 10000;
}

.browse-menu {
    position: absolute;

    top: 58px;
    right: 0;

    width: 320px;

    background: #000;

    border: 1px solid rgba(255,255,255,0.08);

    border-radius: 20px;

    padding: 18px 14px;

    display: none;

    box-shadow:
        0 20px 60px rgba(0,0,0,0.85);

    z-index: 999999;

    backdrop-filter: blur(20px);
}

.browse-menu.active {
    display: block;
}

.browse-title {
    text-align: center;
    font-weight: 900;
    margin-bottom: 20px;
}

.browse-section-label {
    color: #666;
    font-size: 0.72rem;
    font-weight: 900;
    letter-spacing: 1px;
    margin: 16px 0 10px;
}

.browse-grid,
.browse-personal {
    display: grid;
    gap: 12px;
}

.browse-grid {
    grid-template-columns: repeat(3, 1fr);
}

.browse-personal {
    grid-template-columns: repeat(2, 1fr);
}

.browse-menu a {
    height: 76px;

    border-radius: 12px;

    color: white;
    text-decoration: none;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    gap: 7px;

    font-size: 0.72rem;
    font-weight: 800;

    transition: 0.2s ease;
}

.browse-menu a i {
    color: #fff;
    width: 24px;
    height: 24px;
}

.browse-menu a:hover {
    background: rgba(255,255,255,0.05);
}

/* PROFILE */
.profile-dropdown {
    position: relative;
    cursor: pointer;
}

.profile-avatar {
    width: 36px;
    height: 36px;

    border-radius: 10px;

    object-fit: cover;

    border: 1px solid rgba(255,255,255,0.15);
}

.profile-menu {
    position: absolute;

    top: 48px;
    right: 0;

    width: 170px;

    background: #000;

    border: 1px solid rgba(255,255,255,0.10);

    border-radius: 12px;

    padding: 10px;

    display: none;

    box-shadow: 0 12px 35px rgba(0,0,0,0.8);

    z-index: 999999;
}

.profile-menu.active {
    display: block;
}

.profile-menu-name {
    color: white;
    font-size: 0.85rem;
    font-weight: bold;

    padding: 8px 10px;

    border-bottom: 1px solid rgba(255,255,255,0.08);

    margin-bottom: 8px;
}

.profile-menu a {
    display: block;

    padding: 9px 10px;

    border-radius: 8px;

    color: #fff;

    text-decoration: none;

    font-size: 0.9rem;
    font-weight: bold;
}

.profile-menu a:hover {
    background: rgba(255,255,255,0.05);
}

/* PPV PAGE */
.ppv-page {
    margin-top: 82px;

    height: calc(100vh - 82px);

    display: grid;

    grid-template-columns: 1fr 430px;

    background: #000;
}

.player-side {
    background: #000;

    display: flex;
    flex-direction: column;

    height: calc(100vh - 82px);
}

.video-wrap {
    flex: 1;

    position: relative;

    overflow: hidden;

    background: #000;

    display: flex;
    align-items: center;
    justify-content: center;
}

.video-wrap iframe,
.video-wrap video {
    position: absolute;

    top: 0;
    left: 0;

    width: 100%;
    height: 100%;

    border: none;

    object-fit: cover;
}

.no-source {
    color: #666;
    font-weight: 800;
}

/* BOTTOM BAR */
.ppv-info {
    min-height: 115px;

    padding: 18px 25px 22px;

    background: #000;

    border-top: 1px solid rgba(255,255,255,0.06);

    position: relative;

    overflow: hidden;
}

.ppv-title {
    font-size: 1.55rem;
    font-weight: 900;

    margin-bottom: 6px;
}

.ppv-meta {
    color: #888;
    font-size: 0.92rem;
}

/* CHAT */
.chat-side {
    background: #000;

    border-left: 1px solid rgba(255,255,255,0.06);

    height: calc(100vh - 82px);

    display: flex;
    flex-direction: column;

    position: relative;

    overflow: hidden;
}

.chat-header {
    height: 64px;

    padding: 0 18px;

    border-bottom: 1px solid rgba(255,255,255,0.06);

    display: flex;
    align-items: center;
    justify-content: space-between;
}

.chat-header h2 {
    font-size: 1.15rem;
}

.connected {
    color: #777;
    font-size: 0.85rem;
}

.connected::before {
    content: "";

    display: inline-block;

    width: 7px;
    height: 7px;

    background: #fff;

    border-radius: 50%;

    margin-right: 7px;
}

.chat-messages {
    flex: 1;

    padding: 14px 16px;
    padding-right: 10px;

    overflow-y: auto;
    overflow-x: hidden;

    scrollbar-width: thin;
    scrollbar-color: #1f1f1f #050505;
}

.chat-input-area {
    padding: 14px;

    border-top: 1px solid rgba(255,255,255,0.06);

    display: flex;

    gap: 10px;
}

.chat-input-area input {
    flex: 1;

    height: 54px;

    background: #000;

    border: 1px solid rgba(255,255,255,0.08);

    border-radius: 12px;

    color: white;

    padding: 0 15px;

    outline: none;
}

.chat-input-area input:focus {
    border-color: rgba(255,255,255,0.2);
}

.send-btn {
    width: 54px;
    height: 54px;

    border: none;

    border-radius: 12px;

    background: #111;

    color: white;

    cursor: pointer;

    transition: 0.2s ease;
}

.send-btn:hover {
    background: #fff;
    color: #000;
}

@media (max-width: 1000px) {

    .ppv-page {
        grid-template-columns: 1fr;
    }

    .chat-side {
        display: none;
    }

}

.chat-name {
    display: inline-flex;
    align-items: center;
    gap: 6px;

    font-weight: 900;

    color: white;

    flex-shrink: 0;
}

.chat-badge {
    width: 20px;
    height: 20px;

    object-fit: contain;

    border-radius: 50%;

    flex-shrink: 0;
}

.chat-line {
    display: flex;
    align-items: center;
    gap: 8px;

    margin-bottom: 14px;

    color: #d6d6d6;

    font-size: 0.92rem;

    line-height: 1.4;

    flex-wrap: nowrap;
}

.chat-message {
    color: #d6d6d6;

    word-break: break-word;
}

/* SCROLLBAR */
.chat-messages::-webkit-scrollbar {
    width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
    background: #050505;
}

.chat-messages::-webkit-scrollbar-thumb {
    background: #1a1a1a;
    border-radius: 20px;
    border: 1px solid #2a2a2a;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
    background: #2c2c2c;
}

/* FIREFOX */
.chat-messages {
    scrollbar-width: thin;
    scrollbar-color: #1f1f1f #050505;
}

.search-icon-btn {
    background: none;
    border: none;
    color: #ccc;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: 0.25s ease;
}

.search-icon-btn:hover {
    color: #00c2ff;
    transform: scale(1.08);
}

.search-icon-btn i,
.search-icon-btn svg {
    width: 22px;
    height: 22px;
}

.browse-dropdown {
    position: relative;
    display: flex;
    align-items: center;
}

.browse-menu {
    position: absolute;
    top: 42px;
    right: 0;
    width: 320px;
    background: rgba(8,10,13,0.96);
    border: 1px solid rgba(255,255,255,0.12);
    border-radius: 20px;
    padding: 18px 14px;
    display: none;
    box-shadow: 0 18px 45px rgba(0,0,0,0.6);
    z-index: 999;
}

.browse-menu.active {
    display: block;
}

.browse-title {
    text-align: center;
    font-weight: 900;
    margin-bottom: 20px;
}

.browse-section-label {
    color: #8f9aa5;
    font-size: 0.72rem;
    font-weight: 900;
    letter-spacing: 1px;
    margin: 16px 0 10px;
}

.browse-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
}

.browse-personal {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
}

.browse-menu a {
    width: auto;
    height: 76px;
    padding: 0;
    border-radius: 12px;
    color: #ccc;
    text-decoration: none;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 7px;
    font-size: 0.72rem;
    font-weight: 800;
    position: relative;
    transition: 0.3s;
}

.browse-menu a i {
    color: #00c2ff;
    width: 24px;
    height: 24px;
}

.browse-menu a::after {
    content: "";
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    width: 0%;
    height: 2px;
    background: #00c2ff;
    transition: 0.3s;
    border-radius: 999px;
}

.browse-menu a:hover {
    color: white;
    background: rgba(0,194,255,0.10);
}

.browse-menu a:hover::after {
    width: 55%;
}
</style>
</head>
<body>
<?php include "../Preloader.php"; ?>
<header class="header">
    <div class="left">
        <img src="../Assets/Logo.png" class="logo-img">
    </div>

    <div class="right">
        <div class="nav">
            <a href="../Index.php" class="home-btn">
                <i data-lucide="house"></i>
            </a>

            <div class="browse-dropdown">
                <button type="button" class="browse-btn" onclick="toggleBrowseMenu(event)">
                    <i data-lucide="grid-2x2"></i>
                    <i data-lucide="chevron-down" class="browse-arrow"></i>
                </button>

                <div class="browse-menu" id="browseMenu">
                    <div class="browse-title">Browse</div>

                    <div class="browse-section-label">CONTENT</div>
                    <div class="browse-grid">
                        <a href="../Movies/Movies.php">
                            <i data-lucide="clapperboard"></i>
                            Movies
                        </a>

                        <a href="../Series/Series.php">
                            <i data-lucide="tv"></i>
                            TV Shows
                        </a>

                        <a href="PPV.php">
                            <i data-lucide="ticket"></i>
                            PPV
                        </a>
                    </div>

                    <div class="browse-section-label">PERSONAL</div>
                    <div class="browse-personal">
                        <a href="../History.php">
                            <i data-lucide="history"></i>
                            History
                        </a>

                        <a href="../Watchlist.php">
                            <i data-lucide="heart"></i>
                            Watchlist
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($isLoggedIn): ?>
            <div class="profile-dropdown" onclick="toggleProfileMenu()">
                <img src="<?php echo htmlspecialchars($avatar); ?>" class="profile-avatar">

                <div class="profile-menu" id="profileMenu">
                    <div class="profile-menu-name">
                        <?php echo htmlspecialchars($_SESSION["user"]["username"]); ?>
                    </div>

                    <?php if (!empty($_SESSION["user"]["is_admin"])): ?>
                        <a href="../Admin/Dashboard.php">Admin Interface</a>
                    <?php endif; ?>

                    <a href="../Auth/logout.php">Logout</a>
                </div>
            </div>
        <?php else: ?>
            <a href="../Index.php" class="home-btn">
                <i data-lucide="user"></i>
            </a>
        <?php endif; ?>
    </div>
</header>

<main class="ppv-page">
    <section class="player-side">
        <div class="video-wrap">
            <?php if (!empty($streamUrl)): ?>
                <iframe
                    src="<?php echo htmlspecialchars($streamUrl); ?>"
                    allowfullscreen
                    allow="autoplay; fullscreen; encrypted-media">
                </iframe>
            <?php else: ?>
                <div class="no-source">No PPV Stream Source Added.</div>
            <?php endif; ?>
        </div>

        <div class="ppv-info">
            <div class="ppv-title">
                <?php echo htmlspecialchars($ppv["title"]); ?>
            </div>

            <div class="ppv-meta">
                <?php echo $liveViewers; ?> Watching Now
                <?php if (!empty($ppv["category"])): ?>
                    • <?php echo htmlspecialchars($ppv["category"]); ?>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <aside class="chat-side">
        <div class="chat-header">
            <h2>Chat</h2>
        </div>
    
        <div class="chat-messages" id="chatMessages">
            <div class="chat-line">
                <span class="chat-name">
                    <?php if (!empty($badges)): ?>
                        <?php foreach ($badges as $badge): ?>
                            <img
                                src="../<?php echo htmlspecialchars($badge["badge_image"]); ?>"
                                class="chat-badge"
                                title="<?php echo htmlspecialchars($badge["badge_name"]); ?>"
                            >
                        <?php endforeach; ?>
                    <?php endif; ?>
                    <?php echo htmlspecialchars($username); ?>
                </span>
                <span class="chat-message">
                    Joined The Stream.
                </span>
            </div>
        </div>
    
        <div class="chat-input-area">
            <input type="text" placeholder="Send a message" <?php echo $isLoggedIn ? "" : "disabled"; ?>>
            <button class="send-btn">
                <i data-lucide="send"></i>
            </button>
        </div>
    </aside>
</main>

<script>
lucide.createIcons();

function toggleBrowseMenu(event) {
    event.stopPropagation();
    document.getElementById("browseMenu").classList.toggle("active");
    lucide.createIcons();
}

function toggleProfileMenu() {
    const menu = document.getElementById("profileMenu");
    if (menu) menu.classList.toggle("active");
}

document.addEventListener("click", function(e) {
    const browseDropdown = document.querySelector(".browse-dropdown");
    const browseMenu = document.getElementById("browseMenu");

    if (browseDropdown && browseMenu && !browseDropdown.contains(e.target)) {
        browseMenu.classList.remove("active");
    }

    const profileDropdown = document.querySelector(".profile-dropdown");
    const profileMenu = document.getElementById("profileMenu");

    if (profileDropdown && profileMenu && !profileDropdown.contains(e.target)) {
        profileMenu.classList.remove("active");
    }
});
</script>
<script>
const input = document.querySelector(".chat-input-area input");
const sendBtn = document.querySelector(".send-btn");
const chatMessages = document.getElementById("chatMessages");

function sendMessage() {

    const message = input.value.trim();

    if (!message) return;

    const line = document.createElement("div");
    line.className = "chat-line";

    line.innerHTML = `
        <span class="chat-name">

            <?php if (!empty($badges)): ?>
                <?php foreach ($badges as $badge): ?>

                    <img
                        src="../<?php echo htmlspecialchars($badge["badge_image"]); ?>"
                        class="chat-badge"
                    >

                <?php endforeach; ?>
            <?php endif; ?>

            <?php echo htmlspecialchars($username); ?>

        </span>

        <span class="chat-message">
            ${message}
        </span>
    `;

    chatMessages.appendChild(line);

    chatMessages.scrollTop = chatMessages.scrollHeight;

    input.value = "";
}

sendBtn.addEventListener("click", sendMessage);

input.addEventListener("keypress", function(e) {

    if (e.key === "Enter") {
        sendMessage();
    }

});

setInterval(() => {
    fetch(window.location.href, {
        method: "GET",
        headers: {
            "X-Viewer-Ping": "1"
        }
    });
}, 15000);
</script>
<script src="../Security.js"></script>
</body>
</html>