<?php
// ============================================================
// admin_panel.php — GRAY HACKER SECURITY Admin Dashboard
// ============================================================
session_start();
error_reporting(0);

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/points.php';

$ADMIN_WEB_PASS = 'slex@admin2024'; // Change this!

// Auth Login Action
if (isset($_POST['login_pass'])) {
    if ($_POST['login_pass'] === $ADMIN_WEB_PASS) {
        $_SESSION['admin_auth'] = true;
        $_SESSION['admin_role'] = 'admin';
    } else {
        $login_error = '❌ Wrong password!';
    }
}

// Logout Action
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . basename(__FILE__));
    exit;
}

// Secure Stream Download Action
if (isset($_GET['download']) && ($_SESSION['admin_auth'] ?? false)) {
    $jobId = (int)$_GET['download'];
    $jobs  = readJSON(DATA_DIR . '/jobs.json');
    
    if (isset($jobs[$jobId])) {
        $j = $jobs[$jobId];
        
        // Authorization check: Authenticated users are authorized
        $isAuthorized = ($_SESSION['admin_auth'] ?? false);
        
        if ($isAuthorized) {
            $cacheDir = DATA_DIR . '/protected_apks';
            $cachedFile = $j['cached_file'] ?? '';
            $localPath = $cacheDir . '/' . $cachedFile;
            
            $fileData = null;
            $outName = 'protected_' . preg_replace('/[^a-zA-Z0-9._\-]/', '_', $j['apk_name']);
            if (strtolower(substr($outName, -4)) !== '.apk') $outName .= '.apk';
            
            // Check if GitHub URL exists
            if (!empty($j['github_url'])) {
                header('Location: ' . $j['github_url']);
                exit;
            }

            // Check if cached file exists (legacy local fallback)
            if ($cachedFile && file_exists($localPath)) {
                $fileData = file_get_contents($localPath);
            } 
            // Fallback: Stream directly from dexshellx.com if not cached
            elseif (!empty($j['process_id'])) {
                $cookieF = TEMP_DIR . '/admin_cookie_' . md5($jobId . time()) . '.txt';
                $fetchedData = fetchFromServerOnTheFly($j['process_id'], $cookieF);
                if ($fetchedData) {
                    // Cache it to GitHub so future downloads redirect to GitHub
                    $tempPath = TEMP_DIR . '/temp_upload_' . $jobId . '.apk';
                    file_put_contents($tempPath, $fetchedData);
                    $githubUrl = saveToProtectedCache($tempPath, $jobId);
                    @unlink($tempPath);
                    
                    if ($githubUrl) {
                        header('Location: ' . $githubUrl);
                        exit;
                    } else {
                        $fileData = $fetchedData;
                    }
                }
                @unlink($cookieF);
            }
            
            if ($fileData) {
                header('Content-Type: application/vnd.android.package-archive');
                header('Content-Disposition: attachment; filename="' . $outName . '"');
                header('Content-Length: ' . strlen($fileData));
                header('Cache-Control: no-cache, must-revalidate');
                header('Pragma: no-cache');
                echo $fileData;
                exit;
            } else {
                $download_error = "❌ Failed to retrieve APK file. It may have expired or was removed from the protection server.";
            }
        } else {
            $download_error = "🔒 Access Denied: You are not authorized to download this file.";
        }
    } else {
        $download_error = "❌ Job not found.";
    }
}

// Fetch user data
$jobs = [];
if ($_SESSION['admin_auth'] ?? false) {
    $allJobs = readJSON(DATA_DIR . '/jobs.json');
    // Sort jobs descending (newest first)
    krsort($allJobs);
    
    // Show last 20 jobs
    $jobs = array_slice($allJobs, 0, 20, true);
}

// Fallback dynamic downloader helpers
function fetchFromServerOnTheFly($processId, $cookieF) {
    $BASE = DEX_BASE;
    // Login flow
    dexGetHelper($BASE . '/', $cookieF);
    dexGetHelper($BASE . '/dex/login', $cookieF);
    $loginData = http_build_query(['user' => DEX_USER, 'pass' => DEX_PASS, 'language' => 'en_US']);
    dexPostHelper($BASE . '/dex/login', $loginData, 'application/x-www-form-urlencoded', $BASE . '/dex/login', $cookieF);
    
    // Download request
    $downloadUrl = $BASE . '/dex/process/download?id=' . $processId . '&type=apk';
    $ch = curl_init($downloadUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT        => 120,
        CURLOPT_ENCODING       => '',
        CURLOPT_COOKIEFILE     => $cookieF,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => [
            'User-Agent: Mozilla/5.0',
            'Accept: application/octet-stream,*/*',
            'Referer: ' . $BASE . '/dex/process/detail?id=' . $processId,
        ],
    ]);
    $apkData = curl_exec($ch);
    $dlCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $dlType  = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    curl_close($ch);
    
    $isApk = (
        strpos($dlType, 'package-archive') !== false ||
        strpos($dlType, 'octet-stream')    !== false ||
        strpos($dlType, 'application/zip')    !== false
    );
    
    if ($dlCode == 200 && $isApk && strlen($apkData) > 10000) {
        return $apkData;
    }
    return false;
}

