<?php
// Ensure this path jumps up from public/admin/ to the root for config
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

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

// ==========================================
// DYNAMIC DASHBOARD QUERIES
// ==========================================

// 1. Prediction Metrics
$total_preds = $pdo->query("SELECT COUNT(*) FROM admin_manual_tips")->fetchColumn();

// 2. User & VIP Metrics
$total_users = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$total_vips = $pdo->query("SELECT COUNT(*) FROM users WHERE user_tier = 'VIP'")->fetchColumn();
$recent_users = $pdo->query("SELECT * FROM users ORDER BY id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

// 3. Revenue from approved transactions (VIP upgrades)
$total_revenue = $pdo->query("SELECT SUM(amount_paid) FROM transactions WHERE status = 'approved'")->fetchColumn();
$total_revenue = $total_revenue ? $total_revenue : 0.00;

// 4. Pending transactions (unapproved)
$pending_transactions = $pdo->query("SELECT COUNT(*) FROM transactions WHERE status = 'pending'")->fetchColumn();

// 5. Recent transactions (all) for table
$recent_transactions = $pdo->query("SELECT * FROM transactions ORDER BY id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

// 6. System engine mode
$active_engine = defined('DATA_SOURCE') ? strtolower(DATA_SOURCE) : 'manual';

// 7. Pending tips (for alerts)
$pending_tips = $pdo->query("SELECT COUNT(*) FROM admin_manual_tips WHERE outcome = 'PENDING'")->fetchColumn();

// 8. Build alerts
$alerts = [];
if ($pending_transactions > 0) {
    $alerts[] = [
        'type' => 'warning',
        'message' => $pending_transactions . ' transaction' . ($pending_transactions > 1 ? 's' : '') . ' awaiting approval.'
    ];
}
if ($pending_tips > 0) {
    $alerts[] = [
        'type' => 'info',
        'message' => $pending_tips . ' match' . ($pending_tips > 1 ? 'es' : '') . ' are still pending outcome.'
    ];
}
if ($active_engine === 'api') {
    $api_key = defined('FOOTBALL_API_KEY') ? FOOTBALL_API_KEY : '';
    if (empty($api_key) || $api_key === '5166ce33c6b95ec8adba7f26e037f088') {
        $alerts[] = [
            'type' => 'danger',
            'message' => 'API mode is enabled but the API key appears to be the default. Please update the API key in config.'
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - <?php echo $site_name ?? 'Football Pred Pro'; ?></title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/output.css?v=<?php echo time(); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
        .dark ::-webkit-scrollbar-thumb { background: #334155; }
        .alert-enter {
            animation: slideDown 0.3s ease forwards;
        }
        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .alert-dismiss { cursor: pointer; opacity: 0.7; transition: opacity 0.2s; }
        .alert-dismiss:hover { opacity: 1; }
    </style>
    <script>
        if (localStorage.getItem('fpp_theme') === 'dark') {
            document.documentElement.classList.add('dark');
        } else {
            document.documentElement.classList.remove('dark');
        }
    </script>
</head>
<body class="bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-gray-200 antialiased min-h-screen flex flex-col md:flex-row transition-colors duration-300">

    <?php include __DIR__ . '/includes/admin-sidebar.php'; ?>

    <main class="flex-1 p-4 sm:p-6 md:p-8 overflow-x-hidden flex flex-col gap-6">
        
        <!-- ========== SYSTEM ALERTS ========== -->
        <?php if (!empty($alerts)): ?>
            <div class="space-y-2">
                <?php foreach ($alerts as $alert): 
                    $bg = $alert['type'] === 'danger' ? 'bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400' :
                          ($alert['type'] === 'warning' ? 'bg-amber-50 border-amber-200 text-amber-700 dark:bg-amber-500/10 dark:border-amber-500/30 dark:text-amber-400' :
                          'bg-blue-50 border-blue-200 text-blue-700 dark:bg-blue-500/10 dark:border-blue-500/30 dark:text-blue-400');
                    $icon = $alert['type'] === 'danger' ? '🔴' : ($alert['type'] === 'warning' ? '⚠️' : 'ℹ️');
                ?>
                    <div class="alert-enter border rounded-xl p-3 flex items-center justify-between shadow-sm <?php echo $bg; ?>">
                        <div class="flex items-center gap-2 text-sm font-medium">
                            <span><?php echo $icon; ?></span>
                            <span><?php echo htmlspecialchars($alert['message']); ?></span>
                        </div>
                        <button class="alert-dismiss text-sm font-bold" onclick="this.parentElement.style.display='none'">✕</button>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-500/10 dark:border-emerald-500/30 dark:text-emerald-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm alert-enter">
                <span>✅</span>
                <span class="text-sm font-medium">All systems operational. No pending alerts.</span>
            </div>
        <?php endif; ?>

        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Admin Dashboard</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Revenue overview & system metrics at a glance.</p>
            </div>
            <div class="flex items-center gap-3 bg-slate-100 dark:bg-slate-800/40 px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-700">
                <span class="text-xs font-bold text-slate-500 dark:text-gray-400 uppercase tracking-wider">Data Source:</span>
                <span class="text-xs font-black <?php echo $active_engine === 'api' ? 'text-emerald-600 dark:text-emerald-500' : 'text-amber-600 dark:text-amber-500'; ?>">
                    <?php echo strtoupper($active_engine); ?>
                </span>
                <span class="w-2 h-2 rounded-full <?php echo $active_engine === 'api' ? 'bg-emerald-500' : 'bg-amber-500'; ?> animate-pulse"></span>
            </div>
        </div>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
            
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 flex flex-col justify-between relative overflow-hidden h-36 transition-colors duration-300 shadow-sm hover:shadow-md">
                <div>
                    <h4 class="text-xs text-slate-500 dark:text-gray-400 font-medium">Total Predictions</h4>
                    <span class="text-2xl font-bold text-slate-900 dark:text-white mt-1 block"><?php echo number_format($total_preds); ?></span>
                </div>
                <svg class="absolute bottom-0 left-0 w-full h-16 text-cyan-500" preserveAspectRatio="none" viewBox="0 0 100 30">
                    <path d="M0,30 L0,20 C10,15 20,25 30,15 C40,5 50,20 60,10 C70,0 80,15 100,5 L100,30 Z" fill="currentColor" fill-opacity="0.1"></path>
                    <path d="M0,20 C10,15 20,25 30,15 C40,5 50,20 60,10 C70,0 80,15 100,5" fill="none" stroke="currentColor" stroke-width="1.5"></path>
                </svg>
            </div>

            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 flex flex-col justify-between relative overflow-hidden h-36 transition-colors duration-300 shadow-sm hover:shadow-md">
                <div class="flex justify-between items-start">
                    <div>
                        <h4 class="text-xs text-slate-500 dark:text-gray-400 font-medium">VIP Members</h4>
                        <span class="text-2xl font-bold text-slate-900 dark:text-white mt-1 block"><?php echo number_format($total_vips); ?></span>
                    </div>
                    <svg class="w-4 h-4 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"></path></svg>
                </div>
                <svg class="absolute bottom-0 left-0 w-full h-16 text-emerald-500" preserveAspectRatio="none" viewBox="0 0 100 30">
                    <path d="M0,30 L0,25 C15,20 25,28 40,15 C55,2 70,18 85,10 C95,5 100,2 100,2 L100,30 Z" fill="currentColor" fill-opacity="0.1"></path>
                    <path d="M0,25 C15,20 25,28 40,15 C55,2 70,18 85,10 C95,5 100,2 100,2" fill="none" stroke="currentColor" stroke-width="1.5"></path>
                </svg>
            </div>

            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 flex flex-col justify-between relative overflow-hidden h-36 transition-colors duration-300 shadow-sm hover:shadow-md">
                <div class="flex justify-between items-start">
                    <div>
                        <h4 class="text-xs text-slate-500 dark:text-gray-400 font-medium">Total Revenue (Approved)</h4>
                        <span class="text-2xl font-bold text-slate-900 dark:text-white mt-1 block">$<?php echo number_format($total_revenue, 2); ?></span>
                    </div>
                    <svg class="w-4 h-4 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                </div>
                <svg class="absolute bottom-0 left-0 w-full h-16 text-emerald-500" preserveAspectRatio="none" viewBox="0 0 100 30">
                    <path d="M0,30 L0,22 C10,18 20,25 35,10 C50,-5 65,15 80,5 C90,-2 100,8 100,8 L100,30 Z" fill="currentColor" fill-opacity="0.1"></path>
                    <path d="M0,22 C10,18 20,25 35,10 C50,-5 65,15 80,5 C90,-2 100,8 100,8" fill="none" stroke="currentColor" stroke-width="1.5"></path>
                </svg>
            </div>

            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 flex flex-col justify-between relative overflow-hidden h-36 transition-colors duration-300 shadow-sm hover:shadow-md">
                <div class="flex justify-between items-start">
                    <div>
                        <h4 class="text-xs text-slate-500 dark:text-gray-400 font-medium">Pending Transactions</h4>
                        <span class="text-2xl font-bold <?php echo $pending_transactions > 0 ? 'text-amber-500' : 'text-slate-900 dark:text-white'; ?> mt-1 block"><?php echo $pending_transactions; ?></span>
                    </div>
                    <svg class="w-4 h-4 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                </div>
                <svg class="absolute bottom-0 left-0 w-full h-16 text-amber-500" preserveAspectRatio="none" viewBox="0 0 100 30">
                    <path d="M0,30 L0,25 C15,20 25,28 40,15 C55,2 70,18 85,10 C95,5 100,2 100,2 L100,30 Z" fill="currentColor" fill-opacity="0.1"></path>
                    <path d="M0,25 C15,20 25,28 40,15 C55,2 70,18 85,10 C95,5 100,2 100,2" fill="none" stroke="currentColor" stroke-width="1.5"></path>
                </svg>
            </div>
        </div>

        <!-- ========== SECOND ROW ========== -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <h4 class="text-xs text-slate-500 dark:text-gray-400 font-medium">Total Signups</h4>
                <span class="text-2xl font-bold text-slate-900 dark:text-white mt-1 block"><?php echo number_format($total_users); ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <h4 class="text-xs text-slate-500 dark:text-gray-400 font-medium">Pending Match Outcomes</h4>
                <span class="text-2xl font-bold <?php echo $pending_tips > 0 ? 'text-amber-500' : 'text-slate-900 dark:text-white'; ?> mt-1 block"><?php echo $pending_tips; ?></span>
            </div>
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <h4 class="text-xs text-slate-500 dark:text-gray-400 font-medium">Ad Revenue (Month)</h4>
                <span class="text-2xl font-bold text-slate-900 dark:text-white mt-1 block">$0.00</span>
            </div>
        </div>

        <!-- ========== TABLES: Recent Users & Recent Transactions ========== -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            
            <!-- Recent Users -->
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-sm uppercase tracking-wider text-slate-600 dark:text-gray-300">Latest User Signups</h3>
                    <a href="users.php" class="text-[10px] font-bold text-emerald-600 dark:text-emerald-500 hover:underline">View All →</a>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-[11px] border-collapse whitespace-nowrap">
                        <thead>
                            <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800">
                                <th class="py-2 px-2 font-medium">User</th>
                                <th class="py-2 px-2 font-medium">Email</th>
                                <th class="py-2 px-2 font-medium">Tier</th>
                                <th class="py-2 px-2 font-medium text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300">
                            <?php if (!empty($recent_users)): ?>
                                <?php foreach ($recent_users as $u): 
                                    $avatar_name = urlencode($u['full_name']);
                                    $tier_color = $u['user_tier'] === 'VIP' ? 'text-amber-600 dark:text-amber-500' : 'text-slate-500 dark:text-gray-400';
                                ?>
                                <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition">
                                    <td class="py-3 px-2 flex items-center space-x-2">
                                        <div class="w-6 h-6 bg-slate-200 dark:bg-gray-600 rounded-full overflow-hidden shrink-0">
                                            <img src="https://ui-avatars.com/api/?name=<?php echo $avatar_name; ?>&background=random&size=32" alt="Avatar" class="w-full h-full object-cover">
                                        </div>
                                        <span class="font-semibold text-slate-900 dark:text-white truncate max-w-[100px]"><?php echo htmlspecialchars($u['full_name']); ?></span>
                                    </td>
                                    <td class="py-3 px-2 text-slate-500 dark:text-gray-400 truncate max-w-[120px]"><?php echo htmlspecialchars($u['email']); ?></td>
                                    <td class="py-3 px-2 font-bold <?php echo $tier_color; ?>"><?php echo htmlspecialchars($u['user_tier']); ?></td>
                                    <td class="py-3 px-2 text-right">
                                        <a href="users.php?action=view&id=<?php echo $u['id']; ?>" class="inline-block bg-blue-50 text-blue-600 border border-blue-200 dark:bg-blue-500/10 dark:text-blue-400 dark:border-blue-500/30 px-2 py-1 rounded font-bold uppercase tracking-wider text-[9px] hover:bg-blue-100 dark:hover:bg-blue-500 dark:hover:text-white transition">View</a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="py-6 text-center text-slate-400 dark:text-gray-500">No users have registered yet.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Recent Transactions -->
            <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-5 shadow-sm transition-colors duration-300">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-sm uppercase tracking-wider text-slate-600 dark:text-gray-300">Recent Transactions</h3>
                    <a href="monetization.php" class="text-[10px] font-bold text-emerald-600 dark:text-emerald-500 hover:underline">View All →</a>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-left text-[11px] border-collapse whitespace-nowrap">
                        <thead>
                            <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800">
                                <th class="py-2 px-2 font-medium">Date</th>
                                <th class="py-2 px-2 font-medium">User</th>
                                <th class="py-2 px-2 font-medium">Amount</th>
                                <th class="py-2 px-2 font-medium text-center">Status</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300">
                            <?php if(!empty($recent_transactions)): ?>
                                <?php foreach($recent_transactions as $tx): 
                                    $user_name = 'User ' . $tx['user_id'];
                                    // Optionally fetch user name from users table, but we'll keep simple.
                                    $status_color = $tx['status'] === 'approved' ? 'text-emerald-500' : ($tx['status'] === 'pending' ? 'text-amber-500' : 'text-rose-500');
                                ?>
                                    <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/50 transition">
                                        <td class="py-3 px-2"><?php echo date("d M", strtotime($tx['created_at'])); ?></td>
                                        <td class="py-3 px-2 font-medium text-slate-800 dark:text-slate-200"><?php echo htmlspecialchars($user_name); ?></td>
                                        <td class="py-3 px-2 font-bold text-slate-800 dark:text-slate-300">$<?php echo number_format($tx['amount_paid'], 2); ?></td>
                                        <td class="py-3 px-2 text-center font-bold uppercase <?php echo $status_color; ?>"><?php echo htmlspecialchars($tx['status']); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="py-6 text-center text-slate-400 dark:text-gray-500">No transactions recorded yet.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ========== FOOTER ========== -->
        <div class="text-center text-[10px] text-slate-400 dark:text-gray-600 border-t border-slate-200 dark:border-slate-800 pt-4 mt-2">
            System running on <strong><?php echo strtoupper($active_engine); ?></strong> engine • Last sync: <?php echo date('H:i:s'); ?>
        </div>
    </main>

    <script>
        document.querySelectorAll('.alert-dismiss').forEach(btn => {
            btn.addEventListener('click', function() {
                this.closest('.border').style.display = 'none';
            });
        });
    </script>
</body>
</html>