<?php
include 'db.php';

// Login Check
if(!isset($_SESSION['admin'])) {
    if(isset($_POST['login']) && $_POST['user']=='admin' && $_POST['pass']=='1234') {
        $_SESSION['admin'] = true; header("Location: admin.php");
    }
    // Stylish Login Page
    echo "<!DOCTYPE html>
    <html><head><title>Admin Login</title><meta name='viewport' content='width=device-width, initial-scale=1'><style>
    body{background:#f1f5f9; display:flex; align-items:center; justify-content:center; height:100vh; font-family:'Segoe UI', sans-serif; margin:0;}
    .login-card{background:white; padding:40px; border-radius:15px; box-shadow:0 10px 25px rgba(0,0,0,0.1); width:100%; max-width:350px; text-align:center;}
    input{width:100%; padding:12px; margin:10px 0; border:1px solid #ddd; border-radius:8px; box-sizing:border-box;}
    button{width:100%; padding:12px; background:#2563eb; color:white; border:none; border-radius:8px; font-weight:bold; cursor:pointer;}
    button:hover{background:#1d4ed8;}
    </style></head><body>
    <form method='post' class='login-card'>
        <h2 style='color:#333; margin-top:0;'>Admin Panel</h2>
        <input name='user' placeholder='Username' required>
        <input type='password' name='pass' placeholder='Password' required>
        <button type='submit' name='login'>Login Dashboard</button>
    </form></body></html>";
    exit;
}

// --- LOGIC HANDLERS (Same as before) ---
if(isset($_POST['complete_ord'])) { $conn->prepare("UPDATE orders SET status='Completed', delivery_info=? WHERE id=?")->execute([$_POST['info'], $_POST['oid']]); header("Location: admin.php"); }
if(isset($_POST['reject_ord'])) {
    $order = $conn->query("SELECT * FROM orders WHERE id=".$_POST['oid'])->fetch();
    if($order['status']=='Pending' && $order['method']=='Balance') $conn->query("UPDATE users SET balance=balance+{$order['price']} WHERE id={$order['user_id']}");
    $conn->query("UPDATE orders SET status='Rejected' WHERE id=".$_POST['oid']); header("Location: admin.php");
}
if(isset($_GET['app_dep'])) {
    $d=$conn->query("SELECT * FROM deposits WHERE id=".$_GET['app_dep'])->fetch();
    if($d['status']=='Pending'){
        $conn->query("UPDATE users SET balance=balance+{$d['amount']} WHERE id={$d['user_id']}");
        $conn->query("UPDATE deposits SET status='Approved' WHERE id={$d['id']}");
        $u=$conn->query("SELECT referred_by FROM users WHERE id={$d['user_id']}")->fetch();
        if($u['referred_by']) { $b=$d['amount']*0.05; $conn->query("UPDATE users SET balance=balance+$b WHERE ref_code='{$u['referred_by']}'"); }
    } header("Location: admin.php");
}
if(isset($_GET['rej_dep'])) { $conn->query("UPDATE deposits SET status='Rejected' WHERE id=".$_GET['rej_dep']); header("Location: admin.php"); }
if(isset($_POST['add_prod'])) { move_uploaded_file($_FILES['image']['tmp_name'], "uploads/".$_FILES['image']['name']); $conn->prepare("INSERT INTO products (name,image) VALUES(?,?)")->execute([$_POST['name'],$_FILES['image']['name']]); header("Location: admin.php"); }
if(isset($_POST['add_var'])) { $conn->prepare("INSERT INTO variants (product_id,name,price) VALUES(?,?,?)")->execute([$_POST['pid'],$_POST['v_name'],$_POST['v_price']]); header("Location: admin.php"); }
if(isset($_POST['add_promo'])) { $conn->prepare("INSERT INTO promos (code, discount, usage_limit) VALUES (?, ?, ?)")->execute([$_POST['code'], $_POST['disc'], $_POST['limit']]); header("Location: admin.php"); }
if(isset($_GET['del_promo'])) { $conn->query("DELETE FROM promos WHERE id=".$_GET['del_promo']); header("Location: admin.php"); }
if(isset($_POST['add_redeem'])) { $conn->prepare("INSERT INTO redeem_codes (code, amount, usage_limit) VALUES (?, ?, ?)")->execute([$_POST['code'], $_POST['amount'], $_POST['limit']]); header("Location: admin.php"); }
if(isset($_GET['del_redeem'])) { $conn->query("DELETE FROM redeem_codes WHERE id=".$_GET['del_redeem']); header("Location: admin.php"); }

// Logout Logic
if(isset($_GET['logout'])) { session_destroy(); echo "<script>window.location='admin.php'</script>"; }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --sidebar: #1e293b; --bg: #f1f5f9; --primary: #3b82f6; --text: #334155; }
        body { margin:0; font-family:'Segoe UI', sans-serif; background:var(--bg); display:flex; height:100vh; overflow:hidden; }
        
        /* Sidebar */
        .sidebar { width:250px; background:var(--sidebar); color:white; display:flex; flex-direction:column; padding:20px; box-shadow: 2px 0 5px rgba(0,0,0,0.1); }
        .sidebar h2 { margin-top:0; margin-bottom:30px; text-align:center; color:#60a5fa; font-size:24px; }
        .menu-item { padding:12px 15px; cursor:pointer; border-radius:8px; margin-bottom:5px; transition:0.3s; display:flex; align-items:center; gap:10px; color:#cbd5e1; text-decoration: none; }
        .menu-item:hover, .menu-item.active { background:#334155; color:white; }
        .logout { margin-top:auto; background:#ef4444; color:white; text-align:center; }
        
        /* Main Content */
        .main { flex:1; padding:30px; overflow-y:auto; }
        .section { display:none; animation: fadeIn 0.3s; }
        .section.active { display:block; }
        @keyframes fadeIn { from{opacity:0; transform:translateY(10px);} to{opacity:1; transform:translateY(0);} }

        /* Cards & Forms */
        .card { background:white; padding:20px; border-radius:12px; box-shadow:0 2px 10px rgba(0,0,0,0.05); margin-bottom:20px; }
        .card h3 { margin-top:0; color:var(--primary); border-bottom:1px solid #eee; padding-bottom:10px; }
        .form-grid { display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap:10px; }
        input, select, textarea { width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:6px; box-sizing:border-box; margin-bottom:10px; }
        button.action-btn { padding:10px 15px; background:var(--primary); color:white; border:none; border-radius:6px; cursor:pointer; }
        button.action-btn:hover { opacity:0.9; }

        /* Tables */
        table { width:100%; border-collapse:collapse; background:white; border-radius:8px; overflow:hidden; }
        th, td { padding:12px; text-align:left; border-bottom:1px solid #eee; font-size:14px; }
        th { background:#f8fafc; font-weight:600; color:#475569; }
        tr:hover { background:#f8fafc; }
        
        /* Badges */
        .badge { padding:3px 8px; border-radius:12px; font-size:11px; font-weight:bold; }
        .badge.Pending { background:#fef3c7; color:#d97706; }
        .badge.Completed, .badge.Approved, .badge.Active { background:#dcfce7; color:#16a34a; }
        .badge.Rejected, .badge.Expired { background:#fee2e2; color:#dc2626; }

        /* Dashboard Stats */
        .stats-grid { display:grid; grid-template-columns:repeat(4, 1fr); gap:20px; margin-bottom:30px; }
        .stat-card { background:white; padding:20px; border-radius:10px; box-shadow:0 2px 5px rgba(0,0,0,0.05); text-align:center; }
        .stat-num { font-size:24px; font-weight:bold; color:var(--sidebar); display:block; margin-top:5px; }
        .stat-label { color:#64748b; font-size:13px; }

        /* Mobile Responsive */
        @media (max-width: 768px) {
            body { flex-direction:column; }
            .sidebar { width:100%; height:auto; padding:10px; flex-direction:row; overflow-x:auto; }
            .sidebar h2 { display:none; }
            .menu-item { font-size:12px; white-space:nowrap; }
            .logout { display:none; } /* Logout icon in menu */
            .stats-grid { grid-template-columns:repeat(2, 1fr); }
            .main { padding:15px; }
        }
    </style>
</head>
<body>

    <!-- SIDEBAR -->
    <div class="sidebar">
        <h2>GAME SHOP</h2>
        <div class="menu-item active" onclick="showSection('dashboard', this)"><i class="fas fa-th-large"></i> Dashboard</div>
        <div class="menu-item" onclick="showSection('orders', this)"><i class="fas fa-shopping-cart"></i> Orders</div>
        <div class="menu-item" onclick="showSection('deposits', this)"><i class="fas fa-wallet"></i> Deposits</div>
        <div class="menu-item" onclick="showSection('products', this)"><i class="fas fa-box"></i> Products</div>
        <div class="menu-item" onclick="showSection('codes', this)"><i class="fas fa-gift"></i> Codes</div>
        <a href="?logout=true" class="menu-item logout"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>

    <!-- MAIN CONTENT -->
    <div class="main">
        
        <!-- DASHBOARD SECTION -->
        <div id="dashboard" class="section active">
            <h2 style="margin-top:0;">Dashboard Overview</h2>
            <div class="stats-grid">
                <?php 
                    $pendingOrd = $conn->query("SELECT COUNT(*) FROM orders WHERE status='Pending'")->fetchColumn();
                    $pendingDep = $conn->query("SELECT COUNT(*) FROM deposits WHERE status='Pending'")->fetchColumn();
                    $totalUser = $conn->query("SELECT COUNT(*) FROM users")->fetchColumn();
                    $totalSale = $conn->query("SELECT SUM(price) FROM orders WHERE status='Completed'")->fetchColumn();
                ?>
                <div class="stat-card"><span class="stat-label">Pending Orders</span><span class="stat-num" style="color:#eab308"><?php echo $pendingOrd; ?></span></div>
                <div class="stat-card"><span class="stat-label">Pending Deposits</span><span class="stat-num" style="color:#3b82f6"><?php echo $pendingDep; ?></span></div>
                <div class="stat-card"><span class="stat-label">Total Users</span><span class="stat-num"><?php echo $totalUser; ?></span></div>
                <div class="stat-card"><span class="stat-label">Total Sales</span><span class="stat-num" style="color:#10b981">$ <?php echo number_format($totalSale, 2); ?></span></div>
            </div>
            
            <div class="card">
                <h3>Recent Activity</h3>
                <p style="color:#64748b;">Welcome to your admin panel. Use the sidebar to manage your shop.</p>
            </div>
        </div>

        <!-- ORDERS SECTION -->
        <div id="orders" class="section">
            <div class="card">
                <h3>Manage Orders</h3>
                <div style="overflow-x:auto;">
                    <table>
                        <thead><tr><th>ID</th><th>User</th><th>Item</th><th>Price</th><th>Method/Trx</th><th>Status</th><th>Action</th></tr></thead>
                        <tbody>
                        <?php $ords=$conn->query("SELECT o.*, u.phone FROM orders o JOIN users u ON o.user_id=u.id ORDER BY o.id DESC"); while($o=$ords->fetch()): ?>
                        <tr>
                            <td>#<?php echo $o['id']; ?></td>
                            <td><?php echo $o['phone']; ?></td>
                            <td><?php echo $o['product_name']; ?> (<?php echo $o['variant_name']; ?>)</td>
                            <td>$<?php echo $o['price']; ?></td>
                            <td><?php echo $o['method']; ?><br><small><?php echo $o['trx_id']; ?></small></td>
                            <td><span class="badge <?php echo $o['status']; ?>"><?php echo $o['status']; ?></span></td>
                            <td>
                                <?php if($o['status']=='Pending'): ?>
                                <form method="post" style="display:flex; gap:5px;">
                                    <input type="hidden" name="oid" value="<?php echo $o['id']; ?>">
                                    <textarea name="info" placeholder="Delivered Info (Code/Msg)" style="height:35px; margin:0; width:150px;"></textarea>
                                    <button name="complete_ord" class="action-btn" style="background:#10b981; padding:5px 10px;">✔</button> 
                                    <button name="reject_ord" class="action-btn" style="background:#ef4444; padding:5px 10px;">✘</button>
                                </form>
                                <?php else: echo $o['delivery_info']; endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- DEPOSITS SECTION -->
        <div id="deposits" class="section">
            <div class="card">
                <h3>Deposit Requests</h3>
                <table>
                    <thead><tr><th>User</th><th>Method</th><th>Amount</th><th>Trx ID</th><th>Date</th><th>Action</th></tr></thead>
                    <tbody>
                    <?php $deps=$conn->query("SELECT d.*, u.phone FROM deposits d JOIN users u ON d.user_id=u.id WHERE d.status='Pending' ORDER BY d.id DESC"); 
                    if($deps->rowCount()==0) echo "<tr><td colspan='6' style='text-align:center;'>No pending deposits.</td></tr>";
                    while($d=$deps->fetch()): ?>
                    <tr>
                        <td><?php echo $d['phone']; ?></td>
                        <td><?php echo $d['method']; ?></td>
                        <td style="font-weight:bold; color:#10b981;">$ <?php echo $d['amount']; ?></td>
                        <td><?php echo $d['trx_id']; ?></td>
                        <td><?php echo $d['date']; ?></td>
                        <td>
                            <a href="?app_dep=<?php echo $d['id']; ?>" class="action-btn" style="background:#10b981; text-decoration:none;">Approve</a>
                            <a href="?rej_dep=<?php echo $d['id']; ?>" class="action-btn" style="background:#ef4444; text-decoration:none;">Reject</a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- PRODUCTS SECTION -->
        <div id="products" class="section">
            <div class="card">
                <h3>Add New Product</h3>
                <form method="post" enctype="multipart/form-data" class="form-grid">
                    <input name="name" placeholder="Product Name" required>
                    <input type="file" name="image" required style="padding:7px;">
                    <button name="add_prod" class="action-btn">Add Product</button>
                </form>
            </div>
            
            <div class="card">
                <h3>Add Variant (Package)</h3>
                <form method="post" class="form-grid">
                    <select name="pid" required>
                        <option value="">Select Product</option>
                        <?php $p=$conn->query("SELECT * FROM products"); while($r=$p->fetch()) echo "<option value='{$r['id']}'>{$r['name']}</option>"; ?>
                    </select>
                    <input name="v_name" placeholder="Variant Name (e.g. 1 Day)" required>
                    <input name="v_price" placeholder="Price" required>
                    <button name="add_var" class="action-btn">Add Variant</button>
                </form>
            </div>
        </div>

        <!-- CODES SECTION -->
        <div id="codes" class="section">
            <!-- Redeem Codes -->
            <div class="card">
                <h3>Create Redeem Code (Deposit)</h3>
                <form method="post" class="form-grid">
                    <input name="code" placeholder="Code (e.g. GIFT500)" required>
                    <input name="amount" placeholder="Amount" required>
                    <input type="number" name="limit" placeholder="Usage Limit" required>
                    <button name="add_redeem" class="action-btn" style="background:#8b5cf6;">Create Redeem Code</button>
                </form>
                <br>
                <table>
                    <tr style="background:#f1f5f9;"><th>Code</th><th>Amount</th><th>Limit</th><th>Status</th><th>Action</th></tr>
                    <?php $red=$conn->query("SELECT * FROM redeem_codes ORDER BY id DESC"); while($r=$red->fetch()): ?>
                    <tr>
                        <td><b><?php echo $r['code']; ?></b></td>
                        <td>$<?php echo $r['amount']; ?></td>
                        <td><?php echo $r['used_count'].'/'.$r['usage_limit']; ?></td>
                        <td><?php echo ($r['used_count']>=$r['usage_limit'])?"<span class='badge Expired'>Expired</span>":"<span class='badge Active'>Active</span>"; ?></td>
                        <td><a href="?del_redeem=<?php echo $r['id']; ?>" style="color:red;">Delete</a></td>
                    </tr>
                    <?php endwhile; ?>
                </table>
            </div>

            <!-- Promo Codes -->
            <div class="card">
                <h3>Create Promo Code (Discount)</h3>
                <form method="post" class="form-grid">
                    <input name="code" placeholder="Code (e.g. SALE20)" required>
                    <input name="disc" placeholder="Discount Amount" required>
                    <input type="number" name="limit" placeholder="Usage Limit" required>
                    <button name="add_promo" class="action-btn">Create Promo Code</button>
                </form>
                <br>
                <table>
                    <tr style="background:#f1f5f9;"><th>Code</th><th>Discount</th><th>Limit</th><th>Status</th><th>Action</th></tr>
                    <?php $pro=$conn->query("SELECT * FROM promos ORDER BY id DESC"); while($p=$pro->fetch()): ?>
                    <tr>
                        <td><b><?php echo $p['code']; ?></b></td>
                        <td>$<?php echo $p['discount']; ?></td>
                        <td><?php echo $p['used_count'].'/'.$p['usage_limit']; ?></td>
                        <td><?php echo ($p['used_count']>=$p['usage_limit'])?"<span class='badge Expired'>Expired</span>":"<span class='badge Active'>Active</span>"; ?></td>
                        <td><a href="?del_promo=<?php echo $p['id']; ?>" style="color:red;">Delete</a></td>
                    </tr>
                    <?php endwhile; ?>
                </table>
            </div>
        </div>

    </div>

    <!-- Simple JS for Tab Switching -->
    <script>
        function showSection(id, element) {
            // Hide all sections
            document.querySelectorAll('.section').forEach(el => el.classList.remove('active'));
            // Show target section
            document.getElementById(id).classList.add('active');
            
            // Sidebar active state
            document.querySelectorAll('.menu-item').forEach(el => el.classList.remove('active'));
            element.classList.add('active');
            
            // Save state (Optional)
            localStorage.setItem('adminTab', id);
        }

        // Restore last tab on refresh
        let lastTab = localStorage.getItem('adminTab');
        if(lastTab) {
            let el = document.querySelector(`.menu-item[onclick="showSection('${lastTab}', this)"]`);
            if(el) showSection(lastTab, el);
        }
    </script>
</body>
</html>