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

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

$data = json_decode(file_get_contents('php://input'), true);
$charName = $data['char'];
$action = $data['action'];

try {
    $dsn = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') 
           ? "sqlsrv:Server={$db_settings['host']};Database={$db_settings['name']}" 
           : "dblib:host={$db_settings['host']};dbname={$db_settings['name']}";
    
    $pdo = new PDO($dsn, $db_settings['user'], $db_settings['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Verificar dueño
    $stmt = $pdo->prepare("SELECT cLevel, ResetCount FROM Character WHERE Name = ? AND AccountID = ?");
    $stmt->execute([$charName, $_SESSION['user_id']]);
    $char = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$char) throw new Exception("Personaje no válido.");

    if ($action === 'reset') {
        if ($char['cLevel'] < 400) throw new Exception("Nivel 400 necesario.");
        
        $newResets = $char['ResetCount'] + 1;
        $upd = $pdo->prepare("UPDATE Character SET cLevel=1, Experience=0, ResetCount=? WHERE Name=?");
        $upd->execute([$newResets, $charName]);
        echo json_encode(['success'=>true, 'message'=>"Reset realizado a $charName"]);

    } elseif ($action === 'mreset') {
        if ($char['ResetCount'] < 100) throw new Exception("Necesitas 100 resets.");
        
        $upd = $pdo->prepare("UPDATE Character SET cLevel=1, Experience=0, ResetCount=0 WHERE Name=?");
        $upd->execute([$charName]);
        
        // Opcional: Borrar Master Level si existe tabla aparte
        $pdo->prepare("DELETE FROM MasterSkillTree WHERE Name=?")->execute([$charName]);
        
        echo json_encode(['success'=>true, 'message'=>"Master Reset realizado a $charName"]);
    }
} catch (Exception $e) {
    echo json_encode(['success'=>false, 'message'=>$e->getMessage()]);
}