<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once '../config.php';

// Auth Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

// Default Variables (Safeguard)
$totalUsers = 0; $totalBalance = 0.00; 
$pendingDeposits = 0; $pendingWithdraws = 0;
$totalBets = 0; $totalBetAmount = 0.00;
$recentUsers = []; $dbError = "";

try {
    global $pdo;

    // 1. Fetch Users & Balance
    $totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn() ?: 0;
    $totalBalance = $pdo->query("SELECT SUM(main_balance) FROM wallets")->fetchColumn() ?: 0.00;
    
    // 2. Fetch Deposits & Withdrawals (Safe try-catch for missing tables)
    try {
        $pendingDeposits = $pdo->query("SELECT COUNT(*) FROM deposit_requests WHERE status = 'pending'")->fetchColumn() ?: 0;
        $pendingWithdraws = $pdo->query("SELECT COUNT(*) FROM withdraw_requests WHERE status = 'pending'")->fetchColumn() ?: 0;
    } catch(Exception $e) { /* Ignore if table missing */ }

    // 3. Fetch Betting Stats
    try {
        $totalBets = $pdo->query("SELECT COUNT(*) FROM bets")->fetchColumn() ?: 0;
        $totalBetAmount = $pdo->query("SELECT SUM(amount) FROM bets")->fetchColumn() ?: 0.00;
    } catch(Exception $e) { /* Ignore if table missing */ }

    // 4. Fetch Recent 5 Users
    $recentUsers = $pdo->query("SELECT id, username, mobile, created_at FROM users ORDER BY id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    $dbError = $e->getMessage();
}

$pageTitle = "Dashboard Overview";
require_once 'includes/header.php';
?>

<style>
    /* Welcome Banner */
    .welcome-banner {
        background: linear-gradient(135deg, #1e1e2d 0%, #2a2a3c 100%);
        border-radius: 16px;
        padding: 30px;
        color: white;
        margin-bottom: 25px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        position: relative;
        overflow: hidden;
    }
    .welcome-banner::after {
        content: ''; position: absolute; right: -50px; top: -50px;
        width: 200px; height: 200px; background: rgba(255,255,255,0.05); border-radius: 50%;
    }
    .wb-title { font-weight: 900; font-size: 24px; margin-bottom: 5px; }
    .wb-subtitle { color: #a1a5b7; font-size: 14px; font-weight: 600; }

    /* Modern Dashboard Cards */
    .dash-card {
        background: #fff;
        border-radius: 16px;
        padding: 24px;
        border: 1px solid #f0f0f0;
        box-shadow: 0 5px 20px rgba(0,0,0,0.02);
        transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
        position: relative;
        display: flex;
        align-items: center;
        gap: 20px;
    }
    .dash-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(0,0,0,0.08);
        border-color: #e4e6ef;
    }
    
    /* Icon Wrappers with Glowing effect */
    .icon-box {
        width: 60px; height: 60px; border-radius: 14px; display: flex; justify-content: center; align-items: center; font-size: 24px; flex-shrink: 0;
    }
    .icon-blue { background: rgba(0, 158, 247, 0.1); color: #009ef7; }
    .icon-green { background: rgba(80, 205, 137, 0.1); color: #50cd89; }
    .icon-red { background: rgba(241, 65, 108, 0.1); color: #f1416c; }
    .icon-purple { background: rgba(114, 57, 234, 0.1); color: #7239ea; }
    .icon-orange { background: rgba(255, 152, 0, 0.1); color: #ff9800; }

    /* Typography */
    .dc-title { color: #a1a5b7; font-size: 13px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
    .dc-value { color: #181c32; font-size: 24px; font-weight: 900; margin: 0; line-height: 1.2; }

    /* Quick Action Buttons */
    .quick-btn {
        border-radius: 12px; padding: 15px; font-weight: 800; font-size: 14px; text-transform: uppercase; letter-spacing: 1px; transition: 0.2s;
    }

    /* Beautiful Table */
    .table-custom th { background: #f4f5f8; color: #a1a5b7; font-size: 12px; text-transform: uppercase; border: none; padding: 15px; }
    .table-custom td { vertical-align: middle; padding: 15px; border-bottom: 1px dashed #eee; color: #3f4254; font-weight: 600; }
    .table-custom tr:hover { background: #fcfcfc; }
</style>

<?php if($dbError): ?>
    <div class="alert alert-danger fw-bold border-0 shadow-sm rounded-4 mb-4">
        <i class="fas fa-exclamation-triangle"></i> System Notice: <?= htmlspecialchars($dbError) ?>
    </div>
<?php endif; ?>

<div class="welcome-banner">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
        <div>
            <h1 class="wb-title">Welcome back, Admin! 👋</h1>
            <p class="wb-subtitle m-0">Here is what's happening on your platform today.</p>
        </div>
        <div>
            <span class="badge bg-light text-dark py-2 px-3 fs-6 rounded-pill border shadow-sm">
                <i class="far fa-calendar-alt text-primary me-2"></i> <?= date('d M Y, h:i A') ?>
            </span>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    
    <div class="col-12 col-md-6 col-xl-4">
        <div class="dash-card">
            <div class="icon-box icon-blue"><i class="fas fa-users"></i></div>
            <div>
                <div class="dc-title">Total Users</div>
                <h3 class="dc-value"><?= number_format($totalUsers) ?></h3>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-6 col-xl-4">
        <div class="dash-card">
            <div class="icon-box icon-green"><i class="fas fa-wallet"></i></div>
            <div>
                <div class="dc-title">Users Balance</div>
                <h3 class="dc-value">₹<?= number_format((float)$totalBalance, 2) ?></h3>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-6 col-xl-4">
        <div class="dash-card">
            <div class="icon-box icon-purple"><i class="fas fa-dice"></i></div>
            <div>
                <div class="dc-title">Total Bet Volume</div>
                <h3 class="dc-value">₹<?= number_format((float)$totalBetAmount, 2) ?></h3>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-6 col-xl-6">
        <div class="dash-card border-bottom border-warning border-3">
            <div class="icon-box icon-orange"><i class="fas fa-hand-holding-usd"></i></div>
            <div class="d-flex justify-content-between align-items-center w-100">
                <div>
                    <div class="dc-title">Pending Deposits</div>
                    <h3 class="dc-value"><?= number_format($pendingDeposits) ?> <span class="fs-6 text-muted fw-bold">Requests</span></h3>
                </div>
                <a href="deposit_requests.php" class="btn btn-sm btn-light-warning text-warning fw-bold px-3 py-2 rounded-pill">Review</a>
            </div>
        </div>
    </div>

    <div class="col-12 col-md-6 col-xl-6">
        <div class="dash-card border-bottom border-danger border-3">
            <div class="icon-box icon-red"><i class="fas fa-money-check-alt"></i></div>
            <div class="d-flex justify-content-between align-items-center w-100">
                <div>
                    <div class="dc-title">Pending Withdrawals</div>
                    <h3 class="dc-value"><?= number_format($pendingWithdraws) ?> <span class="fs-6 text-muted fw-bold">Requests</span></h3>
                </div>
                <a href="withdraw_requests.php" class="btn btn-sm btn-light-danger text-danger fw-bold px-3 py-2 rounded-pill">Review</a>
            </div>
        </div>
    </div>

</div>

<div class="row g-4">
    
    <div class="col-12 col-xl-8">
        <div class="custom-card h-100 m-0">
            <div class="custom-card-header d-flex justify-content-between align-items-center">
                <h6 class="m-0 fw-bold fs-5 text-dark"><i class="fas fa-user-plus text-primary me-2"></i> Newest Members</h6>
                <a href="users.php" class="btn btn-sm btn-outline-primary fw-bold px-3 rounded-pill">View All</a>
            </div>
            <div class="table-responsive">
                <table class="table table-custom align-middle m-0">
                    <thead>
                        <tr>
                            <th class="ps-4">User Info</th>
                            <th>Mobile</th>
                            <th>Join Date</th>
                            <th class="text-end pe-4">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(!empty($recentUsers)): foreach($recentUsers as $user): ?>
                        <tr>
                            <td class="ps-4">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="bg-light-primary text-primary rounded-circle d-flex align-items-center justify-content-center fw-bold" style="width:40px; height:40px;">
                                        <?= strtoupper(substr($user['username'], 0, 1)) ?>
                                    </div>
                                    <div>
                                        <div class="fw-bold text-dark fs-6"><?= htmlspecialchars($user['username']) ?></div>
                                        <div class="text-muted" style="font-size:11px;">ID: #<?= $user['id'] ?></div>
                                    </div>
                                </div>
                            </td>
                            <td><span class="badge bg-light text-dark border px-2 py-1 fs-6"><?= htmlspecialchars($user['mobile']) ?></span></td>
                            <td>
                                <div class="fw-bold"><?= date('d M, Y', strtotime($user['created_at'])) ?></div>
                                <div class="text-muted" style="font-size:11px;"><?= date('h:i A', strtotime($user['created_at'])) ?></div>
                            </td>
                            <td class="text-end pe-4">
                                <a href="users.php?edit=<?= $user['id'] ?>" class="btn btn-icon btn-light btn-sm rounded-circle text-primary"><i class="fas fa-eye"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; else: ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted fw-bold"><i class="fas fa-inbox fs-1 mb-3 text-light"></i><br>No users found yet.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-4">
        <div class="custom-card h-100 m-0">
            <div class="custom-card-header">
                <h6 class="m-0 fw-bold fs-5 text-dark"><i class="fas fa-bolt text-warning me-2"></i> Quick Actions</h6>
            </div>
            <div class="card-body p-4 d-flex flex-column gap-3">
                <a href="cricketmanage.php" class="btn btn-primary quick-btn text-start d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-baseball-ball me-2"></i> Live Cricket Control</span>
                    <i class="fas fa-arrow-right"></i>
                </a>
                <a href="games.php" class="btn btn-success quick-btn text-start d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-gamepad me-2"></i> Manage Games</span>
                    <i class="fas fa-arrow-right"></i>
                </a>
                <a href="banners.php" class="btn btn-info text-white quick-btn text-start d-flex justify-content-between align-items-center">
                    <span><i class="fas fa-images me-2"></i> Update Banners</span>
                    <i class="fas fa-arrow-right"></i>
                </a>
                <a href="settings.php" class="btn btn-dark quick-btn text-start d-flex justify-content-between align-items-center mt-auto">
                    <span><i class="fas fa-cog me-2"></i> Site Settings</span>
                    <i class="fas fa-arrow-right"></i>
                </a>
            </div>
        </div>
    </div>

</div>

<?php require_once 'includes/footer.php'; ?>