<?php
// online_server.php – DAYBREAK 2025 – FINAL FIXED 100% (NO MORE SYNTAX ERROR)
// → KILL chạy ngon
// → Ảnh hiện đẹp
// → Không còn lỗi ngoặc thừa/thiếu

ini_set('session.use_only_cookies', 0);
ini_set('session.use_cookies', 0);
ini_set('session.use_trans_sid', 1);
ini_set('session.cache_limiter', '');

if (session_status() === PHP_SESSION_NONE) session_start();

header('Cache-Control: no-cache');
header('Access-Control-Allow-Origin: *');
header('X-Accel-Buffering: no');
date_default_timezone_set('Asia/Ho_Chi_Minh');

// Block truy cập trực tiếp nếu không phải SSE hoặc có cmd
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $is_sse  = isset($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], 'text/event-stream') !== false;
    $has_cmd = !empty($_GET['cmd']);
    if (!$is_sse && !$has_cmd) {
        http_response_code(404);
        die('<h1>404 - DAYBREAK PROTECTED</h1>');
    }
}

$online_file = __DIR__.'/online_clients.json';
$proc_file   = __DIR__.'/processes.json';
$images_file = __DIR__.'/images.json';
$queue_dir   = __DIR__.'/queue';

if (!is_dir($queue_dir)) mkdir($queue_dir, 0755, true);
foreach ([$online_file, $proc_file, $images_file] as $f) {
    if (!file_exists($f)) file_put_contents($f, '{}');
}

function load_json($f) { return json_decode(@file_get_contents($f), true) ?: []; }

function save_images_json($data) {
    global $images_file;
    $json = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $json = str_replace('\\\\n', '\\n', $json);
    file_put_contents($images_file, $json);
}

