<?php
// ============================================================
//  Webhook Setup & Admin Panel
//  URL: https://yoursite.com/videoupload/setup.php
//  Bu sahifani ishlatib bo'lgach, kirish parolini o'zgartiring!
// ============================================================

require_once __DIR__ . '/config.php';

// ── Admin parol (o'zgartiring!) ────────────────────────────────
define('SETUP_PASSWORD', 'admin1234');

// ── Session ───────────────────────────────────────────────────
session_start();

$isLoggedIn = ($_SESSION['setup_auth'] ?? false) === true;
$message    = '';
$msgType    = '';

// ── Login ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    if ($_POST['action'] === 'login') {
        if (trim($_POST['password'] ?? '') === SETUP_PASSWORD) {
            $_SESSION['setup_auth'] = true;
            $isLoggedIn = true;
        } else {
            $message = '❌ Parol noto\'g\'ri!';
            $msgType = 'error';
        }
    }

    if ($_POST['action'] === 'logout') {
        session_destroy();
        header('Location: setup.php');
        exit;
    }

    if ($isLoggedIn && $_POST['action'] === 'set_webhook') {
        $webhookUrl = trim($_POST['webhook_url'] ?? '');
        if (!filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
            $message = '❌ Noto\'g\'ri URL formati!';
            $msgType = 'error';
        } else {
            $apiUrl   = 'https://api.telegram.org/bot' . BOT_TOKEN . '/setWebhook';
            $response = file_get_contents($apiUrl . '?url=' . urlencode($webhookUrl));
            $result   = json_decode($response, true);
            if (!empty($result['ok'])) {
                $message = '✅ Webhook muvaffaqiyatli o\'rnatildi!';
                $msgType = 'success';
            } else {
                $message = '❌ Xato: ' . ($result['description'] ?? 'Noma\'lum');
                $msgType = 'error';
            }
        }
    }

    if ($isLoggedIn && $_POST['action'] === 'delete_webhook') {
        $apiUrl   = 'https://api.telegram.org/bot' . BOT_TOKEN . '/deleteWebhook';
        $response = file_get_contents($apiUrl);
        $result   = json_decode($response, true);
        if (!empty($result['ok'])) {
            $message = '✅ Webhook o\'chirildi.';
            $msgType = 'success';
        } else {
            $message = '❌ Xato: ' . ($result['description'] ?? 'Noma\'lum');
            $msgType = 'error';
        }
    }
}

// ── Webhook holati ────────────────────────────────────────────
$webhookInfo = null;
$botInfo     = null;
if ($isLoggedIn) {
    $raw = @file_get_contents('https://api.telegram.org/bot' . BOT_TOKEN . '/getWebhookInfo');
    $webhookInfo = json_decode($raw, true)['result'] ?? null;

    $rawBot  = @file_get_contents('https://api.telegram.org/bot' . BOT_TOKEN . '/getMe');
    $botInfo = json_decode($rawBot, true)['result'] ?? null;
}

