<?php
session_start();
require_once(__DIR__ . '/config/settings.php');

$type = $_GET['type'] ?? 'resets';
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

function getFullClassName($id) {
    $c = [
        0=>'Dark Wizard', 1=>'Soul Master', 2=>'Grand Master', 3=>'Soul Wizard',
        16=>'Dark Knight', 17=>'Blade Knight', 18=>'Blade Master', 19=>'Dragon Knight',
        32=>'Fairy Elf', 33=>'Muse Elf', 34=>'High Elf', 35=>'Noble Elf',
        48=>'Magic Gladiator', 49=>'Duel Master', 50=>'Magic Knight',
        64=>'Dark Lord', 65=>'Lord Emperor', 66=>'Empire Lord',
        80=>'Summoner', 81=>'Bloody Summoner', 82=>'Dimension Master', 83=>'Dimension Knight',
        96=>'Rage Fighter', 97=>'Fist Master', 98=>'Fist Blazer'
    ];
    return isset($c[$id]) ? $c[$id] : "Guerrero";
}

try {
    $dsn = "dblib:host={$db_settings['host']}:1433;dbname={$db_settings['name']};charset=UTF8";
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $col_nivel = "cLevel"; 
    $col_resets = "ResetCount"; 
    $col_mresets = "MasterResetCount"; // Ajustar si tu Louis usa 'mResetCount'

    $join = "";
    $valCol = "C.$col_resets";
    $orderBy = "C.$col_resets DESC, C.$col_nivel DESC";
    $label = "Resets";

    // LÓGICA DE RANKINGS COMPLETA
    switch($type) {
        case 'level':
            $orderBy = "C.$col_nivel DESC, C.$col_resets DESC";
            $valCol = "C.$col_nivel";
            $label = "Nivel";
            break;
        case 'pk':
            $orderBy = "C.PkCount DESC";
            $valCol = "C.PkCount";
            $label = "Kills";
            break;
        case 'master':
            $join = "LEFT JOIN MasterSkillTree M ON C.Name = M.Name";
            $orderBy = "ISNULL(M.MasterLevel, 0) DESC, C.$col_nivel DESC";
            $valCol = "ISNULL(M.MasterLevel, 0)";
            $label = "M-Level";
            break;
        case 'mresets':
            $orderBy = "C.$col_mresets DESC, C.$col_resets DESC";
            $valCol = "C.$col_mresets";
            $label = "M-Resets";
            break;
        case 'gens':
            $join = "LEFT JOIN IGC_Gens G ON C.Name = G.Name";
            $orderBy = "ISNULL(G.Contribution, 0) DESC";
            $valCol = "ISNULL(G.Contribution, 0)";
            $label = "Contrib.";
            break;
        case 'bc':
            $join = "LEFT JOIN RankingBloodCastle E ON C.Name = E.Name";
            $orderBy = "ISNULL(E.Score, 0) DESC";
            $valCol = "ISNULL(E.Score, 0)";
            $label = "BC Score";
            break;
        case 'ds':
            $join = "LEFT JOIN RankingDevilSquare E ON C.Name = E.Name";
            $orderBy = "ISNULL(E.Score, 0) DESC";
            $valCol = "ISNULL(E.Score, 0)";
            $label = "DS Score";
            break;
        case 'cc':
            $join = "LEFT JOIN RankingChaosCastle E ON C.Name = E.Name";
            $orderBy = "ISNULL(E.Score, 0) DESC";
            $valCol = "ISNULL(E.Score, 0)";
            $label = "CC Score";
            break;
        case 'it':
            $join = "LEFT JOIN RankingIllusionTemple E ON C.Name = E.Name";
            $orderBy = "ISNULL(E.Score, 0) DESC";
            $valCol = "ISNULL(E.Score, 0)";
            $label = "IT Score";
            break;
        case 'duels':
            $join = "LEFT JOIN RankingDuel E ON C.Name = E.Name";
            $orderBy = "ISNULL(E.WinScore, 0) DESC";
            $valCol = "ISNULL(E.WinScore, 0)";
            $label = "Duel Wins";
            break;
    }

    $totalRows = $pdo->query("SELECT COUNT(*) FROM Character")->fetchColumn();
    header("X-Total-Pages: " . ceil($totalRows / $limit));

    $sql = "SELECT C.Name, C.Class, C.AccountID, C.$col_nivel as Nivel, C.$col_resets as Resets, 
                   $valCol as StatVal, ISNULL(S.ConnectStat, 0) as ConnectStat
            FROM Character C
            LEFT JOIN MEMB_STAT S ON C.AccountID = S.memb___id
            $join
            ORDER BY $orderBy OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY";

    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$results) { echo '<div class="text-white p-10 text-center uppercase font-bold">Sin registros</div>'; exit; }
?>

