<?php
// Portal Cliente - Login
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';

function isClientLoggedIn(){ return isset($_SESSION['client_id']); }

// Manejar mensajes de la URL
$info_message = '';
$error_message = '';

if (isset($_GET['message'])) {
    switch ($_GET['message']) {
        case 'webtrader_access':
            $info_message = 'Para acceder al WebTrader debe iniciar sesión como cliente.';
            break;
        case 'registered':
            $info_message = 'Registro exitoso. Ahora puedes iniciar sesión.';
            break;
    }
}

if (isset($_GET['error'])) {
    switch ($_GET['error']) {
        case 'account_inactive':
            $error_message = 'Su cuenta está inactiva. Contacte con soporte.';
            break;
    }
}

// Si ya está logueado, redirigir
if (isClientLoggedIn()) { 
    $redirectParam = $_GET['redirect'] ?? null;
    if ($redirectParam && preg_match('/^\/?modules\//', $redirectParam)) {
        $redirect = module_url(ltrim($redirectParam, '/'));
    } else {
        $redirect = $redirectParam ?: module_url('client_portal/dashboard.php');
    }
    header('Location: ' . $redirect); 
    exit; 
}

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $pass = trim($_POST['password'] ?? '');
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $stmt = $pdo->prepare("SELECT * FROM clients WHERE email = ? AND status = 'active'");
    $stmt->execute([$email]);
    $client = $stmt->fetch();
    if ($client && password_verify($pass, $client['password_hash'])) {
        $_SESSION['client_id'] = $client['id'];
        $_SESSION['client_email'] = $client['email'];
        $_SESSION['client_name'] = $client['first_name'] . ' ' . $client['last_name'];
        // Variables de sesión adicionales para compatibilidad con WebTrader y portal
        $_SESSION['client_first_name'] = $client['first_name'] ?? '';
        $_SESSION['client_last_name'] = $client['last_name'] ?? '';
        $_SESSION['client_status'] = 'active';
        
        // Redirigir al webtrader si viene de ahí, sino al dashboard
        $redirectParam = $_GET['redirect'] ?? null;
        if ($redirectParam && preg_match('/^\/?modules\//', $redirectParam)) {
            $redirect = module_url(ltrim($redirectParam, '/'));
        } else {
            $redirect = $redirectParam ?: module_url('client_portal/dashboard.php');
        }
        header('Location: ' . $redirect);
        exit;
    } else {
        $error = 'Credenciales inválidas';
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trader Room - Login</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="symbols">
                <span class="symbol" style="top:12%; left:8%; font-size:18px;">EURUSD</span>
                <span class="symbol alt" style="top:30%; left:22%; font-size:20px; animation-delay: -6s;">BTCUSD</span>
                <span class="symbol" style="top:58%; left:14%; font-size:16px; animation-delay: -12s;">XAUUSD</span>
                <span class="symbol alt" style="top:75%; left:40%; font-size:22px; animation-delay: -3s;">NASDAQ</span>
                <span class="symbol" style="top:44%; left:70%; font-size:18px; animation-delay: -9s;">WTI</span>
                <span class="symbol alt" style="top:20%; left:82%; font-size:16px; animation-delay: -15s;">ETHUSD</span>
            </div>
            <div class="brand-masthead brand-header">
                <div class="brand-logo">TR</div>
                <div class="brand-title">Trader Room</div>
                <div class="brand-subtitle">Plataforma de inversión CFD · Forex</div>
                <ul class="brand-features">
                    <li>Gestión completa de cuentas</li>
                    <li>Dashboard en tiempo real</li>
                    <li>Seguridad avanzada</li>
                </ul>
            </div>
            <div class="news-ticker">
                <div class="ticker-track">
                    <span class="ticker-item up">EURUSD +0.18%</span>
                    <span class="ticker-item down">BTCUSD -1.05%</span>
                    <span class="ticker-item up">XAUUSD +0.42%</span>
                    <span class="ticker-item up">NAS100 +0.35%</span>
                    <span class="ticker-item down">WTI -0.28%</span>
                    <span class="ticker-item up">ETHUSD +0.91%</span>
                </div>
            </div>
        </section>
        <section class="panel">
            <div class="form-container">
                <div class="form-header">
                    <h2 class="form-title">Iniciar Sesión</h2>
                    <p class="form-subtitle">Ingresa tus credenciales para acceder</p>
                </div>
                
                <?php if ($error): ?>
                    <div class="alert alert-error">
                        <strong>Error:</strong> <?= htmlspecialchars($error) ?>
                    </div>
                <?php endif; ?>
                
                <?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="loginForm">
                    <div class="form-floating">
                        <input type="email" id="email" name="email" placeholder=" " required>
                        <label for="email">Usuario o Email</label>
                        <svg class="login-icon" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
                        </svg>
                    </div>
                    
                    <div class="form-floating">
                        <input type="password" id="password" name="password" placeholder=" " required>
                        <label for="password">Contraseña</label>
                        <svg class="login-icon" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM12 17c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM15.1 8H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/>
                        </svg>
                    </div>
                    
                    <div class="form-options">
                        <label class="checkbox-container">
                            <input type="checkbox" name="remember">
                            <span class="checkmark"></span>
                            Recordarme
                        </label>
                        <a href="#" class="forgot-link">¿Olvidaste tu contraseña?</a>
                    </div>
                    
                    <button type="submit" class="btn btn-login">
                        <span>Iniciar Sesión</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>¿No tienes cuenta? <a href="<?php echo module_url('client_portal/register.php'); ?>" class="register-link">Regístrate aquí</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>
