<?php
require 'config.php';
require 'header.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$server_url = "https://rtmp.cenatres.com.br";
$hls_path = "/mnt/hls";

// Buscar todas as aplicações e suas chaves
$stmt = $pdo->query("
    SELECT a.id AS app_id, a.name AS app_name, s.stream_key
    FROM applications a
    LEFT JOIN streams s ON s.app_id = a.id
    ORDER BY a.id
");
$apps = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>



<div class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold text-dark">
            <i class="bi bi-broadcast-pin me-2 text-primary"></i>
            Painel de Transmissões
        </h3>
        <a href="create_live.php" class="btn-modern btn-primary-modern shadow">
    <i class="bi bi-plus-circle"></i> Criar Nova Live
</a>
    </div>

    <div id="lives-container" class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
        <?php foreach ($apps as $app): ?>
            <?php
                $m3u8_file = "$hls_path/{$app['app_name']}/{$app['stream_key']}.m3u8";
                $is_live = @fopen($server_url . "/hls/{$app['app_name']}/{$app['stream_key']}.m3u8", "r") ? true : false;
            ?>
            <div class="col live-card" data-app="<?= htmlspecialchars($app['app_name']) ?>" data-key="<?= htmlspecialchars($app['stream_key']) ?>">
                <div class="card shadow-sm border-0 h-100">
                    <div class="card-body d-flex flex-column">

                        <!-- Nome + Status -->
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h5 class="card-title mb-0 text-capitalize"><?= htmlspecialchars($app['app_name']) ?></h5>
                            <span class="badge <?= $is_live ? 'bg-danger' : 'bg-success' ?>">
                                <?= $is_live ? '🔴 Transmitindo' : '🟢 Ativa' ?>
                            </span>
                        </div>

                        <!-- Player de vídeo ou placeholder -->
                        <?php if ($is_live): ?>
                            <div class="position-relative">
                                <video
                                    id="video_<?= $app['app_name'] ?>"
                                    class="video-js vjs-default-skin mb-3 rounded"
                                    controls
                                    preload="auto"
                                    width="100%"
                                    height="200"
                                    data-setup='{}'>
                                    <source src="<?= $server_url ?>/hls/<?= $app['app_name'] ?>/<?= $app['stream_key'] ?>.m3u8" type="application/x-mpegURL">
                                    </source>
                                </video>

                                <div id="viewers_<?= $app['app_name'] ?>" class="position-absolute top-0 end-0 bg-dark text-white small px2 py-1 rounded-start">
                                    👁 0 assistindo
                                </div>
                            </div>

                        <?php else: ?>
                            <div class="p-4 text-center text-muted border rounded info-box mb-3">
                                <i class="bi bi-broadcast" style="font-size: 2.3rem;"></i>
                                <p class="mt-2 mb-0">Sem transmissão ativa</p>
                            </div>
                        <?php endif; ?>

                        <!-- Informações técnicas -->
                        <div class="mb-3 small">
                            <p><strong>RTMP:</strong> <code>rtmp://rtmp.cenatres.com.br/<?= $app['app_name'] ?></code></p>
                            <p><strong>Stream Key:</strong> <code><?= $app['stream_key'] ?? '—' ?></code></p>
                            <p><strong>HLS:</strong> <code><?= $server_url ?>/hls/<?= $app['app_name'] ?>/<?= $app['stream_key'] ?>.m3u8</code></p>
                        </div>

                        <!-- Botões -->
                        <div class="d-flex justify-content-between mt-auto">
                            <a href="edit_live.php?id=<?= $app['app_id'] ?>" class="btn btn-warning btn-sm">✏️ Editar</a>

                            <!-- Reload NGINX -->
                            <button onclick="reloadNginx(this)" class="btn btn-secondary btn-sm">
                                🔄 Reload NGINX
                            </button>

                            <a href="delete_live.php?id=<?= $app['app_id'] ?>" class="btn btn-danger btn-sm"
                               onclick="return confirm('Deseja realmente excluir esta live?')">
                               🗑 Excluir
                            </a>
                        </div>

                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>
</div>
<!-- Auto-refresh a cada 10s + Função Reload Nginx -->
<script>
function atualizarStatusLives() {
    document.querySelectorAll(".live-card").forEach(card => {
        const app = card.dataset.app;
        const key = card.dataset.key;
        const badge = card.querySelector(".badge");
        const videoContainer = card.querySelector("video");
        const infoDiv = card.querySelector(".info-box");

        fetch(`<?= $server_url ?>/hls/${app}/${key}.m3u8`, { method: "HEAD" })
            .then(res => {
                if (res.ok) {
                    badge.className = "badge bg-danger";
                    badge.textContent = "🔴 Transmitindo";

                    if (!videoContainer) {
                        card.querySelector(".card-body").insertAdjacentHTML("afterbegin", `
                            <video class="video-js vjs-default-skin mb-3 rounded" controls preload="auto" width="100%" height="200" data-setup='{}'>
                                <source src="<?= $server_url ?>/hls/${app}/${key}.m3u8" type="application/x-mpegURL">
                            </video>
                        `);
                        if (infoDiv) infoDiv.remove();
                    }
                } else {
                    badge.className = "badge bg-success";
                    badge.textContent = "🟢 Ativa";
                    if (videoContainer) videoContainer.remove();
                }
            })
            .catch(() => {
                badge.className = "badge bg-success";
                badge.textContent = "🟢 Ativa";
                if (videoContainer) videoContainer.remove();
            });
    });
}

// Função para recarregar o nginx
function reloadNginx(button) {
    button.disabled = true;
    const original = button.innerHTML;
    button.innerHTML = "⏳ Reloading...";

    fetch("reload_nginx.php", { method: "POST" })
        .then(response => response.text())
        .then(result => {
            if (result.trim() === "OK") {
                button.innerHTML = "✔ NGINX Reloaded";
                button.classList.remove("btn-secondary");
                button.classList.add("btn-success");
            } else {
                button.innerHTML = "❌ Erro";
                button.classList.remove("btn-secondary");
                button.classList.add("btn-danger");
            }
        })
        .catch(() => {
            button.innerHTML = "❌ Erro";
            button.classList.remove("btn-secondary");
            button.classList.add("btn-danger");
        })
        .finally(() => {
            setTimeout(() => {
                button.innerHTML = original;
                button.className = "btn btn-secondary btn-sm";
                button.disabled = false;
            }, 3000);
        });
}

// Atualiza a cada 10 segundos
setInterval(atualizarStatusLives, 10000);
document.addEventListener("DOMContentLoaded", atualizarStatusLives);
</script>
<?php require 'footer.php'; ?>