<?php
/**
 * GymFuel Admin License & Auto-Buy Dashboard
 * Single File Web Portal for Managing Licenses, Cashfree Payment Gateway & Sales
 */

session_start();
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/CashfreeService.php';

$pdo = getDatabaseConnection();

// -------------------------------------------------------------
// 1. AUTHENTICATION HANDLER
// -------------------------------------------------------------
$authError = '';
if (isset($_POST['login_action'])) {
    $user = trim($_POST['username'] ?? '');
    $pass = trim($_POST['password'] ?? '');

    if ($user === ADMIN_USERNAME && $pass === ADMIN_PASSWORD) {
        $_SESSION['gymfuel_admin_logged_in'] = true;
        $_SESSION['admin_user'] = $user;
        header("Location: index.php");
        exit();
    } else {
        $authError = 'Invalid admin username or password.';
    }
}

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

$isLoggedIn = !empty($_SESSION['gymfuel_admin_logged_in']);

// -------------------------------------------------------------
// 2. ADMIN ACTIONS (Only when logged in)
// -------------------------------------------------------------
$notification = null;

if ($isLoggedIn && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['admin_action'] ?? '';

    // A. GENERATE NEW LICENSE KEY
    if ($postAction === 'create_key') {
        $name = trim($_POST['customer_name'] ?? 'Athlete');
        $email = trim($_POST['customer_email'] ?? '');
        $phone = trim($_POST['customer_phone'] ?? '');
        $tier = trim($_POST['tier'] ?? 'TITAN_PRO');
        $duration = trim($_POST['duration'] ?? 'lifetime');
        $maxDevices = max(1, (int)($_POST['max_devices'] ?? 1));
        $customKey = trim(strtoupper($_POST['custom_key'] ?? ''));
        $notes = trim($_POST['notes'] ?? '');

        // Generate Key
        if (empty($customKey)) {
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
            $p1 = substr(str_shuffle($chars), 0, 4);
            $p2 = substr(str_shuffle($chars), 0, 4);
            $p3 = substr(str_shuffle($chars), 0, 4);
            $finalKey = "GFUEL-{$p1}-{$p2}-{$p3}";
        } else {
            $finalKey = $customKey;
        }

        // Calculate Expiry
        $expiresAt = null;
        if ($duration !== 'lifetime') {
            $days = (int)$duration;
            if ($days > 0) {
                $expiresAt = date('Y-m-d H:i:s', strtotime("+{$days} days"));
            }
        }

        try {
            $stmt = $pdo->prepare("
                INSERT INTO licenses (license_key, customer_name, customer_email, customer_phone, tier, max_devices, expires_at, notes, status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE')
            ");
            $stmt->execute([$finalKey, $name, $email, $phone, $tier, $maxDevices, $expiresAt, $notes]);

            $_SESSION['newly_created_key'] = [
                'key' => $finalKey,
                'name' => $name,
                'tier' => $tier,
                'expires' => $expiresAt ? date('d M Y', strtotime($expiresAt)) : 'Lifetime Access',
                'devices' => $maxDevices
            ];
            header("Location: index.php?msg=key_created");
            exit();
        } catch (Exception $e) {
            $notification = ['type' => 'error', 'text' => 'Error creating key: ' . $e->getMessage()];
        }
    }

    // B. SAVE CASHFREE & PRICING SETTINGS
    if ($postAction === 'save_settings') {
        $appId = trim($_POST['cashfree_app_id'] ?? '');
        $secretKey = trim($_POST['cashfree_secret_key'] ?? '');
        $env = trim($_POST['cashfree_env'] ?? 'sandbox');
        $p30 = trim($_POST['plan_price_30'] ?? '199');
        $p90 = trim($_POST['plan_price_90'] ?? '499');
        $p365 = trim($_POST['plan_price_365'] ?? '999');
        $pLife = trim($_POST['plan_price_lifetime'] ?? '1999');
        $curr = trim($_POST['currency'] ?? 'INR');

        $toSave = [
            'cashfree_app_id' => $appId,
            'cashfree_secret_key' => $secretKey,
            'cashfree_env' => $env,
            'plan_price_30' => $p30,
            'plan_price_90' => $p90,
            'plan_price_365' => $p365,
            'plan_price_lifetime' => $pLife,
            'currency' => $curr
        ];

        foreach ($toSave as $k => $v) {
            $del = $pdo->prepare("DELETE FROM settings WHERE setting_key = ?");
            $del->execute([$k]);
            $ins = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)");
            $ins->execute([$k, $v]);
        }

        header("Location: index.php?tab=settings&msg=settings_saved");
        exit();
    }

    // C. TOGGLE STATUS (Suspend / Activate)
    if ($postAction === 'toggle_status') {
        $id = (int)$_POST['license_id'];
        $newStatus = $_POST['new_status'] === 'ACTIVE' ? 'ACTIVE' : 'SUSPENDED';
        $stmt = $pdo->prepare("UPDATE licenses SET status = ? WHERE id = ?");
        $stmt->execute([$newStatus, $id]);
        header("Location: index.php?msg=status_updated");
        exit();
    }

    // D. RESET DEVICE BINDINGS (Unbind all devices for a key)
    if ($postAction === 'reset_devices') {
        $id = (int)$_POST['license_id'];
        $stmt = $pdo->prepare("DELETE FROM activations WHERE license_id = ?");
        $stmt->execute([$id]);
        header("Location: index.php?msg=devices_reset");
        exit();
    }

    // E. DELETE KEY
    if ($postAction === 'delete_key') {
        $id = (int)$_POST['license_id'];
        $stmt = $pdo->prepare("DELETE FROM licenses WHERE id = ?");
        $stmt->execute([$id]);
        header("Location: index.php?msg=key_deleted");
        exit();
    }
}

// -------------------------------------------------------------
// 3. FETCH DASHBOARD METRICS, SETTINGS & ORDERS
// -------------------------------------------------------------
if ($isLoggedIn) {
    // Current Active Tab
    $currentTab = $_GET['tab'] ?? 'licenses';

    // Stats
    $totalKeys = (int)$pdo->query("SELECT COUNT(*) FROM licenses")->fetchColumn();
    $activeKeys = (int)$pdo->query("SELECT COUNT(*) FROM licenses WHERE status = 'ACTIVE'")->fetchColumn();
    $totalActivations = (int)$pdo->query("SELECT COUNT(*) FROM activations")->fetchColumn();

    // Orders Stats
    $totalOrders = (int)$pdo->query("SELECT COUNT(*) FROM orders")->fetchColumn();
    $paidOrders = (int)$pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'PAID'")->fetchColumn();
    $totalRevenue = (float)$pdo->query("SELECT SUM(amount) FROM orders WHERE status = 'PAID'")->fetchColumn();

    // Settings
    $settings = [];
    $stmtSettings = $pdo->query("SELECT setting_key, setting_value FROM settings");
    while ($row = $stmtSettings->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }

    // Search & Filter for Licenses
    $search = trim($_GET['q'] ?? '');
    $filterStatus = trim($_GET['status'] ?? 'ALL');

    $query = "
        SELECT l.*, 
               (SELECT COUNT(*) FROM activations a WHERE a.license_id = l.id) as bound_devices
        FROM licenses l 
        WHERE 1=1
    ";
    $params = [];

    if (!empty($search)) {
        $query .= " AND (l.license_key LIKE ? OR l.customer_name LIKE ? OR l.customer_email LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    if ($filterStatus !== 'ALL') {
        $query .= " AND l.status = ?";
        $params[] = $filterStatus;
    }

    $query .= " ORDER BY l.created_at DESC";
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $licenses = $stmt->fetchAll();

    // Fetch Orders
    $ordersStmt = $pdo->query("SELECT * FROM orders ORDER BY created_at DESC LIMIT 100");
    $orders = $ordersStmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>GymFuel Titan • License & Payment Command Center</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800;900&family=JetBrains+Mono:wght@600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-dark: #07090E;
            --card-bg: #0E131F;
            --card-elevated: #151C2C;
            --border-color: rgba(255, 255, 255, 0.08);
            --primary: #FF5E00;
            --primary-gradient: linear-gradient(135deg, #FF5E00 0%, #FF8533 100%);
            --primary-glow: rgba(255, 94, 0, 0.4);
            --gold: #FFB300;
            --gold-gradient: linear-gradient(135deg, #FFB300 0%, #FFE082 100%);
            --cyan: #00E5FF;
            --green: #00E676;
            --red: #FF3D71;
            --text-primary: #F4F7FB;
            --text-muted: #8A97AC;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: 'Plus Jakarta Sans', -apple-system, sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-primary);
            min-height: 100vh;
            line-height: 1.5;
            overflow-x: hidden;
            background-image: 
                radial-gradient(circle at 50% 0%, rgba(255, 94, 0, 0.12) 0%, transparent 60%),
                radial-gradient(circle at 90% 90%, rgba(0, 229, 255, 0.06) 0%, transparent 50%);
            background-attachment: fixed;
        }

        .mono { font-family: 'JetBrains Mono', monospace; }

        /* Top Navbar */
        .navbar {
            background: rgba(14, 19, 31, 0.85);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border-color);
            padding: 14px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .logo-container {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo-badge {
            background: var(--primary-gradient);
            color: #000;
            font-weight: 900;
            font-size: 15px;
            width: 34px;
            height: 34px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 10px;
            box-shadow: 0 4px 14px var(--primary-glow);
        }

        .logo-title {
            font-size: 16px;
            font-weight: 900;
            letter-spacing: -0.4px;
        }

        .logo-sub {
            font-size: 10px;
            color: var(--cyan);
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.8px;
        }

        .container {
            max-width: 1320px;
            margin: 0 auto;
            padding: 24px 16px 60px;
        }

        /* Nav Tabs */
        .nav-tabs-row {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 24px;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 12px;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        .nav-tabs-row::-webkit-scrollbar { display: none; }

        .tab-btn {
            background: transparent;
            border: 1px solid var(--border-color);
            color: var(--text-muted);
            font-size: 13px;
            font-weight: 700;
            padding: 9px 16px;
            border-radius: 10px;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            white-space: nowrap;
            transition: all 0.2s ease;
        }

        .tab-btn:hover {
            color: #fff;
            background: var(--card-elevated);
        }

        .tab-btn.active {
            background: var(--primary-gradient);
            color: #000;
            border-color: var(--primary);
            box-shadow: 0 4px 14px var(--primary-glow);
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 14px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 18px;
            padding: 18px;
            position: relative;
        }

        .stat-label {
            font-size: 11px;
            color: var(--text-muted);
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            margin-bottom: 6px;
        }

        .stat-value {
            font-size: clamp(22px, 5vw, 28px);
            font-weight: 900;
            letter-spacing: -0.5px;
        }

        /* Action Buttons */
        .btn-primary {
            background: var(--primary-gradient);
            color: #000;
            font-weight: 800;
            font-size: 13px;
            padding: 9px 16px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            text-decoration: none;
            box-shadow: 0 4px 14px var(--primary-glow);
            transition: transform 0.15s ease;
            white-space: nowrap;
        }

        .btn-primary:hover { transform: translateY(-2px); }

        .btn-store {
            background: linear-gradient(135deg, var(--cyan), #00B0FF);
            color: #000;
            font-weight: 800;
            font-size: 12.5px;
            padding: 9px 14px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            box-shadow: 0 4px 14px rgba(0, 229, 255, 0.3);
            white-space: nowrap;
        }

        /* Search & Filter Bar */
        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 18px;
        }

        .search-box {
            display: flex;
            align-items: center;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            padding: 6px 14px;
            width: 100%;
            max-width: 320px;
        }

        .search-box input {
            background: transparent;
            border: none;
            color: var(--text-primary);
            font-size: 13.5px;
            width: 100%;
            outline: none;
            padding: 4px;
        }

        /* Form Components */
        .form-group {
            margin-bottom: 16px;
        }

        .form-label {
            display: block;
            font-size: 11.5px;
            font-weight: 800;
            color: var(--text-muted);
            margin-bottom: 6px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .form-input, .form-select {
            width: 100%;
            background: var(--bg-dark);
            border: 1.5px solid var(--border-color);
            padding: 12px 14px;
            border-radius: 12px;
            color: var(--text-primary);
            font-size: 14px;
            font-family: inherit;
            outline: none;
            transition: border-color 0.2s;
        }

        .form-input:focus, .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-glow);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }

        /* Table */
        .table-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
        }

        .table-responsive {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            text-align: left;
            font-size: 13px;
        }

        th {
            background: var(--card-elevated);
            padding: 14px 16px;
            color: var(--text-muted);
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            border-bottom: 1px solid var(--border-color);
            white-space: nowrap;
        }

        td {
            padding: 14px 16px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }

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

        /* Badges */
        .badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: 800;
            text-transform: uppercase;
            white-space: nowrap;
        }

        .badge-active { background: rgba(0, 230, 118, 0.15); color: var(--green); border: 1px solid rgba(0, 230, 118, 0.3); }
        .badge-suspended { background: rgba(255, 61, 113, 0.15); color: var(--red); border: 1px solid rgba(255, 61, 113, 0.3); }
        .badge-pending { background: rgba(255, 179, 0, 0.15); color: var(--gold); border: 1px solid rgba(255, 179, 0, 0.3); }

        .key-box {
            background: var(--bg-dark);
            border: 1px solid var(--border-color);
            padding: 6px 10px;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-weight: 700;
            color: #FFA726;
            white-space: nowrap;
        }

        .copy-btn {
            background: transparent;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            font-size: 13px;
        }

        /* Settings Card */
        .settings-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 22px;
            padding: clamp(20px, 4vw, 32px);
            max-width: 800px;
            margin: 0 auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.4);
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.85);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 16px;
        }

        .modal.active { display: flex; }

        .modal-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 24px;
            padding: clamp(20px, 4vw, 30px);
            width: 100%;
            max-width: 520px;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.8);
            max-height: 90vh;
            overflow-y: auto;
        }

        /* Login Card */
        .login-wrapper {
            min-height: 85vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .login-card {
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 24px;
            padding: clamp(24px, 5vw, 36px);
            width: 100%;
            max-width: 420px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.7);
        }

        @media (max-width: 600px) {
            .navbar { padding: 12px 14px; }
            .form-row { grid-template-columns: 1fr; }
            .search-box { max-width: 100%; }
        }
    </style>
