<?php
// register.php
$page_title = "Criar Conta";

// Inclui conexão e header
require_once 'includes/conexao.php';
include 'includes/header.php';

// Se já estiver logado, redireciona para o painel
if (isset($_SESSION['account_id'])) {
    header("Location: account.php");
    exit;
}

$msg = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitização básica
    $name     = trim($_POST['name']);
    $email    = trim($_POST['email']);
    $pass     = trim($_POST['password']);
    $repass   = trim($_POST['repassword']);
    $charName = trim($_POST['char_name']);
    $sex      = (int)$_POST['sex'];

    // Validações
    if (empty($name) || empty($pass) || empty($charName) || empty($email)) {
        $msg = showAlert('warning', 'Preencha todos os campos obrigatórios.');
    } elseif ($pass !== $repass) {
        $msg = showAlert('danger', 'As senhas não coincidem.');
    } elseif (strlen($name) < 6 || strlen($pass) < 6) {
        $msg = showAlert('warning', 'A conta e a senha devem ter no mínimo 6 caracteres.');
    } elseif (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
        $msg = showAlert('warning', 'O nome da conta deve conter apenas letras e números.');
    } elseif (!preg_match("/^[a-zA-Z ]+$/", $charName)) {
        $msg = showAlert('warning', 'O nome do personagem deve conter apenas letras e espaços.');
    } else {
        
        // Verifica duplicidade no Banco
        try {
            $chk = $pdo->prepare("SELECT id FROM accounts WHERE name = ?");
            $chk->execute([$name]);
            
            $chkEmail = $pdo->prepare("SELECT id FROM accounts WHERE email = ?");
            $chkEmail->execute([$email]);

            $chkChar = $pdo->prepare("SELECT id FROM players WHERE name = ?");
            $chkChar->execute([$charName]);

            if ($chk->rowCount() > 0) {
                $msg = showAlert('danger', 'Este nome de conta já está em uso.');
            } elseif ($chkEmail->rowCount() > 0) {
                $msg = showAlert('danger', 'Este e-mail já está cadastrado.');
            } elseif ($chkChar->rowCount() > 0) {
                $msg = showAlert('danger', 'Este nome de personagem já existe.');
            } else {
                
                // --- INÍCIO DA CRIAÇÃO ---
                $pdo->beginTransaction();

                // 1. Criar Conta
                $passHash = sha1($pass); 
                
                $stmtAcc = $pdo->prepare("INSERT INTO accounts (name, password, email, creation) VALUES (?, ?, ?, ?)");
                $stmtAcc->execute([$name, $passHash, $email, time()]);
                $accId = $pdo->lastInsertId();

                // 2. Criar Personagem (Player)
                
                // --- CONFIGURAÇÃO DE OUTFIT (716) ---
                // Se for masculino usa 716. 
                // Se for feminino, coloquei 716 também conforme seu pedido (ou altere para o ID feminino correspondente se houver)
                $looktype = 716; 
                
                // XP aproximada para level 15 (evita bug de level negativo/reset)
                $startExp = 36400; 

                $sqlPlayer = "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
                ) VALUES (
                    ?, ?, 1, ?, 1, 15, 
                    640, 640, 0, 0, ?,
                    68, 76, 78, 58, ?, 
                    1, 1039, 1011, 7, 
                    470, '', 0, 151200000
                )";
                
                $stmtPlayer = $pdo->prepare($sqlPlayer);
                // Ordem: Name, AccID, Sex, Exp, Looktype
                $stmtPlayer->execute([$charName, $accId, $sex, $startExp, $looktype]);

                $pdo->commit();
                
                $msg = '<div class="alert alert-custom-success shadow border-0 p-4 rounded-3 text-center">
                            <h2 class="alert-heading fw-bold mb-3"><i class="fas fa-check-circle"></i> Conta Criada!</h2>
                            <p class="fs-5">Bem-vindo(a) <strong>'.$name.'</strong>. Você começará com a Outfit Especial!</p>
                            <hr>
                            <a href="login.php" class="btn btn-primary fw-bold px-5 py-3 rounded-pill shadow-sm">
                                <i class="fas fa-sign-in-alt me-2"></i> FAZER LOGIN
                            </a>
                        </div>';
                
                unset($_POST);
            }
        } catch (Exception $e) {
            if($pdo->inTransaction()){
                $pdo->rollBack();
            }
            $msg = showAlert('danger', 'Erro técnico ao criar conta: ' . $e->getMessage());
        }
    }
}

