<?php
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';

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Aceptar usuario (nickname) o email
    $credential = trim($_POST['username'] ?? ($_POST['email'] ?? ''));
    $pass = trim($_POST['password'] ?? '');
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $stmt = $pdo->prepare("SELECT * FROM users WHERE (username = ? OR email = ?) AND status = 'active'");
    $stmt->execute([$credential, $credential]);
    $user = $stmt->fetch();
    if ($user && password_verify($pass, $user['password_hash'])) {
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_email'] = $user['email'];
        $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
        header('Location: ' . route_url(['module' => 'dashboard', 'action' => 'index']));
        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>CRM - Login</title>
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/auth.css'); ?>">
</head>
<body class="auth-page">
    <script>window.APP_BASE_PATH = <?php echo json_encode(get_base_path()); ?>;</script>
    <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">PF</div>
                <div class="brand-title">ProFix CRM</div>
                <div class="brand-subtitle">Gestión de clientes y ventas</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">Accede al CRM</p>
                </div>
                
                <?php if ($error): ?>
                    <div class="alert alert-error">
                        <strong>Error:</strong> <?= htmlspecialchars($error) ?>
                    </div>
                <?php endif; ?>
                
                <form method="post" class="login-form" id="loginForm">
                    <div class="form-floating">
                        <input type="text" id="username" name="username" placeholder=" " required autocomplete="username" spellcheck="false">
                        <label for="username">Usuario o Email</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>Iniciar Sesión</span>
                    </button>
                </form>
            </div>
        </section>
    </div>
    <script src="<?php echo asset('public/login_bg.js'); ?>"></script>
    <script src="<?php echo asset('public/script.js'); ?>"></script>
</body>
</html>