</head>
<body>

<?php if (!$isLoggedIn): ?>
    <!-- LOGIN SCREEN -->
    <div class="login-wrapper">
        <div class="login-card">
            <div style="text-align: center; margin-bottom: 24px;">
                <div class="logo-badge" style="margin: 0 auto 12px; width: 48px; height: 48px; font-size: 22px;">⚡</div>
                <h1 style="font-size: 22px; font-weight: 900;">GymFuel Command</h1>
                <p style="font-size: 13px; color: var(--text-muted);">Sign in to access License & Gateway portal</p>
            </div>

            <?php if (!empty($authError)): ?>
                <div style="background: rgba(255, 61, 113, 0.15); border: 1px solid var(--red); color: #FF708F; padding: 12px; border-radius: 12px; font-size: 13px; margin-bottom: 16px;">
                    <?= htmlspecialchars($authError) ?>
                </div>
            <?php endif; ?>

            <form method="POST">
                <input type="hidden" name="login_action" value="1">
                <div class="form-group">
                    <label class="form-label">Username</label>
                    <input type="text" name="username" class="form-input" placeholder="admin" required autofocus>
                </div>
                <div class="form-group">
                    <label class="form-label">Password</label>
                    <div style="position: relative;">
                        <input type="password" id="admin_password" name="password" class="form-input" placeholder="••••••••" required style="padding-right: 44px;">
                        <button type="button" onclick="togglePass('admin_password', this)" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-muted); cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 6px;" title="Show/Hide Password">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                        </button>
                    </div>
                </div>
                <button type="submit" class="btn-primary" style="width: 100%; justify-content: center; padding: 14px; margin-top: 10px;">
                    ⚡ Authenticate & Login
                </button>
            </form>
        </div>
    </div>

