<?php
// ==========================================================
// ARQUIVO: create_character.php
// ATUALIZADO: Sincronizado com register.php (Level 15, Outfit 716, Status)
// ==========================================================

ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require 'includes/conexao.php';

// --- 1. CONFIG & AUTH ---
if (!isset($_SESSION['account_id'])) {
    header("Location: login.php");
    exit;
}

function getSiteConfig($pdo) {
    try {
        $stmt = $pdo->query("SELECT server_name FROM site_config WHERE id = 1");
        $config = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($config) return $config;
    } catch (Exception $e) {}
    return ['server_name' => 'PokeDash'];
}
$config = getSiteConfig($pdo);
$page_title = "Criar Personagem - " . $config['server_name'];
$account_id = $_SESSION['account_id'];
$msg = '';

// --- 2. LÓGICA DE CRIAÇÃO ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $char_name = trim($_POST['char_name']);
    $sex = (int)$_POST['sex']; // 1 = Male, 0 = Female
    
    // Validações
    if (empty($char_name)) {
        $msg = showAlert('warning', 'Digite o nome do seu treinador.');
    } elseif (!preg_match("/^[a-zA-Z ]+$/", $char_name)) {
        $msg = showAlert('warning', 'O nome deve conter apenas letras e espaços.');
    } elseif (strlen($char_name) < 3 || strlen($char_name) > 20) {
        $msg = showAlert('warning', 'O nome deve ter entre 3 e 20 caracteres.');
    } else {
        // Verifica duplicidade
        $check = $pdo->prepare("SELECT id FROM players WHERE name = ?");
        $check->execute([$char_name]);
        
        if ($check->rowCount() > 0) {
            $msg = showAlert('danger', 'Este nome já está em uso.');
        } else {
            // --- CONFIGURAÇÃO SINCRONIZADA COM O REGISTER ---
            
            // Outfit Fixa 716 (Conforme solicitado para igualar ao registro)
            // Se quiser diferenciar sexo futuramente: ($sex === 1 ? 716 : 717)
            $lookType = 716; 
            
            // Dados de Level 15
            $startLevel = 15;
            $startExp   = 36400;
            $startHealth = 640;
            $startCap   = 470;

            // Posição Inicial
            $townId = 1;
            $posX   = 1039; // Igualado ao register (era 1038)
            $posY   = 1011;
            $posZ   = 7;

            try {
                // QUERY UPDATE: Agora insere com Level 15 e status corretos
                $sql = "INSERT INTO players (
                    name, account_id, group_id, sex, vocation, level, 
                    health, healthmax, mana, manamax, experience, 
                    lookbody, lookfeet, lookhead, looklegs, looktype, 
                    town_id, posx, posy, posz, 
                    cap, conditions, balance, stamina, 
                    save, online, skull, skulltime
                ) VALUES (
                    ?, ?, 1, ?, 1, ?, 
                    ?, ?, 0, 0, ?, 
                    68, 76, 78, 58, ?, 
                    ?, ?, ?, ?, 
                    ?, '', 0, 151200000, 
                    1, 0, 0, 0
                )";
                
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    $char_name, 
                    $account_id, 
                    $sex, 
                    $startLevel,  // Level 15
                    $startHealth, // HP 640
                    $startHealth, // HP Max 640
                    $startExp,    // Exp 36400
                    $lookType,    // Outfit 716
                    $townId, $posX, $posY, $posZ,
                    $startCap     // Cap 470
                ]);
                
                // Sucesso
                header("Location: account.php");
                exit;

            } catch (Exception $e) {
                // Se der erro, mostra na tela
                $msg = showAlert('danger', 'Erro SQL: ' . $e->getMessage());
            }
        }
    }
}

function showAlert($type, $text) {
    $color = ($type == 'danger') ? '#ef4444' : '#f59e0b';
    return '<div class="alert shadow-lg border-0 text-white fw-bold mb-4" style="background: '.$color.'; border-radius: 12px;">
                <i class="fas fa-exclamation-circle me-2"></i> '.$text.'
            </div>';
}

include 'includes/header.php';
?>

<link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
<script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>