function dexGetHelper($url, $cookieF) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_COOKIEJAR      => $cookieF,
        CURLOPT_COOKIEFILE     => $cookieF,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => ['User-Agent: Mozilla/5.0'],
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

function dexPostHelper($url, $postData, $contentType, $referer, $cookieF) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $postData,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_COOKIEJAR      => $cookieF,
        CURLOPT_COOKIEFILE     => $cookieF,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HTTPHEADER     => [
            'User-Agent: Mozilla/5.0',
            'Content-Type: ' . $contentType,
            'Referer: ' . $referer,
        ],
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Admin Panel — GRAY HACKER SECURITY</title>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
:root {
    --bg-dark: #080710;
    --card-bg: rgba(255, 255, 255, 0.05);
    --border-color: rgba(255, 255, 255, 0.1);
    --primary: #6366f1;
    --primary-hover: #4f46e5;
    --text-main: #f8fafc;
    --text-muted: #94a3b8;
    --success: #10b981;
    --error: #ef4444;
    --warn: #f59e0b;
}

* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Outfit', sans-serif;
    background-color: var(--bg-dark);
    color: var(--text-main);
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: flex-start;
    padding: 40px 20px;
    background: radial-gradient(circle at 10% 20%, rgba(99, 102, 241, 0.15) 0%, transparent 40%),
                radial-gradient(circle at 90% 80%, rgba(168, 85, 247, 0.15) 0%, transparent 40%),
                #0b0a19;
}

.login-container {
    margin-top: 10vh;
    width: 100%;
    max-width: 400px;
    background: var(--card-bg);
    backdrop-filter: blur(20px);
    border: 1px solid var(--border-color);
    border-radius: 24px;
    padding: 40px;
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.4);
    text-align: center;
}

.panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    max-width: 900px;
    margin-bottom: 24px;
    background: var(--card-bg);
    backdrop-filter: blur(10px);
    border: 1px solid var(--border-color);
    border-radius: 20px;
    padding: 20px 30px;
}

