<?php
/**
 * QUANTUM_NEXUS_V15.5 - PROACTIVE CACHE EDITION
 * DESIGN: ORIGINAL V15 (REDACTED)
 * LOGIC: High-Speed File Serving + Admin Build Triggers
 */

error_reporting(0);
ini_set('display_errors', 0);
set_time_limit(0);
ini_set('memory_limit', '512M');
ignore_user_abort(true);

$db_file = "db.sqlite";
$m3u_file = "master_playlist.m3u";

$u = $_GET['username'] ?? $_GET['u'] ?? '';
$p = $_GET['password'] ?? $_GET['p'] ?? '';
$action = $_GET['action'] ?? ''; // Trigger für admin.php

// --- DATABASE CONNECT ---
try {
    $db = new PDO("sqlite:$db_file");
    $stmt = $db->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
    $stmt->execute([$u, $p]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) { exit; }

// --- CACHE ENGINE LOGIC ---
// Cache-Pfad basierend auf User + seinen Kategorien
$cache_path = "/tmp/nexus_cache_" . md5($u . ($user['categories'] ?? '')) . ".m3u";

// Funktion zum Bauen der Playlist (wird von admin.php oder beim Erstaufruf getriggert)
function buildPlaylistCache($m3u_source, $target, $user_data) {
    if (!file_exists($m3u_source)) return false;
    
    $f_out = fopen($target, "w");
    fwrite($f_out, "#EXTM3U" . PHP_EOL);

    $cats = explode(",", $user_data['categories'] ?? '');
    $all = (in_array("*", $cats) || ($user_data['categories'] ?? '') === "*");

    $f_in = fopen($m3u_source, "r");
    $buffer = "";
    $print = false;

    while (($line = fgets($f_in)) !== false) {
        if (strpos($line, '#EXTINF') === 0) {
            $print = $all;
            if (!$all) {
                foreach($cats as $c) {
                    if ($c !== "" && strpos($line, 'group-title="' . $c . '"') !== false) {
                        $print = true; break;
                    }
                }
            }
            $buffer = $line;
        } elseif (strpos($line, '#') === 0) {
            $buffer .= $line;
        } else {
            if ($print && strlen($line) > 10) {
                fwrite($f_out, $buffer . $line);
            }
            $buffer = ""; $print = false;
        }
    }
    fclose($f_in);
    fclose($f_out);
    return true;
}

// --- ADMIN ACTIONS ---
if ($action === 'delete') {
    if (file_exists($cache_path)) unlink($cache_path);
    exit("CACHE_DELETED");
}

if ($action === 'build' && $user) {
    buildPlaylistCache($m3u_file, $cache_path, $user);
    exit("CACHE_BUILT");
}

// --- PLAYER & DASHBOARD LOGIC ---
$ua = $_SERVER['HTTP_USER_AGENT'];
$is_browser = preg_match('/(Mozilla|Chrome|Safari|Edge|Firefox|Mobile|Opera)/i', $ua);

// Auth Engine
$ip = $_SERVER['REMOTE_ADDR'];
$ip_file = "/tmp/ips_" . $u . ".json";
$active_ips = file_exists($ip_file) ? json_decode(file_get_contents($ip_file), true) : [];
if (!is_array($active_ips)) $active_ips = [];

$is_auth = ($user && in_array($ip, $active_ips));
$limit = (int)($user['max_ips'] ?? 0);

if (!$is_auth && count($active_ips) < $limit && $user && !$is_browser) {
    $active_ips[] = $ip;
    file_put_contents($ip_file, json_encode($active_ips));
    $is_auth = true;
}

$now = time();
$exp = (int)($user['expires'] ?? 0);
$days = floor(($exp - $now) / 86400);

// PLAYER WEICHE
if (!$is_browser) {
    if (!$user || $now > $exp || $user['active'] == 0) {
        header('HTTP/1.1 403 Forbidden'); exit;
    }

    header('Content-Type: audio/mpegurl');
    // Falls Cache fehlt (proaktives Erstellen fehlgeschlagen), jetzt bauen
    if (!file_exists($cache_path)) {
        buildPlaylistCache($m3u_file, $cache_path, $user);
    }
    readfile($cache_path);
    exit;
}

// --- DASHBOARD (DEIN ORIGINAL V15 DESIGN) ---
$color = ($is_auth && $now < $exp) ? "#00d4ff" : "#ff0055";
$load = sys_getloadavg();
$mem_p = memory_get_peak_usage(true);
$m3u_sz = file_exists($m3u_file) ? filesize($m3u_file) : 0;
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QUANTUM_NEXUS_V15</title>
    <style>
        :root { --main: <?= $color ?>; --bg: #05080a; --card: rgba(10, 15, 20, 0.95); --border: rgba(0, 212, 255, 0.1); }
        body { background: var(--bg); color: #e0e0e0; font-family: 'Inter', -apple-system, sans-serif; margin: 0; padding: 20px; font-size: 12px; }
        .top-banner { display: flex; justify-content: space-between; align-items: center; padding: 20px; border: 1px solid var(--border); background: var(--card); margin-bottom: 20px; border-left: 4px solid var(--main); }
        .top-banner h1 { margin: 0; font-size: 18px; letter-spacing: 3px; color: var(--main); }
        .nexus-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 20px; max-width: 1400px; margin: auto; }
        .card { background: var(--card); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; position: relative; }
        .card-header { background: rgba(255,255,255,0.03); padding: 12px 15px; border-bottom: 1px solid var(--border); font-weight: 800; font-size: 10px; color: var(--main); text-transform: uppercase; display: flex; justify-content: space-between; }
        .card-body { padding: 15px; }
        .data-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.03); }
        .lbl { color: #888; font-size: 11px; }
        .val { font-weight: 600; font-family: 'Monaco', monospace; }
        .big-val { font-size: 28px; font-weight: 200; color: #fff; margin-bottom: 5px; }
        .progress-bar { height: 4px; background: rgba(255,255,255,0.05); border-radius: 2px; margin-top: 10px; overflow: hidden; }
        .progress-fill { height: 100%; background: var(--main); box-shadow: 0 0 10px var(--main); transition: width 1.5s ease-in-out; }
    </style>
</head>
<body>

<div class="top-banner">
    <div>
        <h1>QUANTUM_NEXUS_V15</h1>
        <div style="font-size: 10px; opacity: 0.5;">SERVER: <?= $_SERVER['SERVER_ADDR'] ?> // PROACTIVE_CACHE</div>
    </div>
    <div style="text-align: right;"><div id="live-clock" style="font-size: 20px; font-weight: 100;">00:00:00</div></div>
</div>

<div class="nexus-grid">
    <div class="card">
        <div class="card-header">ACCOUNT_IDENT <span>SEKTOR_01</span></div>
        <div class="card-body">
            <div class="lbl">MASTER_OPERATOR</div>
            <div class="big-val"><?= htmlspecialchars($u) ?></div>
            <div class="data-row"><span class="lbl">STATUS</span><span class="val" style="color:var(--main)">ACTIVE</span></div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">TEMPORAL_STATUS <span>SEKTOR_02</span></div>
        <div class="card-body">
            <div class="lbl">REMAINING_DURATION</div>
            <div class="big-val"><?= $days ?> TAGE</div>
            <div class="progress-bar"><div class="progress-fill" style="width: <?= min(100, ($days/30)*100) ?>%"></div></div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">NETWORK_CONN <span>SEKTOR_03</span></div>
        <div class="card-body">
            <div class="lbl">ACTIVE_GATEWAYS</div>
            <div class="big-val"><?= count($active_ips) ?> / <?= $limit ?></div>
            <div class="data-row" style="margin-top:15px;"><span class="lbl">AKTUELLE_IP</span><span class="val"><?= $ip ?></span></div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">CONTENT_METRICS <span>SEKTOR_04</span></div>
        <div class="card-body">
            <div class="data-row"><span class="lbl">M3U_FILE_SIZE</span><span class="val"><?= round($m3u_sz/1024/1024, 2) ?> MB</span></div>
            <div class="data-row"><span class="lbl">CACHE_STATUS</span><span class="val" style="color:#00ff88"><?= file_exists($cache_path) ? 'READY' : 'GENERATING' ?></span></div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">HARDWARE_CORE <span>SEKTOR_05</span></div>
        <div class="card-body">
            <div class="data-row"><span class="lbl">CPU_LOAD</span><span class="val"><?= $load[0] ?>%</span></div>
            <div class="data-row"><span class="lbl">RAM_PEAK</span><span class="val"><?= round($mem_p/1024/1024, 2) ?> MB</span></div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">SECURITY_LOG <span>SEKTOR_06</span></div>
        <div class="card-body" style="font-family:monospace; font-size:9px; height: 100px; overflow-y: auto;">
            <?php foreach($active_ips as $aip): ?>
                <div style="color:var(--main); margin-bottom:5px;">> IP_VERIFIED: <?= $aip ?></div>
            <?php endforeach; ?>
            <div style="opacity:0.3;">> PROACTIVE_CACHE: ENABLED</div>
        </div>
    </div>
</div>

<script>
    function updateClock() { document.getElementById('live-clock').innerText = new Date().toLocaleTimeString(); }
    setInterval(updateClock, 1000); updateClock();
</script>
</body>
</html>