<style>
    :root {
        --bg-deep: #020617;
        --glass: rgba(30, 41, 59, 0.7);
        --glass-border: rgba(255, 255, 255, 0.1);
        --neon-blue: #3b82f6;
        --text-bright: #ffffff;
        --text-soft: rgba(255, 255, 255, 0.8);
    }

    body {
        background-color: var(--bg-deep);
        background-image: radial-gradient(circle at 50% 10%, #1e1b4b 0%, var(--bg-deep) 60%);
        color: var(--text-bright);
        font-family: 'Segoe UI', sans-serif;
    }

    .main-container {
        min-height: 80vh;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 40px 15px;
    }

    .creation-card {
        background: var(--glass);
        backdrop-filter: blur(12px);
        -webkit-backdrop-filter: blur(12px);
        border: 1px solid var(--glass-border);
        border-radius: 20px;
        padding: 40px;
        width: 100%;
        max-width: 600px;
        box-shadow: 0 0 40px rgba(0,0,0,0.5);
        position: relative;
        overflow: hidden;
    }
    
    .creation-card::before {
        content: ''; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%;
        background: radial-gradient(circle, rgba(59, 130, 246, 0.1) 0%, transparent 60%);
        pointer-events: none;
    }

    .page-title {
        font-family: 'Rajdhani', sans-serif;
        font-size: 2.5rem;
        font-weight: 800;
        text-transform: uppercase;
        background: linear-gradient(to right, #fff, #93c5fd);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        margin-bottom: 10px;
        text-align: center;
    }

    .form-label {
        color: var(--text-bright);
        font-weight: 600;
        letter-spacing: 0.5px;
        margin-bottom: 8px;
    }

    .custom-input {
        background: rgba(0,0,0,0.3);
        border: 1px solid var(--glass-border);
        color: white;
        padding: 15px;
        border-radius: 10px;
        font-size: 1.1rem;
        transition: 0.3s;
    }
    .custom-input:focus {
        background: rgba(0,0,0,0.5);
        border-color: var(--neon-blue);
        box-shadow: 0 0 15px rgba(59, 130, 246, 0.3);
        color: white;
    }

    /* SELETOR DE SEXO VISUAL */
    .sex-selector-container { display: flex; gap: 15px; }
    .sex-option { flex: 1; position: relative; }
    .sex-radio { position: absolute; opacity: 0; width: 100%; height: 100%; cursor: pointer; z-index: 2; }
    .sex-card {
        background: rgba(255,255,255,0.05);
        border: 1px solid var(--glass-border);
        border-radius: 12px;
        padding: 20px;
        text-align: center;
        transition: 0.3s;
        cursor: pointer;
    }
    .sex-radio:checked + .sex-card {
        background: rgba(59, 130, 246, 0.2);
        border-color: var(--neon-blue);
        box-shadow: 0 0 20px rgba(59, 130, 246, 0.3);
        transform: translateY(-5px);
    }
    .sex-radio:hover + .sex-card { background: rgba(255,255,255,0.1); }
    .sex-icon { font-size: 2.5rem; margin-bottom: 10px; display: block; }
    .male-icon { color: #60a5fa; }
    .female-icon { color: #f472b6; }
    .sex-label { color: white; font-weight: bold; text-transform: uppercase; }

    .info-box {
        background: rgba(255,255,255,0.05);
        border-left: 4px solid var(--neon-blue);
        padding: 15px;
        border-radius: 0 8px 8px 0;
        margin-bottom: 25px;
        color: var(--text-soft);
        font-size: 0.9rem;
    }

    .btn-create {
        background: linear-gradient(45deg, var(--neon-blue), #2563eb);
        border: none;
        color: white;
        font-weight: 800;
        text-transform: uppercase;
        padding: 18px;
        border-radius: 12px;
        width: 100%;
        letter-spacing: 1px;
        font-size: 1.1rem;
        transition: 0.3s;
        box-shadow: 0 10px 30px rgba(59, 130, 246, 0.4);
    }
    .btn-create:hover {
        transform: translateY(-3px);
        box-shadow: 0 15px 40px rgba(59, 130, 246, 0.6);
        filter: brightness(1.1);
    }
    
    .btn-back {
        text-decoration: none;
        color: var(--text-soft);
        display: block;
        text-align: center;
        margin-top: 20px;
        font-weight: 600;
        transition: 0.3s;
    }
    .btn-back:hover { color: white; }
</style>

<div class="main-container">
    <div class="creation-card" data-aos="zoom-in">
        
        <h1 class="page-title">Novo Personagem</h1>
        <p class="text-center text-soft mb-4">Escolha o nome e o gênero do seu novo treinador.</p>

        <?php echo $msg; ?>

        <form action="" method="POST">
            
            <div class="mb-4">
                <label for="char_name" class="form-label">Nome do Treinador</label>
                <input type="text" class="form-control custom-input" id="char_name" name="char_name" placeholder="Ex: Ash Ketchum" required autofocus>
                <div class="form-text text-white-50">Use apenas letras e espaços.</div>
            </div>

            <div class="mb-4">
                <label class="form-label mb-3">Gênero do Personagem</label>
                <div class="sex-selector-container">
                    <div class="sex-option">
                        <input type="radio" name="sex" id="male" value="1" class="sex-radio" checked>
                        <div class="sex-card">
                            <i class="fas fa-mars sex-icon male-icon"></i>
                            <span class="sex-label">Masculino</span>
                        </div>
                    </div>
                    <div class="sex-option">
                        <input type="radio" name="sex" id="female" value="0" class="sex-radio">
                        <div class="sex-card">
                            <i class="fas fa-venus sex-icon female-icon"></i>
                            <span class="sex-label">Feminino</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="info-box">
                <div class="d-flex justify-content-between mb-2">
                    <span class="fw-bold text-white">Cidade Inicial:</span>
                    <span>Vermilion City</span>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span class="fw-bold text-white">Level Inicial:</span>
                    <span class="text-warning fw-bold">15 (Bônus)</span>
                </div>
                <div class="d-flex justify-content-between">
                    <span class="fw-bold text-white">Classe:</span>
                    <span>Treinador Iniciante</span>
                </div>
            </div>

            <button type="submit" class="btn-create">
                <i class="fas fa-plus-circle me-2"></i> Criar Personagem
            </button>

            <a href="account.php" class="btn-back">
                <i class="fas fa-arrow-left me-2"></i> Voltar para o Painel
            </a>

        </form>
    </div>
</div>

<script>
    AOS.init();
</script>

<?php include 'includes/footer.php'; ?>