<style>
    /* RESTAURACIÓN DE TUS ESTILOS DE TOP 3 */
    @keyframes lightningSweep { 0% { left: -100%; opacity: 0; } 20% { opacity: 1; } 40% { left: 100%; opacity: 0; } 100% { left: 100%; opacity: 0; } }
    .rank-top1::after { content: ''; position: absolute; top: 0; width: 150px; height: 100%; background: linear-gradient(to right, transparent, rgba(255,215,0,0.4), transparent); transform: skewX(-25deg); animation: lightningSweep 3s infinite linear; }
    @keyframes silverGlow { 0% { box-shadow: 0 0 5px rgba(255,255,255,0.1), inset 0 0 5px rgba(255,255,255,0.1); } 50% { box-shadow: 0 0 20px rgba(255,255,255,0.3), inset 0 0 15px rgba(255,255,255,0.2); } 100% { box-shadow: 0 0 5px rgba(255,255,255,0.1), inset 0 0 5px rgba(255,255,255,0.1); } }
    .rank-top2 { animation: silverGlow 2s infinite ease-in-out; }
    @keyframes bronzeFire { 0% { border-color: rgba(154,52,18,0.3); } 50% { border-color: rgba(255,69,0,0.8); } 100% { border-color: rgba(154,52,18,0.3); } }
    .rank-top3 { animation: bronzeFire 1.5s infinite alternate; }
    .top-legendary { overflow: hidden; position: relative; }
</style>

<?php
    $pos = $offset + 1;
    $delay = 0.05;
    foreach($results as $row) {
        $animClass = "";
        $rankColor = "text-gray-600";
        $avatarBorder = "border-white/10";

        if ($page == 1) {
            if ($pos == 1) {
                $animClass = "rank-top1 top-legendary border-yellow-500 bg-yellow-500/10";
                $rankColor = "text-yellow-500 font-black scale-150";
                $avatarBorder = "border-yellow-400 shadow-[0_0_15px_#eab308]";
            } elseif ($pos == 2) {
                $animClass = "rank-top2 top-legendary border-slate-300 bg-slate-500/10";
                $rankColor = "text-slate-300 font-black scale-125";
                $avatarBorder = "border-slate-300 shadow-[0_0_10px_#cbd5e1]";
            } elseif ($pos == 3) {
                $animClass = "rank-top3 top-legendary border-orange-700 bg-orange-900/10";
                $rankColor = "text-orange-600 font-black";
                $avatarBorder = "border-orange-600";
            }
        }

        $dotStatus = $row['ConnectStat'] == 1 ? "bg-green-500 shadow-[0_0_12px_#22c55e]" : ($row['ConnectStat'] == 2 ? "bg-orange-500 shadow-[0_0_12px_#f97316]" : "bg-gray-600");
        ?>
        <div class="rank-row flex items-center justify-between p-4 rounded-2xl border <?php echo $animClass ? $animClass : 'border-white/5 bg-black/20'; ?> glass group transition-all"
             style="animation: slideIn 0.4s ease forwards; animation-delay: <?php echo $delay; ?>s;">
            
            <div class="flex items-center gap-5 z-10">
                <div class="w-8 text-center <?php echo $rankColor; ?>">#<?php echo $pos; ?></div>

                <div class="relative">
                    <img src="assets/avatars/<?php echo $row['AccountID']; ?>.jpg" 
                         onerror="this.src='https://ui-avatars.com/api/?name=<?php echo $row['Name']; ?>&background=111&color=f97316'" 
                         class="w-12 h-12 rounded-full border-2 <?php echo $avatarBorder; ?> object-cover transition-transform group-hover:rotate-6">
                    <div class="absolute -bottom-1 -right-1 flex h-4 w-4">
                        <?php if($row['ConnectStat'] == 1): ?>
                            <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                        <?php endif; ?>
                        <span class="relative inline-flex rounded-full h-4 w-4 <?php echo $dotStatus; ?> border-2 border-black"></span>
                    </div>
                </div>

                <div>
                    <div class="flex items-center">
                        <h4 class="text-sm font-black text-white uppercase tracking-tight"><?php echo $row['Name']; ?></h4>
                        <?php if($row['ConnectStat'] == 2): ?>
                            <span class="text-[7px] bg-orange-600 text-white px-1.5 py-0.5 rounded font-black uppercase ml-2">AFK</span>
                        <?php endif; ?>
                    </div>
                    <div class="flex flex-col">
                        <span class="text-[10px] text-orange-500 font-bold uppercase"><?php echo getFullClassName($row['Class']); ?></span>
                        <span class="text-[9px] text-gray-400 italic">Nivel <?php echo $row['Nivel']; ?> | Resets <?php echo $row['Resets']; ?></span>
                    </div>
                </div>
            </div>

            <div class="text-right z-10">
                <span class="block text-xl font-black text-white italic tracking-tighter leading-none"><?php echo number_format($row['StatVal']); ?></span>
                <span class="text-[8px] text-gray-500 uppercase font-black tracking-widest"><?php echo $label; ?></span>
            </div>
        </div>
        <?php
        $pos++; $delay += 0.05;
    }
} catch (Exception $e) { 
    echo '<div class="bg-red-900/20 p-4 rounded-xl text-red-500 text-[10px] uppercase font-bold border border-red-500/20">Error en tabla: '.$type.'</div>'; 
}