<?php
// Portal Cliente - Registro
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

$info_message = '';
$error_message = '';
$success = false;

function split_full_name($fullName) {
    $fullName = trim(preg_replace('/\s+/', ' ', $fullName));
    if ($fullName === '') { return ['first' => '', 'last' => '']; }
    $parts = explode(' ', $fullName);
    $first = array_shift($parts);
    $last = count($parts) ? implode(' ', $parts) : '';
    return ['first' => $first, 'last' => $last];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $password = trim($_POST['password'] ?? '');

    // Validaciones básicas
    if ($full_name === '' || $email === '' || $password === '') {
        $error_message = 'Por favor, completa los campos requeridos.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = 'El correo electrónico no es válido.';
    } elseif (strlen($password) < 6) {
        $error_message = 'La contraseña debe tener al menos 6 caracteres.';
    } else {
        try {
            $db = Database::getInstance();
            $pdo = $db->getConnection();

            // Verificar si el email ya existe
            $existing = $db->selectOne('SELECT id FROM clients WHERE email = ?', [$email]);
            if ($existing) {
                $error_message = 'El correo ya está registrado.';
            } else {
                $names = split_full_name($full_name);
                $password_hash = password_hash($password, PASSWORD_DEFAULT);

                $stmt = $pdo->prepare('INSERT INTO clients (email, first_name, last_name, phone, status, password_hash, created_at) VALUES (?, ?, ?, ?, "active", ?, NOW())');
                $ok = $stmt->execute([$email, $names['first'], $names['last'], $phone, $password_hash]);

                if ($ok) {
                    $success = true;
                    // Redirigir al login con mensaje de éxito
                    $login_url = module_url('client_portal/login.php');
                    header('Location: ' . $login_url . '?message=registered');
                    exit;
                } else {
                    $error_message = 'No fue posible registrar el cliente. Inténtalo nuevamente.';
                }
            }
        } catch (Exception $e) {
            error_log('Error en registro: ' . $e->getMessage());
            $error_message = 'Error interno al procesar el registro.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trader Room - Registro</title>
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/auth.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/client_portal.css'); ?>">
</head>
<body class="auth-page">
    <div class="auth-layout">
        <section class="hero" id="hero">
            <canvas id="bgCanvas" class="trading-bg-canvas"></canvas>
            <div class="bg-overlay animated"></div>
            <div class="brand-masthead brand-header">
                <div class="brand-logo">TR</div>
                <div class="brand-title">Trader Room</div>
                <div class="brand-subtitle">Registro de Cliente</div>
            </div>
        </section>
        <section class="panel">
            <div class="form-container">
                <div class="form-header">
                    <h2 class="form-title">Crear Cuenta de Cliente</h2>
                    <p class="form-subtitle">Regístrate para acceder al Trader Room</p>
                </div>

                <?php if ($error_message): ?>
                    <div class="alert alert-error">
                        <strong>Error:</strong> <?= htmlspecialchars($error_message) ?>
                    </div>
                <?php endif; ?>

                <?php if ($info_message): ?>
                    <div class="alert alert-info">
                        <strong>Info:</strong> <?= htmlspecialchars($info_message) ?>
                    </div>
                <?php endif; ?>

                <form method="post" class="login-form" id="registerForm">
                    <div class="form-floating">
                        <input type="text" id="full_name" name="full_name" placeholder=" " required>
                        <label for="full_name">Nombre completo</label>
                    </div>

                    <div class="form-floating">
                        <input type="email" id="email" name="email" placeholder=" " required>
                        <label for="email">Correo electrónico</label>
                    </div>

                    <div class="form-floating">
                        <input type="tel" id="phone" name="phone" placeholder=" ">
                        <label for="phone">Número de teléfono</label>
                    </div>

                    <div class="form-floating">
                        <input type="password" id="password" name="password" placeholder=" " required>
                        <label for="password">Contraseña</label>
                    </div>

                    <button type="submit" class="btn btn-login">
                        <span>Registrarme</span>
                        <svg class="btn-arrow" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"/>
                        </svg>
                    </button>
                </form>

                <div class="login-footer">
                    <p>¿Ya tienes cuenta? <a href="<?php echo module_url('client_portal/login.php'); ?>" class="register-link">Inicia sesión</a></p>
                </div>
            </div>
        </section>
    </div>
    <script src="<?php echo asset('public/login_bg.js'); ?>"></script>
    <script src="<?php echo asset('public/script.js'); ?>"></script>
</body>
</html>