<?php
header('Content-Type: application/json');
require_once(__DIR__ . '/config/settings.php');

error_reporting(0); 

try {
    $host = $db_settings['host'];
    $dbname = $db_settings['name'];
    $user = $db_settings['user'];
    $pass = $db_settings['pass'];

    $dsn = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') 
        ? "sqlsrv:Server=$host;Database=$dbname" 
        : "dblib:host=$host;dbname=$dbname";

    $pdo = new PDO($dsn, $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // --- LIBRERÍA COMPLETA DE OPCIONES SOCKET (TODOS LOS NIVELES) ---
    $socketMap = [
        // FUEGO (Fire)
        0  => ["W" => "Fire: Attack Speed +7",           "A" => "Fire: Monster Die HP Recovery +125"],
        1  => ["W" => "Fire: Attack Success Rate +25",   "A" => "Fire: Monster Die Mana Recovery +125"],
        2  => ["W" => "Fire: Max Damage/Wizardry +30",   "A" => "Fire: AG Consumption Reduction 40%"],
        3  => ["W" => "Fire: Min Damage/Wizardry +20",   "A" => "Fire: Defensive Skill +10%"],
        4  => ["W" => "Fire: Damage/Wizardry +20",       "A" => "Fire: Attack Speed +7"],
        5  => ["W" => "Fire: AG Consumption Reduction 40%", "A" => "Fire: No Effect"],
        // Nivel 2 al 5 de Fuego (+50, +100, +150, +200)
        50 => ["W" => "Fire: Attack Speed +8", "A" => "Fire: Monster Die HP Recovery +130"],
        100 => ["W" => "Fire: Attack Speed +9", "A" => "Fire: Monster Die HP Recovery +135"],
        150 => ["W" => "Fire: Attack Speed +10", "A" => "Fire: Monster Die HP Recovery +140"],
        200 => ["W" => "Fire: Attack Speed +11", "A" => "Fire: Monster Die HP Recovery +150"],
        
        // AGUA (Water)
        10 => ["W" => "Water: Defense Success Rate +10%", "A" => "Water: Defense Success Rate +10%"],
        11 => ["W" => "Water: Defense +30",              "A" => "Water: Defense +30"],
        12 => ["W" => "Water: Shield Block +7%",         "A" => "Water: Shield Block +7%"],
        13 => ["W" => "Water: Damage Reduction +4%",     "A" => "Water: Damage Reduction +4%"],
        14 => ["W" => "Water: Damage Reflection +5%",    "A" => "Water: Damage Reflection +5%"],
        // Nivel 2 al 5 de Agua (+50, +100, +150, +200)
        60 => ["W" => "Water: Def Success Rate +11%", "A" => "Water: Def Success Rate +11%"],
        63 => ["W" => "Water: Damage Reduction +5%", "A" => "Water: Damage Reduction +5%"],
        113 => ["W" => "Water: Damage Reduction +6%", "A" => "Water: Damage Reduction +6%"],
        163 => ["W" => "Water: Damage Reduction +7%", "A" => "Water: Damage Reduction +7%"],
        213 => ["W" => "Water: Damage Reduction +8%", "A" => "Water: Damage Reduction +8%"],
        
        // HIELO (Ice)
        16 => ["W" => "Ice: Monster Die HP Recovery +125",   "A" => "Ice: Monster Die HP Recovery +125"],
        17 => ["W" => "Ice: Monster Die Mana Recovery +125", "A" => "Ice: Monster Die Mana Recovery +125"],
        18 => ["W" => "Ice: Skill Damage +15",               "A" => "Ice: Skill Damage +15"],
        19 => ["W" => "Ice: Attack Success Rate +25",        "A" => "Ice: Attack Success Rate +25"],
        20 => ["W" => "Ice: Item Durability +30%",           "A" => "Ice: Item Durability +30%"],
        
        // VIENTO (Wind)
        21 => ["W" => "Wind: Automatic HP Recovery +8",  "A" => "Wind: Automatic HP Recovery +8"],
        22 => ["W" => "Wind: Max HP Increase +4%",       "A" => "Wind: Max HP Increase +4%"],
        23 => ["W" => "Wind: Max Mana Increase +4%",     "A" => "Wind: Max Mana Increase +4%"],
        24 => ["W" => "Wind: Automatic Mana Recovery +7", "A" => "Wind: Automatic Mana Recovery +7"],
        25 => ["W" => "Wind: Max AG Increase +25",       "A" => "Wind: Max AG Increase +25"],
        // Nivel 5 de Viento (Ejemplo Max HP +8%)
        222 => ["W" => "Wind: Max HP Increase +8%", "A" => "Wind: Max HP Increase +8%"],
        
        // RAYO (Lightning)
        29 => ["W" => "Lightning: Excellent Damage +15",      "A" => "Lightning: Reflect Damage +5%"],
        30 => ["W" => "Lightning: Excellent Damage Rate +10%", "A" => "Lightning: Defense Success Rate +10%"],
        31 => ["W" => "Lightning: Critical Damage +30",       "A" => "Lightning: Defense +30"],
        32 => ["W" => "Lightning: Critical Damage Rate +8%",  "A" => "Lightning: No Effect"],
        // Nivel 5 de Rayo
        231 => ["W" => "Lightning: Critical Damage +50", "A" => "Lightning: Defense +50"],
        
        // TIERRA (Earth)
        38 => ["W" => "Earth: Stamina Increase +30", "A" => "Earth: Stamina Increase +30"],
        39 => ["W" => "Earth: Strength Increase +30", "A" => "Earth: Strength Increase +30"],
        40 => ["W" => "Earth: Dexterity Increase +30", "A" => "Earth: Dexterity Increase +30"],
        41 => ["W" => "Earth: Energy Increase +30",  "A" => "Earth: Energy Increase +30"],
        // NIVEL 5 (IDs que mencionaste como 210, 212)
        88  => ["W" => "Earth: Stamina +32", "A" => "Earth: Stamina +32"],
        138 => ["W" => "Earth: Stamina +34", "A" => "Earth: Stamina +34"],
        188 => ["W" => "Earth: Stamina +36", "A" => "Earth: Stamina +36"],
        210 => ["W" => "Earth: Stamina +38", "A" => "Earth: Stamina +38"], // Nivel 5 base (38+50*x o ID directo)
        211 => ["W" => "Earth: Strength +38", "A" => "Earth: Strength +38"],
        212 => ["W" => "Earth: Dexterity +38", "A" => "Earth: Dexterity +38"],
        213 => ["W" => "Earth: Energy +38", "A" => "Earth: Energy +38"],

        254 => ["W" => "Empty Socket", "A" => "Empty Socket"],
        255 => ["W" => "No Socket",    "A" => "No Socket"]
    ];

    $sql = "SELECT * FROM Web_Market_Chars ORDER BY id DESC";
    $stmt = $pdo->query($sql);
    $chars = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $response = [];
    $basePath = "assets/items/"; 

    foreach ($chars as $row) {
        $equipped = [];
        $rawInv = $row['inventory'];
        $invHex = "";

        if (is_resource($rawInv)) {
            $invHex = bin2hex(stream_get_contents($rawInv));
        } elseif (!empty($rawInv)) {
            $invHex = (is_string($rawInv) && substr($rawInv, 0, 2) === '0x') ? substr($rawInv, 2) : bin2hex($rawInv);
        }
        
        $invHex = strtoupper($invHex);
        $slotSize = 32; 

        for ($i = 0; $i <= 11; $i++) {
            $start = $i * $slotSize;
            $itemHex = substr($invHex, $start, $slotSize);
            
            if ($itemHex && strlen($itemHex) >= 32 && substr($itemHex, 0, 4) !== 'FFFF') {
                
                $b0  = hexdec(substr($itemHex, 0, 2));   // ID
                $b1  = hexdec(substr($itemHex, 2, 2));   // Lvl, Skill, Luck, Opt
                $b7  = hexdec(substr($itemHex, 14, 2));  // Exc / ID High
                $b8  = hexdec(substr($itemHex, 16, 2));  // Ancient
                $b9  = hexdec(substr($itemHex, 18, 2));  // Category
                
                $sockets = [
                    hexdec(substr($itemHex, 22, 2)), 
                    hexdec(substr($itemHex, 24, 2)), 
                    hexdec(substr($itemHex, 26, 2)), 
                    hexdec(substr($itemHex, 28, 2)), 
                    hexdec(substr($itemHex, 30, 2))  
                ];

                $level = ($b1 >> 3) & 15;
                $skill = ($b1 & 128) ? "Habilidad Especial" : ""; 
                $luck  = ($b1 & 4) ? "Suerte" : ""; 
                $opt   = ($b1 & 3) + (($b7 & 0x40) ? 4 : 0);
                
                $cat = floor($b9 / 16);
                $isAnc  = ($b8 === 5 || $b8 === 6 || $b8 === 9 || $b8 === 10); 
                $isSock = ($sockets[0] < 255);
                
                $optsFinal = [];
                if ($skill) $optsFinal[] = $skill;
                if ($luck)  $optsFinal[] = $luck;
                if ($opt > 0) $optsFinal[] = "Adicional +".($opt * 4);

                // EXCELENTES
                $excVal = ($b7 & 0x3F);
                if ($excVal > 0) {
                    $optsFinal[] = "\n--- OPCIONES EXCELENTES ---";
                    if ($cat <= 5) { // Armas
                        if ($excVal & 1)  $optsFinal[] = "Mana per kill +8";
                        if ($excVal & 2)  $optsFinal[] = "Life per kill +8";
                        if ($excVal & 4)  $optsFinal[] = "Speed +7";
                        if ($excVal & 8)  $optsFinal[] = "Damage +2%";
                        if ($excVal & 16) $optsFinal[] = "Wizardry Damage +2%";
                        if ($excVal & 32) $optsFinal[] = "Exc Damage Rate +10%";
                    } else { // Armaduras
                        if ($excVal & 1)  $optsFinal[] = "Zen Drop +40%";
                        if ($excVal & 2)  $optsFinal[] = "Defense Success Rate +10%";
                        if ($excVal & 4)  $optsFinal[] = "Reflect Damage +5%";
                        if ($excVal & 8)  $optsFinal[] = "Damage Decrease +4%";
                        if ($excVal & 16) $optsFinal[] = "Mana Increase +4%";
                        if ($excVal & 32) $optsFinal[] = "HP Increase +4%";
                    }
                }

                // ANCIENT
                if ($isAnc) {
                    $optsFinal[] = "\n--- OPCIONES ANCIENT ---";
                    $optsFinal[] = "Item de Set Ancient Activo";
                }

                // SOCKETS DINÁMICOS
                if ($isSock) {
                    $optsFinal[] = "\n--- OPCIONES SOCKET ---";
                    $itemType = ($cat <= 5) ? "W" : "A";

                    foreach($sockets as $index => $sByte) {
                        if ($sByte < 255) {
                            if (isset($socketMap[$sByte])) {
                                $desc = $socketMap[$sByte][$itemType];
                            } else {
                                // Fallback para IDs calculados dinámicamente si no están en el mapa manual
                                $baseId = $sByte % 50;
                                if (isset($socketMap[$baseId])) {
                                    $desc = $socketMap[$baseId][$itemType] . " (Lvl ". (floor($sByte/50)+1) .")";
                                } else {
                                    $desc = "Seed Desconocida ($sByte)";
                                }
                            }
                            $optsFinal[] = "Slot ".($index+1).": ".$desc;
                        }
                    }
                }

                $equipped[] = [
                    'slot'   => $i,
                    'lvl'    => $level,
                    'isExe'  => ($excVal > 0),
                    'isAnc'  => $isAnc,
                    'isSock' => $isSock,
                    'opts'   => implode("\n", $optsFinal), 
                    'img'    => $basePath . $cat . "/" . (($b7 & 0x80) ? $b0 + 256 : $b0) . ".gif"
                ];
            }
        }

        $response[] = [
            'id'             => (int)$row['id'],
            'char_name'      => $row['char_name'],
            'price'          => (int)$row['price'], 
            'char_level'     => (int)$row['char_level'],
            'char_resets'    => (int)$row['char_resets'],
            'char_class'     => (int)$row['char_class'],
            // --- AGREGAR ESTO ---
            'char_str'       => (int)$row['char_str'],
            'char_agi'       => (int)$row['char_agi'],
            'char_vit'       => (int)$row['char_vit'],
            'char_ene'       => (int)$row['char_ene'],
            // --- AGREGAR ESTA LÍNEA ---
            'char_cmd'       => (int)($row['char_cmd'] ?? 0), 
            // --------------------------
            'equipment'      => $equipped 
        ];
    }
    echo json_encode($response);
} catch (Exception $e) { echo json_encode([]); }