<?php else: ?>

    <!-- NAVBAR -->
    <div class="navbar">
        <div class="logo-container">
            <div class="logo-badge">⚡</div>
            <div>
                <div class="logo-title">GymFuel Titan</div>
                <div class="logo-sub">Command Center</div>
            </div>
        </div>

        <div style="display: flex; align-items: center; gap: 8px;">
            <a href="buy.php" target="_blank" class="btn-store">🛍️ Store</a>
            <button onclick="openModal('createKeyModal')" class="btn-primary">➕ Key</button>
            <a href="index.php?action=logout" style="color: var(--text-muted); font-size: 12.5px; text-decoration: none; padding: 6px 8px;">Logout</a>
        </div>
    </div>

    <div class="container">

        <!-- NAV TABS -->
        <div class="nav-tabs-row">
            <a href="index.php?tab=licenses" class="tab-btn <?= $currentTab === 'licenses' ? 'active' : '' ?>">
                🔑 Licenses (<?= $totalKeys ?>)
            </a>
            <a href="index.php?tab=orders" class="tab-btn <?= $currentTab === 'orders' ? 'active' : '' ?>">
                💳 Cashfree Orders (<?= $paidOrders ?> Paid)
            </a>
            <a href="index.php?tab=settings" class="tab-btn <?= $currentTab === 'settings' ? 'active' : '' ?>">
                ⚙️ Gateway & Pricing
            </a>
        </div>

        <!-- TAB 1: LICENSES VIEW -->
        <?php if ($currentTab === 'licenses'): ?>

            <!-- STATS -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-label">Total Licenses</div>
                    <div class="stat-value"><?= $totalKeys ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Active Licenses</div>
                    <div class="stat-value" style="color: var(--green);"><?= $activeKeys ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Bound Devices</div>
                    <div class="stat-value" style="color: var(--cyan);"><?= $totalActivations ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Store Online Revenue</div>
                    <div class="stat-value" style="color: var(--gold);">₹<?= number_format($totalRevenue, 2) ?></div>
                </div>
            </div>

            <!-- TOOLBAR -->
            <div class="toolbar">
                <form method="GET" style="display: flex; gap: 8px; width: 100%; max-width: 420px;">
                    <input type="hidden" name="tab" value="licenses">
                    <div class="search-box" style="max-width: 100%;">
                        <input type="text" name="q" placeholder="Search key, athlete or email..." value="<?= htmlspecialchars($search) ?>">
                    </div>
                    <button type="submit" class="btn-primary" style="padding: 8px 14px;">Filter</button>
                    <?php if (!empty($search)): ?>
                        <a href="index.php?tab=licenses" style="color: var(--text-muted); padding: 8px;">Clear</a>
                    <?php endif; ?>
                </form>

                <button onclick="openModal('createKeyModal')" class="btn-primary">➕ 1-Click Key Generator</button>
            </div>

            <!-- LICENSES TABLE -->
            <div class="table-card">
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>Status</th>
                                <th>License Key</th>
                                <th>Athlete / Customer</th>
                                <th>Tier</th>
                                <th>Devices</th>
                                <th>Expires</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($licenses)): ?>
                                <tr>
                                    <td colspan="7" style="text-align: center; padding: 36px; color: var(--text-muted);">
                                        No license keys found matching your criteria.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($licenses as $l): ?>
                                    <tr>
                                        <td>
                                            <?php if ($l['status'] === 'ACTIVE'): ?>
                                                <span class="badge badge-active">Active</span>
                                            <?php else: ?>
                                                <span class="badge badge-suspended"><?= htmlspecialchars($l['status']) ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="key-box mono">
                                                <span><?= htmlspecialchars($l['license_key']) ?></span>
                                                <button class="copy-btn" onclick="copyText('<?= htmlspecialchars($l['license_key']) ?>')" title="Copy Key">📋</button>
                                            </div>
                                        </td>
                                        <td>
                                            <div style="font-weight: 700;"><?= htmlspecialchars($l['customer_name']) ?></div>
                                            <div style="font-size: 11px; color: var(--text-muted);"><?= htmlspecialchars($l['customer_email']) ?></div>
                                        </td>
                                        <td>
                                            <span style="font-weight: 700; font-size: 11px; color: var(--gold);"><?= htmlspecialchars($l['tier']) ?></span>
                                        </td>
                                        <td>
                                            <span style="font-weight: 700;"><?= (int)$l['bound_devices'] ?> / <?= (int)$l['max_devices'] ?></span>
                                        </td>
                                        <td>
                                            <?php if (empty($l['expires_at'])): ?>
                                                <span class="badge" style="background: rgba(0, 229, 255, 0.15); color: var(--cyan);">Lifetime</span>
                                            <?php else: ?>
                                                <span style="font-size: 12px;"><?= date('d M Y', strtotime($l['expires_at'])) ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div style="display: flex; gap: 6px; flex-wrap: nowrap;">
                                                <!-- WhatsApp Share -->
                                                <?php 
                                                    $waMsg = urlencode("⚡ Welcome to GymFuel Titan!\n\nYour License Key: {$l['license_key']}\nAthlete: {$l['customer_name']}\nAccess: " . ($l['expires_at'] ? date('d M Y', strtotime($l['expires_at'])) : 'Lifetime VIP') . "\n\nDownload App & Activate now!");
                                                ?>
                                                <a href="https://api.whatsapp.com/send?text=<?= $waMsg ?>" target="_blank" style="background: #25D366; color: #000; padding: 6px 10px; border-radius: 8px; text-decoration: none; font-size: 11px; font-weight: 800;">WhatsApp</a>

                                                <!-- Reset Devices Form -->
                                                <form method="POST" onsubmit="return confirm('Reset all device bindings for this key?')">
                                                    <input type="hidden" name="admin_action" value="reset_devices">
                                                    <input type="hidden" name="license_id" value="<?= $l['id'] ?>">
                                                    <button type="submit" style="background: rgba(0, 229, 255, 0.15); color: var(--cyan); border: 1px solid var(--cyan); padding: 6px 10px; border-radius: 8px; cursor: pointer; font-size: 11px; font-weight: 700;">Reset</button>
                                                </form>

                                                <!-- Status Toggle -->
                                                <form method="POST">
                                                    <input type="hidden" name="admin_action" value="toggle_status">
                                                    <input type="hidden" name="license_id" value="<?= $l['id'] ?>">
                                                    <input type="hidden" name="new_status" value="<?= $l['status'] === 'ACTIVE' ? 'SUSPENDED' : 'ACTIVE' ?>">
                                                    <button type="submit" style="background: var(--card-elevated); color: var(--text-primary); border: 1px solid var(--border-color); padding: 6px 10px; border-radius: 8px; cursor: pointer; font-size: 11px;">
                                                        <?= $l['status'] === 'ACTIVE' ? 'Suspend' : 'Unsuspend' ?>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        <!-- TAB 2: CASHFREE ONLINE ORDERS & SALES -->
        <?php elseif ($currentTab === 'orders'): ?>

            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-label">Total Online Orders</div>
                    <div class="stat-value"><?= $totalOrders ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Successful Purchases</div>
                    <div class="stat-value" style="color: var(--green);"><?= $paidOrders ?></div>
                </div>
                <div class="stat-card">
                    <div class="stat-label">Total Revenue Collected</div>
                    <div class="stat-value" style="color: var(--gold);">₹<?= number_format($totalRevenue, 2) ?></div>
                </div>
            </div>

            <div class="table-card">
                <div class="table-responsive">
                    <table>
                        <thead>
                            <tr>
                                <th>Status</th>
                                <th>Order ID</th>
                                <th>Customer Info</th>
                                <th>Plan</th>
                                <th>Amount</th>
                                <th>Generated Key</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($orders)): ?>
                                <tr>
                                    <td colspan="7" style="text-align: center; padding: 36px; color: var(--text-muted);">
                                        No online orders placed yet. Customers who buy via <a href="buy.php" target="_blank" style="color: var(--primary);">buy.php</a> will appear here automatically!
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($orders as $ord): ?>
                                    <tr>
                                        <td>
                                            <?php if ($ord['status'] === 'PAID'): ?>
                                                <span class="badge badge-active">PAID</span>
                                            <?php else: ?>
                                                <span class="badge badge-pending"><?= htmlspecialchars($ord['status']) ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="mono" style="font-size: 11.5px; color: var(--text-muted);">
                                            <?= htmlspecialchars($ord['order_id']) ?>
                                        </td>
                                        <td>
                                            <div style="font-weight: 700;"><?= htmlspecialchars($ord['customer_name']) ?></div>
                                            <div style="font-size: 11px; color: var(--text-muted);"><?= htmlspecialchars($ord['customer_phone']) ?> • <?= htmlspecialchars($ord['customer_email']) ?></div>
                                        </td>
                                        <td>
                                            <span style="font-weight: 700; font-size: 12px;"><?= htmlspecialchars($ord['plan_title']) ?></span>
                                        </td>
                                        <td>
                                            <span style="font-weight: 900; color: var(--green);">₹<?= number_format($ord['amount'], 2) ?></span>
                                        </td>
                                        <td>
                                            <?php if (!empty($ord['license_key'])): ?>
                                                <div class="key-box mono" style="font-size: 12px;">
                                                    <span><?= htmlspecialchars($ord['license_key']) ?></span>
                                                    <button class="copy-btn" onclick="copyText('<?= htmlspecialchars($ord['license_key']) ?>')">📋</button>
                                                </div>
                                            <?php else: ?>
                                                <span style="color: var(--text-muted); font-size: 11px;">Not generated yet</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="font-size: 11.5px; color: var(--text-muted); white-space: nowrap;">
                                            <?= date('d M Y, H:i', strtotime($ord['created_at'])) ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        <!-- TAB 3: CASHFREE GATEWAY & PRICING SETTINGS -->
        <?php elseif ($currentTab === 'settings'): ?>

            <div class="settings-card">
                <h2 style="font-size: clamp(18px, 4vw, 22px); font-weight: 900; margin-bottom: 6px;">⚙️ Cashfree Gateway & Pricing Configuration</h2>
                <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 24px;">Enter your Cashfree API keys to automatically accept payments and instantly issue license keys to users.</p>

                <form method="POST">
                    <input type="hidden" name="admin_action" value="save_settings">

                    <div class="form-group">
                        <label class="form-label">Cashfree Environment Mode</label>
                        <select name="cashfree_env" class="form-select">
                            <option value="sandbox" <?= ($settings['cashfree_env'] ?? '') === 'sandbox' ? 'selected' : '' ?>>Sandbox (Test Mode)</option>
                            <option value="production" <?= ($settings['cashfree_env'] ?? '') === 'production' ? 'selected' : '' ?>>Production (Live UPI / Cards / NetBanking)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Cashfree App ID / Client ID</label>
                        <input type="text" name="cashfree_app_id" class="form-input mono" placeholder="e.g. TEST10345265... or LIVE_APP_ID" value="<?= htmlspecialchars($settings['cashfree_app_id'] ?? '') ?>" required>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Cashfree Secret Key</label>
                        <input type="text" name="cashfree_secret_key" class="form-input mono" placeholder="e.g. cfsk_ma_test_..." value="<?= htmlspecialchars($settings['cashfree_secret_key'] ?? '') ?>" required>
                    </div>

                    <hr style="border: none; border-top: 1px solid var(--border-color); margin: 24px 0;">

                    <h3 style="font-size: 16px; font-weight: 800; margin-bottom: 16px; color: var(--primary);">💰 Plan Pricing (in INR ₹)</h3>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">1 Month (30 Days Shred) Price (₹)</label>
                            <input type="number" name="plan_price_30" class="form-input" value="<?= htmlspecialchars($settings['plan_price_30'] ?? '199') ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">3 Months (90 Days Bulk) Price (₹)</label>
                            <input type="number" name="plan_price_90" class="form-input" value="<?= htmlspecialchars($settings['plan_price_90'] ?? '499') ?>" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">1 Year (365 Days Titan Pro) Price (₹)</label>
                            <input type="number" name="plan_price_365" class="form-input" value="<?= htmlspecialchars($settings['plan_price_365'] ?? '999') ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Lifetime VIP Beast Pass Price (₹)</label>
                            <input type="number" name="plan_price_lifetime" class="form-input" value="<?= htmlspecialchars($settings['plan_price_lifetime'] ?? '1999') ?>" required>
                        </div>
                    </div>

                    <button type="submit" class="btn-primary" style="padding: 14px 28px; width: 100%; justify-content: center; font-size: 15px; margin-top: 10px;">
                        💾 Save Payment Gateway & Pricing Settings
                    </button>
                </form>
            </div>

        <?php endif; ?>

    </div>

    <!-- 1-CLICK CREATE KEY MODAL -->
    <div id="createKeyModal" class="modal">
        <div class="modal-card">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px;">
                <h2 style="font-size: 18px; font-weight: 900;">⚡ 1-Click License Key Generator</h2>
                <button onclick="closeModal('createKeyModal')" style="background: none; border: none; color: var(--text-muted); font-size: 22px; cursor: pointer; padding: 4px;">✕</button>
            </div>

            <form method="POST">
                <input type="hidden" name="admin_action" value="create_key">

                <div class="form-group">
                    <label class="form-label">Customer / Athlete Name</label>
                    <input type="text" name="customer_name" class="form-input" placeholder="e.g. John Titan" required>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Email (Optional)</label>
                        <input type="email" name="customer_email" class="form-input" placeholder="athlete@gmail.com">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Phone / WhatsApp</label>
                        <input type="tel" name="customer_phone" class="form-input" placeholder="+919876543210">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Duration</label>
                        <select name="duration" class="form-select">
                            <option value="lifetime">Lifetime Access</option>
                            <option value="365">1 Year (365 Days)</option>
                            <option value="90">3 Months (90 Days)</option>
                            <option value="30">1 Month (30 Days)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Allowed Devices</label>
                        <select name="max_devices" class="form-select">
                            <option value="1">1 Device (Default)</option>
                            <option value="2">2 Devices</option>
                            <option value="3">3 Devices (VIP)</option>
                            <option value="5">5 Devices (Gym Stack)</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Custom Key (Leave blank to auto-generate)</label>
                    <input type="text" name="custom_key" class="form-input mono" placeholder="Auto: GFUEL-XXXX-XXXX-XXXX">
                </div>

                <button type="submit" class="btn-primary" style="width: 100%; justify-content: center; padding: 14px; margin-top: 8px;">
                    ⚡ Generate & Activate Key
                </button>
            </form>
        </div>
    </div>

<?php endif; ?>

<script>
    function togglePass(inputId, btn) {
        const inp = document.getElementById(inputId);
        if (inp.type === 'password') {
            inp.type = 'text';
            btn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#FF5E00" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>';
        } else {
            inp.type = 'password';
            btn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>';
        }
    }

    function openModal(id) {
        document.getElementById(id).classList.add('active');
    }

    function closeModal(id) {
        document.getElementById(id).classList.remove('active');
    }

    function copyText(text) {
        navigator.clipboard.writeText(text).then(() => {
            alert('✅ Copied to clipboard:\n\n' + text);
        }).catch(() => {
            prompt('Copy text manually:', text);
        });
    }
</script>

</body>
</html>
