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

// --- INTEGRACIÓN DE CONFIGURACIÓN DE MONEDA ---
$coin_config_file = __DIR__ . '/config/coin_settings.php';
if (file_exists($coin_config_file)) {
    include($coin_config_file); 
} else {
    $coin_config = [
        'coin_name' => 'Creditos',
        'coin_table' => 'CashShopData',
        'coin_column' => 'WCoinC',
        'coin_id_column' => 'AccountID'
    ];
}

if (!isset($_SESSION['logged_in'])) {
    echo json_encode(['success' => false, 'message' => 'Sesion expirada']);
    exit;
}

$action = $_POST['action'] ?? '';

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);

    if ($action === 'buy') {
        $market_id = intval($_POST['market_id'] ?? 0);
        $buyerId = $_SESSION['user_id'];

        if ($market_id <= 0) {
            echo json_encode(['success' => false, 'message' => 'ID de mercado no válido']);
            exit;
        }

        $pdo->beginTransaction();

        $stmtM = $pdo->prepare("SELECT * FROM Web_Market_Chars WHERE id = ?");
        $stmtM->execute([$market_id]);
        $marketItem = $stmtM->fetch(PDO::FETCH_ASSOC);

        if (!$marketItem) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'El personaje ya no está disponible']);
            exit;
        }

        $price = (int)$marketItem['price'];
        $sellerId = $marketItem['seller_id'];
        $charName = $marketItem['char_name'];

        if (strtolower($sellerId) === strtolower($buyerId)) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'No puedes comprar tu propio personaje']);
            exit;
        }

        $cTable = $coin_config['coin_table'];
        $cCol   = $coin_config['coin_column'];
        $cIdCol = $coin_config['coin_id_column'];

        $stCoin = $pdo->prepare("SELECT $cCol FROM $cTable WHERE $cIdCol = ?");
        $stCoin->execute([$buyerId]);
        $buyerBalance = $stCoin->fetchColumn();

        if ($buyerBalance === false) {
            $buyerBalance = 0;
            $pdo->prepare("IF NOT EXISTS (SELECT 1 FROM $cTable WHERE $cIdCol = ?) INSERT INTO $cTable ($cIdCol, $cCol, WCoinP, GobPoint) VALUES (?, 0, 0, 0)")->execute([$buyerId, $buyerId]);
        }

        if ((int)$buyerBalance < $price) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Saldo insuficiente']);
            exit;
        }

        $pdo->prepare("UPDATE $cTable SET $cCol = $cCol - ? WHERE $cIdCol = ?")->execute([$price, $buyerId]);
        $pdo->prepare("UPDATE $cTable SET $cCol = $cCol + ? WHERE $cIdCol = ?")->execute([$price, $sellerId]);

        // RESTAURACIÓN CORREGIDA: Prefijo 0x y CONVERT
        $hexInv = '0x' . bin2hex($marketItem['inventory']);
        $hexMag = '0x' . bin2hex($marketItem['magic_list']);

        $sqlInsertChar = "INSERT INTO Character 
            (AccountID, Name, cLevel, LevelUpPoint, Class, Experience, Strength, Dexterity, Vitality, Energy, Inventory, MagicList, Money, Life, MaxLife, Mana, MaxMana, MapNumber, MapPosX, MapPosY, PkCount, PkLevel, PkTime, ResetCount, Leadership) 
            VALUES (?, ?, ?, 0, ?, 0, ?, ?, ?, ?, CONVERT(VARBINARY(MAX), ?, 1), CONVERT(VARBINARY(MAX), ?, 1), 0, 100, 100, 100, 100, 0, 125, 125, 0, 3, 0, ?, ?)";
        
        $stmtRestore = $pdo->prepare($sqlInsertChar);
        $stmtRestore->execute([
            $buyerId, 
            $charName, 
            (int)$marketItem['char_level'], 
            (int)$marketItem['char_class'],
            (int)$marketItem['char_str'], 
            (int)$marketItem['char_agi'], 
            (int)$marketItem['char_vit'], 
            (int)$marketItem['char_ene'], 
            $hexInv, 
            $hexMag, 
            (int)$marketItem['char_resets'], 
            0
        ]);

        $stAcc = $pdo->prepare("SELECT * FROM AccountCharacter WHERE Id = ?");
        $stAcc->execute([$buyerId]);
        $accChars = $stAcc->fetch(PDO::FETCH_ASSOC);

        $assigned = false;
        for ($i = 1; $i <= 5; $i++) {
            if (empty(trim($accChars["GameID$i"]))) {
                $pdo->prepare("UPDATE AccountCharacter SET GameID$i = ? WHERE Id = ?")->execute([$charName, $buyerId]);
                $assigned = true;
                break;
            }
        }

        if (!$assigned) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'No hay espacio en la cuenta']);
            exit;
        }

        $pdo->prepare("DELETE FROM Web_Market_Chars WHERE id = ?")->execute([$market_id]);
        $pdo->commit();
        echo json_encode(['success' => true]);

    } elseif ($action === 'sell') {
        $charName = trim($_POST['char'] ?? '');
        $price = intval($_POST['price'] ?? 0);
        $str = intval($_POST['char_str'] ?? $_POST['str'] ?? 0); 
        $agi = intval($_POST['char_agi'] ?? $_POST['agi'] ?? 0);
        $vit = intval($_POST['char_vit'] ?? $_POST['vit'] ?? 0);
        $ene = intval($_POST['char_ene'] ?? $_POST['ene'] ?? 0);

        if (empty($charName) || $price <= 0) {
            echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
            exit;
        }

        $pdo->beginTransaction();

        $stmt = $pdo->prepare("SELECT Name, Class, cLevel, ResetCount, Inventory, MagicList FROM Character WHERE Name = ? AND AccountID = ?");
        $stmt->execute([$charName, $_SESSION['user_id']]);
        $charData = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$charData) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Personaje no encontrado']);
            exit;
        }

        // VENTA CORREGIDA: Prefijo 0x y CONVERT para evitar error 20018
        $hexInvSell = '0x' . bin2hex($charData['Inventory']);
        $hexMagSell = '0x' . bin2hex($charData['MagicList']);

        $sql = "INSERT INTO Web_Market_Chars 
                (char_name, seller_id, price, char_class, char_level, char_resets, char_str, char_agi, char_vit, char_ene, inventory, magic_list, date_listed) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CONVERT(VARBINARY(MAX), ?, 1), CONVERT(VARBINARY(MAX), ?, 1), GETDATE())";
        
        $stmtSell = $pdo->prepare($sql);
        $stmtSell->execute([
            trim($charData['Name']),
            $_SESSION['user_id'],
            $price,
            (int)$charData['Class'],
            (int)$charData['cLevel'],
            (int)$charData['ResetCount'],
            $str,
            $agi,
            $vit,
            $ene,
            $hexInvSell,
            $hexMagSell
        ]);

        $realCharName = $charData['Name'];
        for ($i = 1; $i <= 5; $i++) {
            $pdo->prepare("UPDATE AccountCharacter SET GameID$i=NULL WHERE Id=? AND GameID$i=?")->execute([$_SESSION['user_id'], $realCharName]);
        }

        $pdo->prepare("DELETE FROM Character WHERE Name = ? AND AccountID = ?")->execute([$realCharName, $_SESSION['user_id']]);
        $pdo->prepare("DELETE FROM OptionData WHERE Name = ?")->execute([$realCharName]);
        $pdo->prepare("DELETE FROM T_CGuid WHERE Name = ?")->execute([$realCharName]);

        $pdo->commit();
        echo json_encode(['success' => true]);
    }

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}