<?php
require_once __DIR__ . '/../db/config.php';

header('Content-Type: application/json');

try {
    $pdo = db();
    $username = $_GET['username'] ?? null;
    
    // Get top fans from the fans table
    $stmt = $pdo->query("SELECT name as username, points as total_likes, photo, is_fan_of_month, loyalty_points, chat_color, dj_day_until FROM fans ORDER BY points DESC LIMIT 5");
    $fans = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If username provided and not in top 5, fetch it specifically
    if ($username) {
        $found = false;
        foreach ($fans as $f) {
            if (strtolower($f['username']) === strtolower($username)) {
                $found = true;
                break;
            }
        }
        if (!$found) {
            $stmt = $pdo->prepare("SELECT name as username, points as total_likes, photo, is_fan_of_month, loyalty_points, chat_color, dj_day_until FROM fans WHERE name = ?");
            $stmt->execute([$username]);
            $userFan = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($userFan) {
                $userFan['is_extra'] = true;
                $fans[] = $userFan;
            }
        }
    }

    // Add level and progress logic
foreach ($fans as &$fan) {
    $fan['badges'] = [];
    $points = $fan['total_likes'];
    
    // Level Calculation
    if ($points >= 2500) {
        $fan['level'] = 5;
        $fan['level_name'] = 'Leyenda';
        $fan['level_color'] = '#a855f7'; // Purple
        $fan['next_level_points'] = 0;
        $fan['level_progress'] = 100;
        $fan['unlocked_emoji'] = '👑';
    } elseif ($points >= 1000) {
        $fan['level'] = 4;
        $fan['level_name'] = 'Super Fan';
        $fan['level_color'] = '#f97316'; // Orange
        $fan['next_level_points'] = 2500;
        $fan['level_progress'] = (($points - 1000) / (2500 - 1000)) * 100;
        $fan['unlocked_emoji'] = '🔥';
    } elseif ($points >= 500) {
        $fan['level'] = 3;
        $fan['level_name'] = 'Fan Leal';
        $fan['level_color'] = '#22c55e'; // Green
        $fan['next_level_points'] = 1000;
        $fan['level_progress'] = (($points - 500) / (1000 - 500)) * 100;
        $fan['unlocked_emoji'] = '⭐';
    } elseif ($points >= 100) {
        $fan['level'] = 2;
        $fan['level_name'] = 'Oyente Frecuente';
        $fan['level_color'] = '#3b82f6'; // Blue
        $fan['next_level_points'] = 500;
        $fan['level_progress'] = (($points - 100) / (500 - 100)) * 100;
        $fan['unlocked_emoji'] = '';
    } else {
        $fan['level'] = 1;
        $fan['level_name'] = 'Novato';
        $fan['level_color'] = '#94a3b8'; // Slate
        $fan['next_level_points'] = 100;
        $fan['level_progress'] = ($points / 100) * 100;
        $fan['unlocked_emoji'] = '';
    }

    if ($fan['is_fan_of_month']) {
        $fan['badges'][] = ['icon' => 'bi-star-fill', 'color' => '#facc15', 'label' => 'Fan del Mes'];
    }
    
    $isDj = $fan['dj_day_until'] && strtotime($fan['dj_day_until']) > time();
    if ($isDj) {
        $fan['badges'][] = ['icon' => 'bi-headphones', 'color' => '#facc15', 'label' => 'DJ INVITADO'];
        $fan['level_color'] = '#facc15';
        $fan['level_name'] = 'DJ INVITADO';
    }

    if ($fan['loyalty_points'] > 0) {
        $fan['badges'][] = ['icon' => 'bi-heart-fill', 'color' => '#00e676', 'label' => 'Fan Leal'];
    }

    if ($points >= 1000) {
        $fan['badges'][] = ['icon' => 'bi-gem', 'color' => '#38bdf8', 'label' => 'Diamante'];
    } elseif ($points >= 500) {
        $fan['badges'][] = ['icon' => 'bi-shield-check', 'color' => '#00c853', 'label' => 'Veterano'];
    }
    
    // Custom color based on level
    $fan['custom_color'] = $fan['level_color'];
    if ($fan['is_fan_of_month']) $fan['custom_color'] = '#facc15';
}

    echo json_encode(['success' => true, 'fans' => $fans]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