.panel-container {
    width: 100%;
    max-width: 900px;
    background: var(--card-bg);
    backdrop-filter: blur(10px);
    border: 1px solid var(--border-color);
    border-radius: 24px;
    padding: 30px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

h1 {
    font-size: 24px;
    font-weight: 700;
    letter-spacing: -0.5px;
    background: linear-gradient(135deg, #a5b4fc, #c084fc);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

h2 {
    font-size: 20px;
    font-weight: 600;
    margin-bottom: 20px;
    color: var(--text-main);
}

.desc {
    font-size: 14px;
    color: var(--text-muted);
    margin-bottom: 28px;
}

.form-group {
    margin-bottom: 20px;
    text-align: left;
}

label {
    display: block;
    margin-bottom: 8px;
    font-size: 13px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

input[type="text"], input[type="number"], input[type="password"] {
    width: 100%;
    padding: 14px 18px;
    background: rgba(255, 255, 255, 0.04);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    color: var(--text-main);
    font-size: 15px;
    outline: none;
    transition: 0.2s;
    font-family: inherit;
}

input:focus {
    border-color: var(--primary);
    background: rgba(99, 102, 241, 0.08);
}

.btn {
    display: inline-block;
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, var(--primary), #8b5cf6);
    border: none;
    border-radius: 12px;
    color: var(--text-main);
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: 0.2s;
    text-decoration: none;
    text-align: center;
}

.btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(99, 102, 241, 0.4);
}

.btn-logout {
    background: rgba(255, 255, 255, 0.05);
    border: 1px solid var(--border-color);
    padding: 8px 16px;
    border-radius: 10px;
    color: var(--text-muted);
    text-decoration: none;
    font-size: 14px;
    transition: 0.2s;
}

.btn-logout:hover {
    background: var(--error);
    color: white;
    border-color: transparent;
}

.alert {
    padding: 12px 18px;
    border-radius: 12px;
    font-size: 14px;
    margin-bottom: 24px;
    text-align: left;
    border: 1px solid transparent;
}

.alert-error {
    background: rgba(239, 68, 68, 0.1);
    color: #fca5a5;
    border-color: rgba(239, 68, 68, 0.2);
}

.user-info {
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: var(--text-muted);
}

.user-info strong {
    color: var(--text-main);
}

/* Table styling */
.table-container {
    width: 100%;
    overflow-x: auto;
    margin-top: 10px;
}

table {
    width: 100%;
    border-collapse: collapse;
    text-align: left;
}

th, td {
    padding: 16px;
    border-bottom: 1px solid var(--border-color);
    font-size: 14px;
}

th {
    color: var(--text-muted);
    font-weight: 600;
    text-transform: uppercase;
    font-size: 12px;
    letter-spacing: 0.5px;
}

tr:hover td {
    background: rgba(255, 255, 255, 0.02);
}

.status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

.status-done { background: rgba(16, 185, 129, 0.15); color: #34d399; }
.status-processing { background: rgba(245, 158, 11, 0.15); color: #fbbf24; }
.status-failed, .status-timeout, .status-refunded { background: rgba(239, 68, 68, 0.15); color: #fca5a5; }

.btn-download {
    display: inline-flex;
    align-items: center;
    padding: 6px 12px;
    background: rgba(99, 102, 241, 0.1);
    border: 1px solid var(--primary);
    border-radius: 8px;
    color: #a5b4fc;
    text-decoration: none;
    font-size: 12px;
    font-weight: 600;
    transition: 0.2s;
}

.btn-download:hover {
    background: var(--primary);
    color: white;
}

.empty-state {
    text-align: center;
    padding: 40px;
    color: var(--text-muted);
    font-size: 15px;
}
</style>
</head>
<body>

<?php if (!($_SESSION['admin_auth'] ?? false)): ?>
    <!-- LOGIN SCREEN -->
    <div class="login-container">
        <div style="font-size: 40px; margin-bottom: 12px;">🛡️</div>
        <h2>GRAY HACKER SECURITY App History</h2>
        <p class="desc">Log in using the administrator password to access and download protected applications.</p>
        
        <?php if (isset($login_error)): ?>
            <div class="alert alert-error"><?= $login_error ?></div>
        <?php endif; ?>
        
        <form method="POST">
            <div class="form-group">
                <label for="login_pass">Admin Password</label>
                <input type="password" id="login_pass" name="login_pass" required placeholder="Enter password" autofocus>
            </div>
            <button type="submit" class="btn">Access Panel</button>
        </form>
    </div>
<?php else: ?>
    <!-- DASHBOARD PANEL -->
    <div class="panel-header">
        <div>
            <h1>🛡️ GRAY HACKER SECURITY App History</h1>
            <div class="user-info" style="margin-top: 8px;">
                <span>Role: <strong style="text-transform: capitalize; color:#c084fc;">Administrator</strong></span>
            </div>
        </div>
        <div>
            <a href="?logout=1" class="btn-logout">Logout</a>
        </div>
    </div>
    
    <div class="panel-container">
        <h2>📲 Recent Protected Applications</h2>
        
        <?php if (isset($download_error)): ?>
            <div class="alert alert-error" style="margin-bottom: 20px;"><?= $download_error ?></div>
        <?php endif; ?>
        
        <div class="table-container">
            <?php if (empty($jobs)): ?>
                <div class="empty-state">No jobs found in your history. Send an APK file to the bot first!</div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Job ID</th>
                            <th>File Name</th>
                            <th>Status</th>
                            <th>Time</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($jobs as $id => $j): ?>
                            <tr>
                                <td><strong>#<?= $id ?></strong></td>
                                <td><?= htmlspecialchars($j['apk_name'] ?? 'app.apk') ?></td>
                                <td>
                                    <span class="status-badge status-<?= strtolower($j['status'] ?? 'processing') ?>">
                                        <?= htmlspecialchars($j['status'] ?? 'processing') ?>
                                    </span>
                                </td>
                                <td><?= htmlspecialchars(date('M d, H:i', strtotime($j['started_at'] ?? 'now'))) ?></td>
                                <td>
                                    <?php if ($j['status'] === 'done'): ?>
                                        <a href="?download=<?= $id ?>" class="btn-download">⬇️ Download APK</a>
                                    <?php else: ?>
                                        <span style="color: var(--text-muted); font-size:12px;">N/A</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>
<?php endif; ?>

</body>
</html>
