<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'] ?? 'user';
$is_admin = ($user_role === 'admin');

// 1. Fetch Top Earners for TODAY
try {
    $stmt = $pdo->prepare("
        SELECT 
            u.id, 
            u.name, 
            u.email, 
            u.phone, 
            SUM(t.amount) as today_earnings 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        JOIN users u ON v.user_id = u.id 
        WHERE t.status = 'completed' AND DATE(t.created_at) = CURDATE() 
        GROUP BY u.id 
        ORDER BY today_earnings DESC
    ");
    $stmt->execute();
    $top_earners = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $top_earners = [];
}

// 2. Check if current user is "Active" (at least 1 transaction today)
$is_active = false;
if ($is_admin) {
    $is_active = true;
} else {
    try {
        $stmt = $pdo->prepare("
            SELECT COUNT(*) FROM transactions t 
            JOIN videos v ON t.video_id = v.id 
            WHERE v.user_id = ? AND t.status = 'completed' AND DATE(t.created_at) = CURDATE()
        ");
        $stmt->execute([$user_id]);
        $is_active = $stmt->fetchColumn() > 0;
    } catch (PDOException $e) {}
}

// Privacy Masking Functions
function maskEmail($email) {
    if (strpos($email, '@') !== false) {
        list($first, $last) = explode('@', $email);
        $len = strlen($first);
        if ($len <= 2) return $first . '***@' . $last;
        return substr($first, 0, 2) . str_repeat('*', $len - 2) . '@' . $last;
    }
    return $email;
}

function maskPhone($phone) {
    if (empty($phone)) return 'N/A';
    if (strlen($phone) > 5) {
        return substr($phone, 0, 3) . str_repeat('*', strlen($phone) - 3);
    }
    return str_repeat('*', strlen($phone));
}

function getMedal($index) {
    if ($index === 0) return '🥇';
    if ($index === 1) return '🥈';
    if ($index === 2) return '🥉';
    return $index + 1;
}

$pageTitle = "Top Earners - SonicPesa";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
    .content-blur { filter: blur(12px); pointer-events: none; user-select: none; transition: filter 0.5s ease; }
    .sophisticated-table-card { 
        background: white; 
        border-radius: 16px; 
        border: 1px solid rgba(0,0,0,0.05); 
        box-shadow: 0 10px 30px rgba(0,0,0,0.04); 
        overflow: hidden; 
    }
    .medal-wrapper { 
        font-size: 1.75rem; 
        display: inline-flex; 
        align-items: center; 
        justify-content: center; 
        width: 48px; 
        height: 48px; 
        border-radius: 12px;
        background: rgba(255,159,41,0.08);
    }
    .rank-cell { font-weight: 800; color: #94a3b8; font-size: 1.1rem; }
    .user-avatar-sm { 
        width: 40px; 
        height: 40px; 
        border-radius: 12px; 
        background: linear-gradient(135deg, #6366f1 0%, #4338ca 100%); 
        color: white; 
        font-weight: 700; 
        display: flex; 
        align-items: center; 
        justify-content: center;
        box-shadow: 0 4px 10px rgba(99, 102, 241, 0.2);
    }
    .earnings-badge {
        font-family: 'Inter', sans-serif;
        letter-spacing: -0.5px;
    }
    .top-rank-row { background: rgba(99, 102, 241, 0.03); }
    .status-active-pulse {
        width: 8px;
        height: 8px;
        background: #10b981;
        border-radius: 50%;
        display: inline-block;
        box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4);
        animation: activePulse 2s infinite;
    }
    @keyframes activePulse {
        0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
        70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }
        100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
    }
</style>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body <?= !$is_active ? 'content-blur' : '' ?>">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <div>
                    <h4 class="fw-bold mb-0"><iconify-icon icon="solar:ranking-bold-duotone" class="text-primary-600 me-8"></iconify-icon> Today's Earnings Leaderboard</h4>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-0 text-sm mt-4">
                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-secondary-light">Dashboard</a></li>
                            <li class="breadcrumb-item active text-primary-600">Top Earners</li>
                        </ol>
                    </nav>
                </div>
                <div class="d-flex align-items-center gap-12">
                    <span class="badge bg-success-focus text-success-main px-16 py-8 radius-20 fw-bold d-flex align-items-center gap-8">
                        <span class="status-active-pulse"></span>
                        LIVE DATA
                    </span>
                    <span class="badge bg-primary-100 text-primary-600 px-16 py-8 radius-20 fw-bold text-sm">
                        <?= count($top_earners) ?> Active Earners
                    </span>
                </div>
            </div>

            <div class="card sophisticated-table-card">
                <div class="card-header border-bottom bg-base py-16 px-24 d-flex align-items-center justify-content-between">
                    <h6 class="mb-0 fw-bold">Performance Rankings</h6>
                    <div class="text-xs text-secondary-light fw-bold text-uppercase ls-1">Refreshes every 24h</div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover border-0 mb-0">
                            <thead>
                                <tr class="bg-light">
                                    <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light" style="width: 80px;">Rank</th>
                                    <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Influencer Account</th>
                                    <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light">Contact Summary</th>
                                    <th class="px-24 py-16 border-0 text-xs fw-bold text-uppercase text-secondary-light text-end">Daily Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(empty($top_earners)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center py-60">
                                            <div class="p-24 bg-base radius-12 border d-inline-block">
                                                <iconify-icon icon="solar:chart-square-broken" class="text-4xl text-secondary-light mb-12 d-block mx-auto"></iconify-icon>
                                                <span class="text-secondary-light fw-medium">No earnings recorded for today yet.</span>
                                            </div>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach($top_earners as $index => $row): ?>
                                        <tr class="<?= $index < 3 ? 'top-rank-row' : '' ?>">
                                            <td class="px-24 py-16 border-0 vertical-align-middle">
                                                <div class="medal-wrapper">
                                                    <?php $medal = getMedal($index); echo (is_string($medal) ? $medal : '<span class="rank-cell">#'.str_pad($medal, 2, '0', STR_PAD_LEFT).'</span>'); ?>
                                                </div>
                                            </td>
                                            <td class="px-24 py-16 border-0">
                                                <div class="d-flex align-items-center gap-16">
                                                    <div class="user-avatar-sm" style="background: <?= $index === 0 ? 'linear-gradient(135deg, #FF9F29, #f39016)' : ($index === 1 ? 'linear-gradient(135deg, #abb1be, #7e879a)' : ($index === 2 ? 'linear-gradient(135deg, #dc8a55, #b36336)' : '')) ?>">
                                                        <?= strtoupper(substr($row['name'], 0, 1)) ?>
                                                    </div>
                                                    <div>
                                                        <div class="fw-bold text-dark text-md"><?= $is_admin ? htmlspecialchars($row['name']) : 'Influencer BF-'.str_pad($row['id'], 4, '0', STR_PAD_LEFT) ?></div>
                                                        <div class="text-xs text-secondary-light mt-2 fw-medium"><?= $is_admin ? htmlspecialchars($row['email']) : maskEmail($row['email']) ?></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="px-24 py-16 border-0">
                                                <div class="d-flex align-items-center gap-8">
                                                    <iconify-icon icon="solar:phone-bold-duotone" class="text-secondary-light"></iconify-icon>
                                                    <span class="text-sm fw-semibold text-secondary-light">
                                                        <?= $is_admin ? htmlspecialchars($row['phone']) : maskPhone($row['phone']) ?>
                                                    </span>
                                                </div>
                                            </td>
                                            <td class="px-24 py-16 border-0 text-end">
                                                <div class="fw-extrabold text-primary-600 text-xl earnings-badge">TSH <?= number_format($row['today_earnings']) ?></div>
                                                <div class="text-xxs text-secondary-light text-uppercase fw-bold ls-1 mt-4">Confirmed Net Earn</div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <?php include 'includes/footer.php'; ?>
    </main>

    <?php if(!$is_active): ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Swal.fire({
                title: 'Access Restricted',
                text: 'Only active users can view the live rankings. Please complete at least one transaction today to unlock this feature!',
                icon: 'warning',
                confirmButtonText: 'Back to Dashboard',
                allowOutsideClick: false,
                allowEscapeKey: false,
                confirmButtonColor: '#6366f1'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'dashboard';
                }
            });
        });
    </script>
    <?php endif; ?>
</body>
</html>


