<?php
session_start();

$dataFile = __DIR__ . '/data.json';
$streams = require __DIR__ . '/streams.php'; // Stream IDs with hashed passwords

// LOGOUT
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

// LOGIN
if (isset($_POST['login'])) {
    $stream_id = trim($_POST['stream_id']);
    $password = trim($_POST['password']);

    if (isset($streams[$stream_id]) && password_verify($password, $streams[$stream_id])) {
        $_SESSION['stream_id'] = $stream_id;
        header("Location: index.php");
        exit;
    }
    $error = "Invalid Stream ID or password";
}

// Show login form if not logged in
if (!isset($_SESSION['stream_id'])):
?>
<!DOCTYPE html>
<html>
<head>
<title>Streamer Login</title>
<style>
body{background:#0f172a;color:#e5e7eb;font-family:Arial;display:flex;justify-content:center;align-items:center;height:100vh}
.box{background:#1e293b;padding:40px;border-radius:12px;width:320px}
input,button{width:100%;padding:10px;margin:10px 0;border-radius:6px;border:none}
input{background:#334155;color:#fff}
button{background:#22c55e;font-weight:bold}
.error{color:#f87171;text-align:center}
</style>
</head>
<body>
<div class="box">
<h2 align="center">Streamer Login</h2>
<?php if(!empty($error)) echo "<div class='error'>$error</div>"; ?>
<form method="post">
<input name="stream_id" placeholder="Stream ID" required>
<input type="password" name="password" placeholder="Password" required>
<button name="login">Login</button>
</form>
</div>
</body>
</html>
<?php exit; endif; ?>

<?php
// LOAD DATA
$data = file_exists($dataFile) ? json_decode(file_get_contents($dataFile), true) : [];
if (!is_array($data)) $data = [];

// FILTER ONLY LOGGED-IN STREAM
$stream_id = $_SESSION['stream_id'];
$data = isset($data[$stream_id]) ? [$stream_id => $data[$stream_id]] : [];
?>

<!DOCTYPE html>
<html>
<head>
<title>Live Stream Statistics</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body{background:#0f172a;color:#e5e7eb;font-family:Arial;padding:20px;}
.card{background:#1e293b;padding:20px;border-radius:12px;margin-bottom:25px;}
.count{color:#22c55e;font-size:22px;font-weight:bold;}
.peak{color:#fbbf24;font-size:14px;margin-top:2px;}
.country-summary{margin:5px 0;display:flex;flex-wrap:wrap;gap:5px;}
.country-summary span{display:flex;align-items:center;font-size:13px;margin-right:10px;}
.country-summary img{width:16px;height:11px;margin-right:3px;border-radius:2px;}
table{width:100%;border-collapse:collapse;margin-top:10px;}
th,td{padding:8px;border-bottom:1px solid #334155;font-size:14px;color:#e5e7eb;}
th{background:#020617;}
.flag{width:18px;border-radius:3px;vertical-align:middle;}
a{color:#38bdf8;}
canvas{margin-top:10px;border-radius:8px;background:#1e293b;padding:10px;}
</style>
</head>
<body>

<h1>📡 Stream: <?= htmlspecialchars($stream_id) ?></h1>
<p><a href="?logout=1">Logout</a></p>

<div id="streams"></div>

<script>
let charts = {};

async function loadData() {
    try {
        const res = await fetch('data.json?_=' + new Date().getTime());
        const fullData = await res.json();
        const data = fullData['<?= addslashes($stream_id) ?>'] ? {'<?= addslashes($stream_id) ?>': fullData['<?= addslashes($stream_id) ?>']} : {};

        const container = document.getElementById('streams');
        container.innerHTML = '';

        for (const stream in data) {
            const info = data[stream];
            const card = document.createElement('div');
            card.className = 'card';

            const h2 = document.createElement('h2');
            h2.textContent = '🎥 ' + stream;
            card.appendChild(h2);

            const countDiv = document.createElement('div');
            countDiv.className = 'count';
            countDiv.textContent = info.count + ' viewers';
            card.appendChild(countDiv);

            const peakDiv = document.createElement('div');
            peakDiv.className = 'peak';
            peakDiv.textContent = 'Peak: ' + (info.peak || 0);
            card.appendChild(peakDiv);

            // Country summary
            if (info.countries) {
                const countryDiv = document.createElement('div');
                countryDiv.className = 'country-summary';
                for (const country in info.countries) {
                    const span = document.createElement('span');
                    let code = '';
                    for (const v of info.viewers) { if (v.country === country) { code = v.code; break; } }
                    const img = document.createElement('img');
                    img.src = code ? `images/flags/${code}.png` : 'images/flags/unknown.png';
                    img.alt = country;
                    span.appendChild(img);
                    span.appendChild(document.createTextNode(`${country} (${info.countries[country]})`));
                    countryDiv.appendChild(span);
                }
                card.appendChild(countryDiv);

                const canvas = document.createElement('canvas');
                canvas.id = 'chart_' + stream;
                canvas.height = 100;
                card.appendChild(canvas);

                if (charts[stream]) charts[stream].destroy();

                const ctx = canvas.getContext('2d');
                charts[stream] = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: Object.keys(info.countries),
                        datasets: [{
                            label: 'Viewers per Country',
                            data: Object.values(info.countries),
                            backgroundColor: [
                                'rgba(34,197,94,0.7)',
                                'rgba(59,130,246,0.7)',
                                'rgba(251,191,36,0.7)',
                                'rgba(239,68,68,0.7)',
                                'rgba(168,85,247,0.7)',
                                'rgba(16,185,129,0.7)'
                            ],
                            borderColor: [
                                'rgba(34,197,94,1)',
                                'rgba(59,130,246,1)',
                                'rgba(251,191,36,1)',
                                'rgba(239,68,68,1)',
                                'rgba(168,85,247,1)',
                                'rgba(16,185,129,1)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive:true,
                        plugins:{legend:{display:false}},
                        scales:{y:{beginAtZero:true,ticks:{color:'#e5e7eb'}},x:{ticks:{color:'#e5e7eb'}}}
                    }
                });
            }

            // Viewer table
            if (info.viewers) {
                const table = document.createElement('table');
                const tr = document.createElement('tr');
                ['','IP','Country','City','User Agent','Last Seen'].forEach(h => {
                    const th = document.createElement('th');
                    th.textContent = h;
                    tr.appendChild(th);
                });
                table.appendChild(tr);

                for (const v of info.viewers) {
                    const tr = document.createElement('tr');
                    const tdFlag = document.createElement('td');
                    const img = document.createElement('img');
                    img.src = v.code ? `images/flags/${v.code}.png` : 'images/flags/unknown.png';
                    img.className = 'flag';
                    tdFlag.appendChild(img);
                    tr.appendChild(tdFlag);

                    ['ip','country','city','ua','last'].forEach(k => {
                        const td = document.createElement('td');
                        td.textContent = v[k];
                        tr.appendChild(td);
                    });
                    table.appendChild(tr);
                }
                card.appendChild(table);
            }

            container.appendChild(card);
        }

    } catch(e) {
        console.error('Error loading data', e);
    }
}

// Initial load
loadData();
// Update every 5 seconds
setInterval(loadData, 5000);
</script>

</body>
</html>