// ===================== BEACON (launcher ping) =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_GET['cmd'])) {
    $input = json_decode(file_get_contents('php://input'), true) ?: [];
    $ip = $_SERVER['REMOTE_ADDR'];
    $hostname = $input['h'] ?? 'Unknown';
    $mac = strtoupper($input['mac'] ?? '00:00:00:00:00:00');

    $clients = load_json($online_file);
    $now = time();

    // Xóa IP cũ nếu trùng MAC + hostname
    foreach ($clients as $old_ip => $info) {
        if ($info['mac'] === $mac && $info['hostname'] === $hostname) {
            unset($clients[$old_ip]);
        }
    }

    $clients[$ip] = [
        'hostname' => $hostname,
        'mac'      => $mac,
        'first_seen' => $clients[$ip]['first_seen'] ?? $now,
        'last_ping'  => $now
    ];
    ksort($clients);
    file_put_contents($online_file, json_encode($clients, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    echo "OK";
    exit;
}

// ===================== ADMIN COMMANDS =====================
if (!empty($_GET['cmd'])) {

    // CHỈ DÙNG REMOTE_ADDR KHI LAUNCHER GỌI CHECK
    if ($_GET['cmd'] === 'check') {
        $client_ip = $_SERVER['REMOTE_ADDR'];
        header('Content-Type: text/plain');
        $cmd_file = "$queue_dir/$client_ip.txt";
        if (file_exists($cmd_file)) {
            $cmd = trim(file_get_contents($cmd_file));
            @unlink($cmd_file);
            echo $cmd;
        } else {
            echo "";
        }
        exit;
    }

    // Các lệnh từ admin
    if ($_GET['cmd'] === 'request' && isset($_GET['ip'])) {
        file_put_contents("$queue_dir/{$_GET['ip']}.txt", "GETPROC|{$_GET['ip']}");
        echo "OK";
        exit;
    }

    if ($_GET['cmd'] === 'requestimg' && isset($_GET['ip'])) {
        file_put_contents("$queue_dir/{$_GET['ip']}.txt", "GETIMG|{$_GET['ip']}");
        echo "ĐÃ GỬI LỆNH CHỤP CHO {$_GET['ip']}";
        exit;
    }

    // KILL ĐÃ HOÀN HẢO
    if ($_GET['cmd'] === 'kill' && isset($_GET['ip']) && isset($_GET['pid'])) {
        $target_ip = $_GET['ip'];
        $pid = $_GET['pid'];
        file_put_contents("$queue_dir/{$target_ip}.txt", "KILLPROC|$target_ip|$pid");
        echo "ĐÃ GỬI LỆNH GIẾT PID $pid CHO $target_ip – CHẾT NGAY!";
        exit;
    }

    if ($_GET['cmd'] === 'uploadproc') {
        $input = json_decode(file_get_contents('php://input'), true);
        if ($input && isset($input['ip']) && isset($input['procs'])) {
            $all = load_json($proc_file);
            $all[$input['ip']] = $input['procs'];
            file_put_contents($proc_file, json_encode($all, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            echo "OK";
        }
        exit;
    }

    if ($_GET['cmd'] === 'getproc' && isset($_GET['ip'])) {
        header('Content-Type: application/json');
        echo json_encode(load_json($proc_file)[$_GET['ip']] ?? [], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Upload ảnh
    if ($_GET['cmd'] === 'uploadimg') {
        $input = json_decode(file_get_contents('php://input'), true);
        if ($input && isset($input['img'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
            $images = load_json($images_file);
            $raw = $input['img'];
            if (strpos($raw, '\\n') !== false) $raw = str_replace('\\n', "\n", $raw);
            $images[$ip] = [
                'img' => $raw,
                'time' => time(),
                'hostname' => gethostbyaddr($ip)
            ];
            save_images_json($images);
            echo "OK";
        } else {
            echo "ERROR";
        }
        exit;
    }

    if ($_GET['cmd'] === 'viewimg' && isset($_GET['ip'])) {
        $ip = $_GET['ip'];
        $images = load_json($images_file);
        if (!empty($images[$ip]['img'])) {
            $img = $images[$ip]['img'];
            if (strpos($img, '\\n') !== false) $img = str_replace('\\n', "\n", $img);
            $time = date('H:i:s d/m/Y', $images[$ip]['time']);
            $host = $images[$ip]['hostname'] ?? $ip;
            echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>CHEATER CAUGHT</title><style>
                body{background:#000;color:#0f0;font-family:Consolas;margin:0;padding:50px;text-align:center;}
                h2{color:#0f0;text-shadow:0 0 30px #0f0;font-size:40px;}
                img{max-width:98%;border:12px solid #f00;border-radius:30px;box-shadow:0 0 100px #f00;margin:40px auto;}
                .btn{padding:25px 100px;font-size:36px;background:#900;color:white;border:none;border-radius:25px;cursor:pointer;margin:15px;}
                .btn:hover{background:#f00;transform:scale(1.1);box-shadow:0 0 80px red;}
                </style></head><body>';
            echo "<h2>CHEATER: <b style='color:#ff0'>$host</b> ($ip)<br>Thời gian: $time</h2>";
            echo "<img src='data:image/png;base64,$img'>";
            echo "<br><br><button class='btn' onclick=\"if(confirm('XÓA ẢNH?')) location.href='?cmd=delimg&ip=$ip'\">XÓA ẢNH</button> <button class='btn' style='background:#444;' onclick='window.close()'>ĐÓNG</button>";
            echo '</body></html>';
        } else {
            echo "<h2 style='color:#f00;font-size:48px;padding-top:100px;'>KHÔNG CÓ ẢNH HOẶC ẢNH BỊ LỖI</h2>";
        }
        exit;
    }

    if ($_GET['cmd'] === 'delimg' && isset($_GET['ip'])) {
        $images = load_json($images_file);
        unset($images[$_GET['ip']]);
        save_images_json($images);
        echo "<h2 style='color:#0f0;font-size:52px;padding-top:200px;'>ĐÃ XÓA SẠCH ẢNH!</h2>";
        exit;
    }
    if ($_GET['cmd'] === 'clearimages') {
        file_put_contents($images_file, '{}');
        echo "ĐÃ XÓA SẠCH TOÀN BỘ ẢNH TRONG images.json!";
        exit;
    }

    if ($_GET['cmd'] === 'clearallproc') {
        file_put_contents($proc_file, '{}');
        echo "ĐÃ XÓA SẠCH TOÀN BỘ PROCESS!";
        exit;
    }
}

// ===================== REALTIME ONLINE =====================
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

while (ob_get_level() > 0) ob_end_clean();
ob_implicit_flush(true);

$clients = load_json($online_file);
$now = time();
foreach ($clients as $ip => $info) {
    if (($now - $info['last_ping']) > 35) unset($clients[$ip]);
}
ksort($clients);
file_put_contents($online_file, json_encode($clients, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

$output = [];
foreach ($clients as $ip => $info) {
    $output[$ip] = [
        'hostname' => $info['hostname'],
        'mac'      => $info['mac'],
        'join'     => date('H:i:s d/m/Y', $info['first_seen'])
    ];
}

echo "data: " . json_encode($output, JSON_UNESCAPED_UNICODE) . "\n\n";
echo "id: " . $now . "\n";
echo "retry: 2000\n\n";
flush();

// ĐÃ SỬA DÒNG LỖI Ở ĐÂY
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
}
ignore_user_abort(true);
exit;
?>