// Função auxiliar para alertas
function showAlert($type, $text) {
    $icon = ($type == 'danger') ? 'exclamation-triangle' : 'info-circle';
    return '<div class="alert alert-'.$type.' d-flex align-items-center shadow-sm border-0" role="alert">
                <i class="fas fa-'.$icon.' me-3 fs-4"></i>
                <div>'.$text.'</div>
            </div>';
}
?>

<style>
    /* --- DESIGN AZUL & DARK BLUE --- */
    :root {
        --blue-primary: #0066cc;    /* Azul Vibrante */
        --blue-secondary: #004080;  /* Azul Profundo */
        --blue-gradient-start: #003366;
        --blue-gradient-end: #0059b3;
    }

    body {
        background: url('images/bg-blue-pattern.png') repeat, linear-gradient(135deg, #e6f2ff 0%, #cce0ff 100%);
        font-family: 'Poppins', sans-serif;
    }

    .register-container {
        max-width: 900px;
        margin: 0 auto;
    }

    .register-card {
        border: none;
        border-radius: 20px;
        overflow: hidden;
        box-shadow: 0 20px 60px rgba(0, 40, 100, 0.2);
        background: white;
    }

    /* Sidebar Azul Escuro */
    .register-sidebar {
        background: linear-gradient(160deg, var(--blue-gradient-start) 0%, var(--blue-gradient-end) 100%);
        color: white;
        padding: 50px 40px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        text-align: center;
        position: relative;
        overflow: hidden;
    }
    
    .register-sidebar::after {
        content: '';
        position: absolute;
        width: 200%;
        height: 200%;
        top: -50%;
        left: -50%;
        background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(0,0,0,0) 60%);
        pointer-events: none;
    }

    .sidebar-icon {
        font-size: 5rem;
        margin-bottom: 20px;
        text-shadow: 0 5px 15px rgba(0,0,0,0.3);
        animation: float 3s ease-in-out infinite;
        color: #66b3ff;
    }

    /* Formulário */
    .register-form-area {
        padding: 50px;
        background: #fff;
    }

    .form-floating > .form-control {
        border-radius: 10px;
        border: 1px solid #dae1e7;
        background-color: #f8fafc;
    }
    .form-floating > .form-control:focus {
        border-color: var(--blue-primary);
        box-shadow: 0 0 0 0.25rem rgba(0, 102, 204, 0.2);
        background-color: white;
    }
    
    .section-title {
        font-family: 'Rajdhani', sans-serif;
        font-weight: 700;
        text-transform: uppercase;
        color: var(--blue-secondary);
        border-left: 5px solid var(--blue-primary);
        padding-left: 15px;
        margin-bottom: 25px;
        letter-spacing: 1px;
    }

    /* Seleção de Sexo Customizada (Estilo Azul) */
    .sex-selector .btn-check:checked + .btn {
        background-color: var(--blue-primary);
        color: white;
        border-color: var(--blue-primary);
        box-shadow: 0 5px 15px rgba(0, 102, 204, 0.3);
    }
    .sex-selector .btn {
        border: 1px solid #dae1e7;
        padding: 12px;
        color: #64748b;
        font-weight: 600;
        transition: all 0.3s;
        background: white;
    }
    .sex-selector .btn:hover {
        border-color: var(--blue-primary);
        color: var(--blue-primary);
    }

    /* Botão Principal */
    .btn-register {
        background: linear-gradient(45deg, var(--blue-secondary), var(--blue-primary));
        color: white;
        padding: 16px;
        font-size: 1.1rem;
        font-weight: bold;
        letter-spacing: 1px;
        border-radius: 10px;
        border: none;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(0, 64, 128, 0.2);
    }
    .btn-register:hover {
        background: linear-gradient(45deg, #003366, #0059b3);
        transform: translateY(-2px);
        box-shadow: 0 10px 25px rgba(0, 64, 128, 0.4);
        color: #e6f2ff;
    }

    /* Estilo do Alerta de Sucesso Personalizado */
    .alert-custom-success {
        background-color: #e6f7ff;
        border: 1px solid #91d5ff;
        color: #0050b3;
    }
    
    .text-link-blue {
        color: var(--blue-primary);
        font-weight: 700;
        text-decoration: none;
        transition: color 0.2s;
    }
    .text-link-blue:hover {
        color: var(--blue-secondary);
        text-decoration: underline;
    }

    @keyframes float {
        0% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
        100% { transform: translateY(0px); }
    }

    @media (max-width: 768px) {
        .register-sidebar { padding: 30px; }
        .register-form-area { padding: 30px 20px; }
    }
</style>

<div class="container my-5 register-container">
    
    <?php if(!empty($msg) && strpos($msg, 'alert-custom-success') !== false): ?>
        <?php echo $msg; ?>
    <?php else: ?>

    <div class="card register-card">
        <div class="row g-0">
            <div class="col-lg-4 register-sidebar">
                <i class="fas fa-user-shield sidebar-icon"></i>
                <h2 class="fw-bold mb-3" style="font-family: 'Rajdhani', sans-serif;">NOVA JORNADA</h2>
                <p class="mb-4 opacity-75">Crie sua conta e receba um Starter Pack especial com Level 15!</p>
                
                <div class="mt-auto">
                    <small class="d-block mb-2 text-white-50">Já possui uma conta?</small>
                    <a href="login.php" class="btn btn-outline-light rounded-pill px-4 fw-bold w-100 shadow-sm">
                        ACESSAR PAINEL
                    </a>
                </div>
            </div>

            <div class="col-lg-8 register-form-area">
                
                <?php echo $msg; ?>

                <form method="POST" action="">
                    <h5 class="section-title">1. Dados de Acesso</h5>
                    <div class="row g-3 mb-4">
                        <div class="col-md-12">
                            <div class="form-floating">
                                <input type="text" class="form-control" id="name" name="name" placeholder="Nome da Conta" required value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>">
                                <label for="name"><i class="fas fa-user me-2 text-muted"></i>Nome da Conta (Login)</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="password" class="form-control" id="password" name="password" placeholder="Senha" required>
                                <label for="password"><i class="fas fa-lock me-2 text-muted"></i>Senha</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-floating">
                                <input type="password" class="form-control" id="repassword" name="repassword" placeholder="Confirmar Senha" required>
                                <label for="repassword"><i class="fas fa-lock me-2 text-muted"></i>Confirmar Senha</label>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-floating">
                                <input type="email" class="form-control" id="email" name="email" placeholder="E-mail" required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
                                <label for="email"><i class="fas fa-envelope me-2 text-muted"></i>E-mail Válido</label>
                            </div>
                        </div>
                    </div>

                    <h5 class="section-title">2. Criar Personagem</h5>
                    <div class="row g-3 mb-4">
                        <div class="col-md-8">
                            <div class="form-floating">
                                <input type="text" class="form-control" id="char_name" name="char_name" placeholder="Nome do Personagem" required value="<?php echo isset($_POST['char_name']) ? htmlspecialchars($_POST['char_name']) : ''; ?>">
                                <label for="char_name"><i class="fas fa-gamepad me-2 text-muted"></i>Nome do Treinador</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="d-flex gap-2 sex-selector h-100">
                                <div class="flex-grow-1">
                                    <input type="radio" class="btn-check" name="sex" id="male" value="1" checked>
                                    <label class="btn w-100 h-100 d-flex flex-column justify-content-center align-items-center" for="male">
                                        <i class="fas fa-mars fs-5 mb-1"></i> Male
                                    </label>
                                </div>
                                <div class="flex-grow-1">
                                    <input type="radio" class="btn-check" name="sex" id="female" value="0">
                                    <label class="btn w-100 h-100 d-flex flex-column justify-content-center align-items-center" for="female">
                                        <i class="fas fa-venus fs-5 mb-1"></i> Female
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-check mb-4 ps-4">
                        <input class="form-check-input" type="checkbox" id="terms" required style="cursor: pointer;">
                        <label class="form-check-label text-muted small" for="terms" style="cursor: pointer;">
                            Eu li e concordo com os <a href="#" class="text-link-blue">Termos de Uso</a> e Regras do Servidor.
                        </label>
                    </div>

                    <button type="submit" class="btn-register w-100">
                        CRIAR CONTA AGORA <i class="fas fa-arrow-right ms-2"></i>
                    </button>

                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

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