// ── Joriy URL ─────────────────────────────────────────────────
$scheme     = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host       = $_SERVER['HTTP_HOST'];
$dir        = dirname($_SERVER['REQUEST_URI']);
$suggestedUrl = $scheme . '://' . $host . rtrim($dir, '/') . '/bot.php?secret=' . WEBHOOK_SECRET;
?>
<!DOCTYPE html>
<html lang="uz">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bot Webhook Setup</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --bg:        #0d0f18;
            --surface:   #161927;
            --surface2:  #1e2235;
            --border:    #2a2f4a;
            --accent:    #4f8ef7;
            --accent2:   #7c3aed;
            --green:     #22c55e;
            --red:       #ef4444;
            --yellow:    #f59e0b;
            --text:      #e2e8f0;
            --muted:     #8892ab;
            --radius:    14px;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg);
            color: var(--text);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 24px 16px;
        }

        /* ── Header ── */
        .header {
            width: 100%;
            max-width: 820px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 32px;
        }
        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 1.3rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--accent), var(--accent2));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .logo svg { flex-shrink: 0; }

        /* ── Card ── */
        .card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 28px 32px;
            width: 100%;
            max-width: 820px;
            margin-bottom: 20px;
        }
        .card-title {
            font-size: .8rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: .08em;
            color: var(--muted);
            margin-bottom: 18px;
        }

        /* ── Login ── */
        .login-wrap {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 60px;
        }
        .login-icon {
            width: 72px;
            height: 72px;
            background: linear-gradient(135deg, #1e2ebc33, #7c3aed33);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            margin-bottom: 20px;
            border: 1px solid var(--border);
        }
        .login-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 36px 40px;
            width: 100%;
            max-width: 420px;
        }
        .login-card h2 {
            font-size: 1.4rem;
            font-weight: 700;
            margin-bottom: 6px;
            text-align: center;
        }
        .login-card p {
            text-align: center;
            color: var(--muted);
            font-size: .9rem;
            margin-bottom: 28px;
        }

        /* ── Form elements ── */
        label {
            display: block;
            font-size: .85rem;
            font-weight: 500;
            color: var(--muted);
            margin-bottom: 6px;
        }
        input[type="password"],
        input[type="text"],
        input[type="url"] {
            width: 100%;
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 9px;
            padding: 11px 14px;
            color: var(--text);
            font-family: inherit;
            font-size: .95rem;
            outline: none;
            transition: border-color .2s;
            margin-bottom: 16px;
        }
        input:focus { border-color: var(--accent); }
        input::placeholder { color: var(--muted); }

        /* ── Buttons ── */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 11px 22px;
            border-radius: 9px;
            border: none;
            font-family: inherit;
            font-size: .9rem;
            font-weight: 600;
            cursor: pointer;
            transition: opacity .2s, transform .1s;
            text-decoration: none;
        }
        .btn:hover { opacity: .88; transform: translateY(-1px); }
        .btn:active { transform: translateY(0); }
        .btn-primary { background: linear-gradient(135deg, var(--accent), var(--accent2)); color: #fff; width: 100%; justify-content: center; }
        .btn-success { background: var(--green); color: #fff; }
        .btn-danger  { background: var(--red); color: #fff; }
        .btn-ghost   { background: var(--surface2); color: var(--text); border: 1px solid var(--border); }

        /* ── Alert ── */
        .alert {
            padding: 12px 16px;
            border-radius: 9px;
            font-size: .9rem;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .alert.success { background: #16a34a22; border: 1px solid #22c55e55; color: var(--green); }
        .alert.error   { background: #dc262622; border: 1px solid #ef444455; color: var(--red); }

        /* ── Status grid ── */
        .stat-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 14px;
            margin-bottom: 0;
        }
        .stat-box {
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 16px;
        }
        .stat-label { font-size: .75rem; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; margin-bottom: 6px; }
        .stat-value { font-size: 1rem; font-weight: 600; }
        .badge {
            display: inline-flex;
            align-items: center;
            gap: 5px;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: .8rem;
            font-weight: 600;
        }
        .badge-green { background: #22c55e22; color: var(--green); border: 1px solid #22c55e44; }
        .badge-red   { background: #ef444422; color: var(--red);   border: 1px solid #ef444444; }
        .badge-gray  { background: var(--surface2); color: var(--muted); border: 1px solid var(--border); }

        /* ── URL box ── */
        .url-box {
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 9px;
            padding: 12px 14px;
            font-family: 'Courier New', monospace;
            font-size: .82rem;
            color: var(--accent);
            word-break: break-all;
            margin-bottom: 8px;
        }

        /* ── Action row ── */
        .action-row {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            align-items: flex-end;
        }
        .action-row input { margin-bottom: 0; flex: 1; min-width: 220px; }

        /* ── Steps ── */
        .steps { counter-reset: step; }
        .step {
            display: flex;
            gap: 14px;
            margin-bottom: 14px;
            align-items: flex-start;
        }
        .step-num {
            counter-increment: step;
            width: 28px;
            height: 28px;
            min-width: 28px;
            background: linear-gradient(135deg, var(--accent), var(--accent2));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: .75rem;
            font-weight: 700;
            margin-top: 2px;
        }
        .step-num::before { content: counter(step); }
        .step-body { flex: 1; }
        .step-body strong { display: block; margin-bottom: 3px; font-size: .95rem; }
        .step-body span { color: var(--muted); font-size: .85rem; line-height: 1.5; }

        /* ── Nav ── */
        .nav-bar {
            width: 100%;
            max-width: 820px;
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
        }

        code {
            background: var(--surface2);
            border: 1px solid var(--border);
            border-radius: 5px;
            padding: 1px 6px;
            font-size: .82rem;
            color: var(--accent);
        }

        .divider { border: none; border-top: 1px solid var(--border); margin: 20px 0; }

        @media (max-width: 540px) {
            .card { padding: 20px 18px; }
            .login-card { padding: 28px 20px; }
        }
    </style>
</head>
<body>

<div class="header">
    <div class="logo">
        <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
            <rect width="32" height="32" rx="8" fill="url(#g1)"/>
            <path d="M8 16.5L13 21.5L24 10.5" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
            <defs>
                <linearGradient id="g1" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
                    <stop stop-color="#4f8ef7"/>
                    <stop offset="1" stop-color="#7c3aed"/>
                </linearGradient>
            </defs>
        </svg>
        M3U8 Bot — Admin Panel
    </div>
</div>

<?php if (!$isLoggedIn): ?>
<!-- ══════════════════════ LOGIN ══════════════════════ -->
<div class="login-wrap">
    <div class="login-icon">🔐</div>
    <div class="login-card">
        <h2>Admin Panel</h2>
        <p>Davom etish uchun parolni kiriting</p>

        <?php if ($message): ?>
        <div class="alert <?= $msgType ?>"><span><?= $message ?></span></div>
        <?php endif; ?>

        <form method="POST">
            <input type="hidden" name="action" value="login">
            <label for="password">Parol</label>
            <input type="password" id="password" name="password" placeholder="••••••••" autofocus required>
            <button type="submit" class="btn btn-primary">Kirish</button>
        </form>

        <hr class="divider">
        <p style="text-align:center;color:var(--muted);font-size:.78rem;">
            Parolni <code>setup.php</code> faylidan o'zgartiring.
        </p>
    </div>
</div>

<?php else: ?>
<!-- ══════════════════════ DASHBOARD ══════════════════════ -->
<div class="nav-bar">
    <form method="POST" style="display:inline">
        <input type="hidden" name="action" value="logout">
        <button type="submit" class="btn btn-ghost">⬅ Chiqish</button>
    </form>
</div>

<?php if ($message): ?>
<div style="width:100%;max-width:820px">
    <div class="alert <?= $msgType ?>"><?= $message ?></div>
</div>
<?php endif; ?>

<!-- Bot ma'lumotlari -->
<?php if ($botInfo): ?>
<div class="card">
    <div class="card-title">🤖 Bot Ma'lumotlari</div>
    <div class="stat-grid">
        <div class="stat-box">
            <div class="stat-label">Bot nomi</div>
            <div class="stat-value"><?= htmlspecialchars($botInfo['first_name']) ?></div>
        </div>
        <div class="stat-box">
            <div class="stat-label">Username</div>
            <div class="stat-value"><a href="https://t.me/<?= $botInfo['username'] ?>" target="_blank" style="color:var(--accent);text-decoration:none">@<?= htmlspecialchars($botInfo['username']) ?></a></div>
        </div>
        <div class="stat-box">
            <div class="stat-label">Bot ID</div>
            <div class="stat-value"><code><?= $botInfo['id'] ?></code></div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Webhook holati -->
<?php if ($webhookInfo !== null): ?>
<div class="card">
    <div class="card-title">🔗 Webhook Holati</div>
    <div class="stat-grid">
        <div class="stat-box">
            <div class="stat-label">Holat</div>
            <div class="stat-value">
                <?php if (!empty($webhookInfo['url'])): ?>
                    <span class="badge badge-green">✅ Ulangan</span>
                <?php else: ?>
                    <span class="badge badge-red">❌ Ulanmagan</span>
                <?php endif; ?>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-label">Pending updates</div>
            <div class="stat-value">
                <?php
                    $pending = $webhookInfo['pending_update_count'] ?? 0;
                    $color   = $pending > 10 ? 'var(--yellow)' : 'var(--green)';
                ?>
                <span style="color:<?= $color ?>"><?= $pending ?></span>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-label">So'nggi xato</div>
            <div class="stat-value" style="font-size:.85rem;color:var(--red)">
                <?= htmlspecialchars($webhookInfo['last_error_message'] ?? '—') ?>
            </div>
        </div>
    </div>

    <?php if (!empty($webhookInfo['url'])): ?>
    <div style="margin-top:14px">
        <div class="stat-label" style="margin-bottom:6px">Joriy URL</div>
        <div class="url-box"><?= htmlspecialchars($webhookInfo['url']) ?></div>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- Webhook o'rnatish -->
<div class="card">
    <div class="card-title">⚙️ Webhook O'rnatish</div>

    <label>Tavsiya etilgan Webhook URL (shu sayt uchun)</label>
    <div class="url-box" id="suggestedUrl"><?= htmlspecialchars($suggestedUrl) ?></div>
    <button class="btn btn-ghost" style="margin-bottom:20px;font-size:.8rem;padding:7px 14px"
            onclick="document.getElementById('webhookInput').value=document.getElementById('suggestedUrl').innerText">
        📋 Ushbu URL ni qo'ying
    </button>

    <form method="POST">
        <input type="hidden" name="action" value="set_webhook">
        <label for="webhookInput">Webhook URL</label>
        <div class="action-row">
            <input type="url" id="webhookInput" name="webhook_url"
                   placeholder="https://yoursite.com/videoupload/bot.php?secret=..." required>
            <button type="submit" class="btn btn-success">✅ O'rnatish</button>
        </div>
    </form>

    <hr class="divider">

    <form method="POST" onsubmit="return confirm('Webhookni o\'chirishni tasdiqlaysizmi?')">
        <input type="hidden" name="action" value="delete_webhook">
        <button type="submit" class="btn btn-danger">🗑 Webhookni O'chirish</button>
    </form>
</div>

<!-- Qo'llanma -->
<div class="card">
    <div class="card-title">📖 Sozlash Bo'yicha Qo'llanma</div>
    <div class="steps">
        <div class="step">
            <div class="step-num"></div>
            <div class="step-body">
                <strong>config.php ni to'ldiring</strong>
                <span>BOT_TOKEN, MADELINE_API_ID, MADELINE_API_HASH</span>
            </div>
        </div>
        <div class="step">
            <div class="step-num"></div>
            <div class="step-body">
                <strong>Yuqoridagi URL ni Webhook maydonga joylashtiring</strong>
                <span>«📋 Ushbu URL ni qo'ying» tugmasini bosing</span>
            </div>
        </div>
        <div class="step">
            <div class="step-num"></div>
            <div class="step-body">
                <strong>«✅ O'rnatish» tugmasini bosing</strong>
                <span>Muvaffaqiyatli bo'lsa — Holat: Ulangan ko'rinadi</span>
            </div>
        </div>
        <div class="step">
            <div class="step-num"></div>
            <div class="step-body">
                <strong>MadelineProto sessiyasini yarating (katta fayllar uchun)</strong>
                <span>Terminalda: <code>C:\xampp\php\php.exe setup_session.php</code></span>
            </div>
        </div>
        <div class="step">
            <div class="step-num"></div>
            <div class="step-body">
                <strong>Botga /start yuboring va sinab ko'ring</strong>
                <span>m3u8 havolasini yuboring → 1080p MP4 oling!</span>
            </div>
        </div>
    </div>

    <hr class="divider">
    <p style="color:var(--muted);font-size:.82rem;line-height:1.6">
        ⚠️ Localhost da sinab ko'rish uchun
        <a href="https://ngrok.com" target="_blank" style="color:var(--accent)">ngrok</a>
        yoki
        <a href="https://localtunnel.github.io" target="_blank" style="color:var(--accent)">localtunnel</a>
        orqali HTTPS tunnel oching.
    </p>
</div>

<?php endif; ?>

<p style="color:var(--muted);font-size:.75rem;margin-top:8px">M3U8 → MP4 Bot Admin Panel • <?= date('Y') ?></p>

</body>
</html>
