<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/EmailService.php'; // Load EmailService (though not used directly here)

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

$success_msg = '';
$error_msg = '';

// =========================================================
// DATA ANALYTICS & REFERRAL SCHEME METRICS
// =========================================================
try {
    // Total referred associations
    $ref_counts_stmt = $pdo->query("SELECT COUNT(*) FROM referrals");
    $total_referred = $ref_counts_stmt->fetchColumn();

    // Total distinct referrers
    $referrers_stmt = $pdo->query("SELECT COUNT(DISTINCT referrer_user_id) FROM referrals");
    $total_referrers = $referrers_stmt->fetchColumn();

    // Total rewarded referrals (from referral_rewards table if exists)
    $rewarded_stmt = $pdo->query("SELECT COUNT(*) FROM referral_rewards");
    $total_rewarded = $rewarded_stmt->fetchColumn();

    // Total VIP days awarded
    $vip_days_stmt = $pdo->query("SELECT SUM(days_added) FROM referral_rewards");
    $total_vip_days = $vip_days_stmt->fetchColumn() ?: 0;

    // Fetch master ledger
    $master_query = "
        SELECT 
            r.id AS referral_record_id, 
            r.created_at AS referral_date, 
            r.referral_code_used,
            r.reward_given,
            u1.full_name AS invited_name, 
            u1.email AS invited_email,
            u2.full_name AS sponsor_name, 
            u2.email AS sponsor_email
        FROM referrals r
        LEFT JOIN users u1 ON r.invited_user_id = u1.id
        LEFT JOIN users u2 ON r.referrer_user_id = u2.id
        ORDER BY r.id DESC
    ";
    $referral_ledger = $pdo->query($master_query)->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $total_referred = 0;
    $total_referrers = 0;
    $total_rewarded = 0;
    $total_vip_days = 0;
    $referral_ledger = [];
    $error_msg = "Database Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Referral System Matrix</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;900&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; }
    </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">
        
        <!-- ========== HEADER ========== -->
        <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
            <div>
                <div class="inline-flex items-center space-x-2 bg-amber-500/10 border border-amber-500/20 px-3 py-1 rounded-full text-[10px] font-bold tracking-widest uppercase text-amber-400 mb-2">
                    <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse"></span>
                    <span>Affiliate Structures</span>
                </div>
                <h2 class="text-2xl sm:text-3xl font-extrabold text-slate-900 dark:text-white tracking-wide">Referral System</h2>
                <p class="text-xs text-slate-500 dark:text-gray-400 mt-0.5">Audit multi-tier networks and reward distribution.</p>
            </div>
        </div>

        <!-- ========== MESSAGES ========== -->
        <?php if(!empty($success_msg)): ?>
            <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 text-sm font-medium">
                <span>✅</span> <?php echo $success_msg; ?>
            </div>
        <?php endif; ?>
        <?php if(!empty($error_msg)): ?>
            <div class="bg-rose-50 border-rose-200 text-rose-700 dark:bg-rose-500/10 dark:border-rose-500/30 dark:text-rose-400 border rounded-xl p-3 flex items-center gap-2 shadow-sm text-sm font-medium">
                <span>❌</span> <?php echo $error_msg; ?>
            </div>
        <?php endif; ?>

        <!-- ========== STATS CARDS ========== -->
        <div class="grid grid-cols-1 sm: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 shadow-sm transition-colors duration-300">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Total Referrals</span>
                <span class="text-2xl font-extrabold text-slate-900 dark:text-white mt-1 block"><?php echo $total_referred; ?></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">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Active Promoters</span>
                <span class="text-2xl font-extrabold text-cyan-600 dark:text-cyan-400 mt-1 block"><?php echo $total_referrers; ?></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">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">Rewards Given</span>
                <span class="text-2xl font-extrabold text-emerald-600 dark:text-emerald-500 mt-1 block"><?php echo $total_rewarded; ?></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">
                <span class="text-[10px] text-slate-500 dark:text-gray-400 uppercase tracking-widest font-bold">VIP Days Awarded</span>
                <span class="text-2xl font-extrabold text-purple-600 dark:text-purple-400 mt-1 block"><?php echo $total_vip_days; ?></span>
            </div>
        </div>

        <!-- ========== LEDGER TABLE ========== -->
        <div class="bg-white border border-slate-200 dark:bg-slate-900 dark:border-slate-800 rounded-2xl p-4 sm:p-6 shadow-sm transition-colors duration-300">
            <h3 class="font-bold text-lg mb-5 text-slate-900 dark:text-white border-b border-slate-200 dark:border-slate-800 pb-3">Network Associations Ledger</h3>
            
            <div class="overflow-x-auto -mx-4 sm:-mx-6 px-4 sm:px-6">
                <table class="w-full text-left text-sm border-collapse min-w-[700px]">
                    <thead>
                        <tr class="text-slate-500 dark:text-gray-500 border-b border-slate-200 dark:border-slate-800 text-[10px] tracking-wider uppercase font-black">
                            <th class="py-3 px-2">Invited Member</th>
                            <th class="py-3 px-2">Sponsor</th>
                            <th class="py-3 px-2 text-center">Date</th>
                            <th class="py-3 px-2 text-center">Code Used</th>
                            <th class="py-3 px-2 text-center">Reward</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 dark:divide-slate-800/60 text-slate-700 dark:text-gray-300 text-xs">
                        <?php foreach($referral_ledger as $ref): 
                            $reg_date = date("d M Y", strtotime($ref['referral_date']));
                            $reward_status = $ref['reward_given'] ? '<span class="text-emerald-500 font-bold">✅ Given</span>' : '<span class="text-amber-500 font-bold">⏳ Pending</span>';
                        ?>
                        <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/40 transition group">
                            <td class="py-3 px-2">
                                <div class="font-bold text-slate-900 dark:text-white text-sm"><?php echo htmlspecialchars($ref['invited_name'] ?? 'Deleted User'); ?></div>
                                <div class="text-[10px] text-slate-500 dark:text-gray-400"><?php echo htmlspecialchars($ref['invited_email'] ?? ''); ?></div>
                            </td>
                            <td class="py-3 px-2">
                                <?php if(!empty($ref['sponsor_name'])): ?>
                                    <div class="font-bold text-cyan-600 dark:text-cyan-400 text-sm"><?php echo htmlspecialchars($ref['sponsor_name']); ?></div>
                                    <div class="text-[10px] text-slate-500 dark:text-gray-400"><?php echo htmlspecialchars($ref['sponsor_email']); ?></div>
                                <?php else: ?>
                                    <span class="text-[10px] font-bold italic text-slate-400">Direct / Disconnected</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-3 px-2 text-center text-slate-500 dark:text-gray-400 font-medium"><?php echo $reg_date; ?></td>
                            <td class="py-3 px-2 text-center font-mono text-[10px] font-bold text-amber-500 uppercase"><?php echo htmlspecialchars($ref['referral_code_used']); ?></td>
                            <td class="py-3 px-2 text-center"><?php echo $reward_status; ?></td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <?php if(empty($referral_ledger)): ?>
                        <tr>
                            <td colspan="5" class="py-12 text-center text-slate-400 dark:text-gray-500 text-xs font-medium uppercase tracking-widest">
                                No referral records found.
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </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">
            Referral system last synced: <?php echo date('H:i:s'); ?>
            <br>
            <span class="text-[8px] text-slate-500">📧 Referral reward emails are sent automatically when users earn VIP days.</span>
        </div>

    </main>
</body>
</html>