<?php

require_once __DIR__ . '/core/config.php';
require_once __DIR__ . '/core/session.php';
require_once __DIR__ . '/core/format.php';

if (is_logged_in()) {
    header('Location: /modules/dashboard/');
    exit;
}

?>
<!DOCTYPE html>
<html lang="es" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <title>Acceso | ICYLAB OS</title>
    <meta
    name="viewport"
    content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">

    <script src="https://accounts.google.com/gsi/client" async defer></script>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="/assets/css/app.css">
    <link rel="icon" type="image/svg+xml" href="/assets/img/favicon.svg">
    <link rel="manifest" href="/manifest.webmanifest">
    <link rel="icon" type="image/webp" href="/assets/img/favicon_light.webp">
    <meta name="theme-color" content="#050505">
</head>

<body class="login-body">

    <main class="login-shell">

        <section class="login-card" style="background: var(--surface-1); padding: var(--space-6); border-radius: var(--radius-xl); border: 1px solid var(--border-default); box-shadow: var(--shadow-lg); width: 100%; max-width: 400px; margin: 0 auto;">

            <div class="login-logo" style="text-align: center; margin-bottom: var(--space-3);">
                <img src="/assets/img/icylab-os.svg" alt="ICYLAB OS" style="height: 40px;">
            </div>
        
            <div class="login-content" style="text-align: center; margin-bottom: var(--space-5);">
                <p class="text-secondary">Plataforma interna para la gestión de ICYLAB.</p>
            </div>
        
            <?php if (isset($_GET['error'])): ?>
                <div class="alert alert-error mb-4" style="text-align: center;">
                    <?php echo safe_text($_GET['error']); ?>
                </div>
            <?php endif; ?>
        
            <form action="/login_process.php" method="POST" style="margin-bottom: var(--space-4);">
                <input type="hidden" name="_csrf_token" value="<?php echo safe_text(csrf_token()); ?>">
                <div class="form-field">
                    <label class="label">Email</label>
                    <input class="input" type="email" name="email" required placeholder="tu@correo.com">
                </div>
                <div class="form-field">
                    <label class="label">Contraseña</label>
                    <input class="input" type="password" name="password" required placeholder="••••••••">
                </div>
                <button type="submit" class="btn btn-primary" style="width: 100%; justify-content: center; margin-top: var(--space-2);">
                    Ingresar al Sistema
                </button>
            </form>
        
            <div style="display: flex; align-items: center; text-align: center; margin: var(--space-4) 0; color: var(--text-muted);">
                <div style="flex: 1; border-bottom: 1px solid var(--border-subtle);"></div>
                <span style="padding: 0 var(--space-3); font-size: 0.85rem; font-weight: 500;">O continuar con</span>
                <div style="flex: 1; border-bottom: 1px solid var(--border-subtle);"></div>
            </div>
        
            <div class="login-action" style="display: flex; flex-direction: column; gap: 8px; justify-content: center;">
                <button type="button" id="btn-google-auth" class="btn btn-outline" style="width: 100%; display: flex; align-items: center; justify-content: center; gap: 10px; height: 44px; border-radius: 50px;">
                    <img src="https://upload.wikimedia.org/wikipedia/commons/c/c1/Google_%22G%22_logo.svg" alt="Google" style="width: 20px; height: 20px;">
                    <span style="font-weight: 500;">Iniciar sesión con Google</span>
                </button>
                
                <button type="button" id="btn-google-sync" style="background: transparent; border: none; font-size: 0.75rem; color: var(--text-muted); cursor: pointer; text-decoration: underline; margin-top: 8px;">
                    ¿El calendario no sincroniza? Haz clic aquí
                </button>
            </div>
        
            <p class="login-note" style="text-align: center; margin-top: var(--space-5); font-size: 0.75rem; color: var(--text-muted);">
                Solo usuarios autorizados por administración.
            </p>
        
        </section>

    </main>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var googleAuthBtn = document.getElementById('btn-google-auth');
            var googleSyncBtn = document.getElementById('btn-google-sync');
            
            function triggerGoogleAuth(forceConsent) {
                if (typeof google === 'undefined' || !google.accounts) {
                    alert("La librería de Google aún no está cargada. Por favor, espera un momento y vuelve a intentar.");
                    return;
                }

                const clientConfig = {
                    client_id: '<?php echo GOOGLE_CLIENT_ID; ?>',
                    scope: 'openid email profile https://www.googleapis.com/auth/calendar.events',
                    ux_mode: 'popup',
                    state: <?php echo json_encode(csrf_token(), JSON_UNESCAPED_SLASHES); ?>,
                    hd: <?php echo json_encode(GOOGLE_ALLOWED_DOMAIN, JSON_UNESCAPED_SLASHES); ?>,
                    // Si forceConsent es falso, Google permite paso silencioso.
                    prompt: forceConsent ? 'consent' : '', 
                    callback: (response) => {
                        if (response.code) {
                            var originalText = googleAuthBtn.innerHTML;
                            googleAuthBtn.innerHTML = '<span style="font-weight: 500;">Autenticando...</span>';
                            googleAuthBtn.disabled = true;
                            
                            fetch('/auth/google_callback.php', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'X-Requested-With': 'XMLHttpRequest'
                                },
                                body: JSON.stringify({
                                    code: response.code,
                                    state: response.state || clientConfig.state
                                })
                            })
                            .then(res => res.text())
                            .then(text => {
                                var data;
                                try { data = JSON.parse(text); } catch (e) {
                                    alert('Respuesta inválida del servidor.');
                                    googleAuthBtn.innerHTML = originalText;
                                    googleAuthBtn.disabled = false;
                                    return;
                                }

                                if (data.success) {
                                    window.location.href = '/modules/dashboard/';
                                } else {
                                    alert(data.message || 'Acceso rechazado.');
                                    googleAuthBtn.innerHTML = originalText;
                                    googleAuthBtn.disabled = false;
                                }
                            })
                            .catch(error => {
                                alert('Error de autenticación en la red.');
                                googleAuthBtn.innerHTML = originalText;
                                googleAuthBtn.disabled = false;
                            });
                        }
                    }
                };

                const client = google.accounts.oauth2.initCodeClient(clientConfig);
                client.requestCode();
            }

            if (googleAuthBtn) {
                googleAuthBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    triggerGoogleAuth(false); // Inicio de sesión normal y silencioso
                });
            }

            if (googleSyncBtn) {
                googleSyncBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    triggerGoogleAuth(true); // Fuerza el consentimiento para recuperar el refresh_token perdido
                });
            }
        });
    </script>

</body>
</html>
