<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/database.php';
require_once __DIR__ . '/../includes/functions.php';

if (is_logged_in()) redirect('');

$page_title = 'Crear Cuenta';
$error = '';
$nombres = $apellidos = $email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        $error = 'Token de seguridad invalido. Recarga la pagina.';
    } else {
        $nombres = sanitize($_POST['nombres'] ?? '');
        $apellidos = sanitize($_POST['apellidos'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmar = $_POST['confirmar_password'] ?? '';

        if (empty($nombres) || empty($apellidos) || empty($email) || empty($password)) {
            $error = 'Todos los campos son obligatorios.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Ingresa un correo electronico valido.';
        } elseif (strlen($password) < 6) {
            $error = 'La contrasena debe tener al menos 6 caracteres.';
        } elseif ($password !== $confirmar) {
            $error = 'Las contrasenas no coinciden.';
        } else {
            try {
                $db = db();
                $stmt = $db->prepare('SELECT id FROM usuarios WHERE email = ?');
                $stmt->execute([$email]);
                if ($stmt->fetch()) {
                    $error = 'Este correo ya esta registrado.';
                } else {
                    $hash = password_hash($password, PASSWORD_BCRYPT);
                    $stmt = $db->prepare(
                        'INSERT INTO usuarios (nombres, apellidos, email, password, rol) VALUES (?, ?, ?, ?, "cliente")'
                    );
                    $stmt->execute([$nombres, $apellidos, $email, $hash]);
                    $usuario_id = $db->lastInsertId();

                    if (session_status() === PHP_SESSION_NONE) {
                        session_start();
                    }
                    session_regenerate_id(true);
                    $_SESSION['usuario_id'] = $usuario_id;
                    $_SESSION['usuario_nombre'] = $nombres;
                    $_SESSION['usuario_rol'] = 'cliente';
                    csrf_regenerate();

                    set_flash('success', 'Cuenta creada exitosamente. Bienvenido a TechShop Peru.');
                    redirect('');
                }
            } catch (PDOException $e) {
                $error = 'Error del servidor. Intentalo nuevamente.';
            }
        }
    }
}

require_once __DIR__ . '/../includes/header.php';
?>

<section class="py-5">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-5 col-lg-4">
                <div class="auth-card card shadow-sm border-0">
                    <div class="card-body p-4">
                        <div class="text-center mb-4">
                            <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width:72px;height:72px;">
                                <i class="bi bi-person-plus-fill text-primary fs-1"></i>
                            </div>
                            <h1 class="h4 fw-bold mb-1">Crear Cuenta</h1>
                            <p class="text-muted small mb-0">Unete a TechShop Peru</p>
                        </div>

                        <?= flash_message() ?>
                        <?php if ($error): ?>
                            <div class="alert alert-danger d-flex align-items-center"><i class="bi bi-exclamation-triangle-fill me-2"></i><?= e($error) ?></div>
                        <?php endif; ?>

                        <form method="POST" novalidate>
                            <?= csrf_field() ?>
                            <div class="mb-3">
                                <label for="nombres" class="form-label fw-medium">Nombres</label>
                                <input type="text" class="form-control" id="nombres" name="nombres" value="<?= e($nombres) ?>" required maxlength="100">
                            </div>
                            <div class="mb-3">
                                <label for="apellidos" class="form-label fw-medium">Apellidos</label>
                                <input type="text" class="form-control" id="apellidos" name="apellidos" value="<?= e($apellidos) ?>" required maxlength="100">
                            </div>
                            <div class="mb-3">
                                <label for="email" class="form-label fw-medium">Correo Electronico</label>
                                <input type="email" class="form-control" id="email" name="email" value="<?= e($email) ?>" required>
                            </div>
                            <div class="mb-3">
                                <label for="password" class="form-label fw-medium">Contrasena</label>
                                <input type="password" class="form-control" id="password" name="password" required minlength="6">
                                <div class="form-text">Minimo 6 caracteres.</div>
                            </div>
                            <div class="mb-3">
                                <label for="confirmar_password" class="form-label fw-medium">Confirmar Contrasena</label>
                                <input type="password" class="form-control" id="confirmar_password" name="confirmar_password" required minlength="6">
                            </div>
                            <div class="d-grid mb-3">
                                <button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-person-check me-2"></i>Crear Cuenta</button>
                            </div>
                            <div class="text-center">
                                <p class="small text-muted mb-0">Ya tienes cuenta? <a href="<?= url('pages/login.php') ?>" class="fw-medium">Inicia Sesion</a></p>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
