<?php
require_once 'auth.php';

$auth = getAuth();

// Si ya esta logueado, redirige al inicio new
if ($auth->isLoggedIn()) {
    header('Location: ./');
    exit;
}

$flash = $_SESSION['login_flash'] ?? null;
unset($_SESSION['login_flash']);

$activeTab = $flash['tab'] ?? 'login';
$loginMessage = $flash['loginMessage'] ?? null;   // ['type' => 'error'|'success', 'text' => '...']
$registerMessage = $flash['registerMessage'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'login') {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $res = $auth->login($username, $password);
        if (!empty($res['success'])) {
            header('Location: ./');
            exit;
        }
        if (!empty($res['verification_required'])) {
            $_SESSION['verification_flash'] = [
                'type' => 'info',
                'text' => $res['message'] ?? 'Verifica tu correo para continuar.',
                'email' => $res['email'] ?? $username
            ];
            header('Location: verify_account');
            exit;
        }
        $_SESSION['login_flash'] = [
            'tab' => 'login',
            'loginMessage' => [
                'type' => 'error',
                'text' => $res['message'] ?? 'Error de inicio de sesion'
            ]
        ];     
        header('Location: login');
        exit;
    } elseif (isset($_POST['action']) && $_POST['action'] === "register") {
        $fullName = trim($_POST['full_name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? null;
        $docType = $_POST['doc_type'] ?? '';
        $docNumber = $_POST['doc_number'] ?? '';
        $country = $_POST['country'] ?? 'Colombia';
        $verificationMethod = $_POST['verification_method'] ?? 'both';
        $res = $auth->register($username, $email, $password, $fullName, $confirm, $docType, $docNumber, $country, $verificationMethod);
        if (!empty($res['success'])) {
            $_SESSION['login_flash'] = [
                'tab' => 'login',
                'loginMessage' => [
                    'type' => 'success',
                    'text' => isset($res['message']) && is_string($res['message']) ? $res['message'] : 'Cuenta creada. Ahora puede iniciar sesion.'
                ]
            ];
        } else {
            $_SESSION['login_flash'] = [
                'tab' => 'register',
                'registerMessage' => [
                    'type' => 'error',
                    'text' => $res['message'] ?? 'Error al registrar usuario'
                ]
            ];
        }
        header('Location: login');
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <title>Firmador de PDFs CODEX - Acceso</title>
    <style>
        * { box-sizing: border-box; }
        body {
            margin: 0; padding: 0; min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #29648D 0%, #29648D 100%);
            display: grid; place-items: center;
        }
        .card {
            width: 100%; max-width: 420px; background: #fff; border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3); overflow: hidden;
        }
        .card-header { padding: 24px; text-align: center; color: #fff;
            background: linear-gradient(135deg, #29648D 0%, #29648D 100%);
        }
        .brand { font-size: 1.4rem; font-weight: 700; margin: 6px 0 2px; }
        .subtitle { opacity: .9; font-size: .95rem; }
        .tabs { display: grid; grid-template-columns: 1fr 1fr; }
        .tab-btn {
            border: none; padding: 14px; background: #f3f6fb; cursor: pointer;
            font-weight: 600; color: #274864; border-bottom: 3px solid transparent;
        }
        .tab-btn.active { background: #fff; border-bottom-color: #29648D; }
        .pane { display: none; padding: 20px 22px 28px; }
        .pane.active { display: block; }
        .input { width: 100%; padding: 12px 14px; border: 1px solid #e3e8ef; border-radius: 10px; margin-top: 8px; }
        label { display: block; color: #374151; font-size: .9rem; margin-top: 14px; }
        .hint { color: #6b7280; font-size: .8rem; margin-top: 4px; }
        .btn-primary {
            width: 100%; margin-top: 18px; padding: 12px 16px; border-radius: 22px; border: none;
            background: linear-gradient(135deg, #1f6aa5, #29648D); color: #fff; font-weight: 700;
            cursor: pointer; box-shadow: 0 6px 18px rgba(41,100,141,.25);
        }
        .alert { padding: 12px 14px; border-radius: 10px; margin-bottom: 12px; font-size: .9rem; }
        .alert.error { background: #fdecea; color: #b42318; border: 1px solid #f1a7a1; }
        .alert.success { background: #ecfdf5; color: #027a48; border: 1px solid #9ae6b4; }
    </style>
</head>
<body>
    <div class="card">
        <div class="card-header">
            <div style="font-size:42px;">Tu Firma</div>
            <div class="brand">Firmador de PDFs CODEX</div>
            <div class="subtitle">Sistema Seguro de Firma Digital</div>
        </div>
        <div class="tabs">
            <button class="tab-btn <?php echo $activeTab==='login'?'active':''; ?>" data-tab="login">Iniciar Sesión</button>
            <button class="tab-btn <?php echo $activeTab==='register'?'active':''; ?>" data-tab="register">Registrarse</button>
        </div>

        <div class="pane <?php echo $activeTab==='login'?'active':''; ?>" id="pane-login">
            <?php if ($loginMessage): ?>
                <div class="alert <?php echo htmlspecialchars($loginMessage['type']); ?>">
                    <?php echo htmlspecialchars($loginMessage['text']); ?>
                </div>
            <?php endif; ?>
            <form method="post" action="">
                <input type="hidden" name="action" value="login">
                <label>Usuario o Email
                    <input class="input" type="text" name="username" autocomplete="username" required>
                </label>
                <label>Contraseña
                    <input class="input" type="password" name="password" autocomplete="current-password" required>
                </label>
                <button class="btn-primary" type="submit">Entrar</button>
                <div style="margin-top:10px; text-align:center;">
                    <a href="forgot_password" style="color:#29648D; font-weight:600; text-decoration:none;">Olvidaste tu contraseña? Recuperala aqui</a>
                </div>
            </form>
        </div>

        <div class="pane <?php echo $activeTab==='register'?'active':''; ?>" id="pane-register">
            <?php if ($registerMessage): ?>
                <div class="alert <?php echo htmlspecialchars($registerMessage['type']); ?>">
                    <?php echo htmlspecialchars($registerMessage['text']); ?>
                </div>
            <?php endif; ?>
            <form method="post" action="" id="registerForm" novalidate>
                <input type="hidden" name="action" value="register">  
                <label>Nombre Completo (Como en el documento)
                    <input class="input" type="text" name="full_name" required>
                </label>
                <label>Usuario
                    <input class="input" type="text" name="username" required>
                </label>
                <label>Email
                    <input class="input" type="email" name="email" autocomplete="email" required>
                </label>
                <label>Tipo de Documento
                    <select class="input" name="doc_type" required>
                        <option value="">Seleccione...</option>
                        <option value="CC">Cédula de ciudadaní­a</option>
                        <option value="CE">Cédula de extranjerí­a</option>
                        <option value="LC">Licencia de conducción</option>
                        <option value="PA">Pasaporte</option> 
                    </select>
                </label>
                <label>Número de Documento
                    <input class="input" type="text" name="doc_number" required>
                </label>
                <label>Paí­s
                    <select class="input" name="country" required>
                        <option value="Colombia" selected>Colombia</option>
                        <option value="Argentina">Argentina</option>
                        <option value="Chile">Chile</option>
                        <option value="Peru">Perú</option>
                        <option value="Mexico">México</option>
                        <option value="Otro">Otro</option>
                    </select>
                </label>
                <label>Metodo de verificacion del correo
                    <select class="input" name="verification_method" required>
                        <option value="link" selected>Enlace de verificacion</option>
                        <option value="code">Codigo de verificacion</option>
                        <option value="both">Enlace y codigo</option>
                    </select>
                </label>
                <label>Contraseña
                    <input class="input" type="password" id="reg_password" name="password" minlength="8" required>
                    <div class="hint">Mínimo 8 caracteres</div>
                </label>
                <label>Confirmar Contraseña
                    <input class="input" type="password" id="reg_confirm" name="confirm_password" minlength="8" required>
                </label>
                <button class="btn-primary" type="submit">Crear Cuenta</button>
            </form>
        </div>
    </div>

    <script>
        /// Tabs
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
                document.querySelectorAll('.pane').forEach(p => p.classList.remove('active'));
                btn.classList.add('active');
                const tab = btn.getAttribute('data-tab');
                document.getElementById('pane-' + tab).classList.add('active');
            });
        });

        /// Client-side confirm password validation
        const p = document.getElementById('reg_password');
        const c = document.getElementById('reg_confirm');
        function validateMatch(){
            if (!p || !c) return;
            const ok = p.value === c.value;
            c.setCustomValidity(ok ? '' : 'Las contraseñas no coinciden');
        } 
        if (p && c) {
            p.addEventListener('input', validateMatch);
            c.addEventListener('input', validateMatch);
        }
    </script>
</body>
</html>
