<?php
// =================================================================
// BLOQUE 1: INICIALIZACIÓN Y CONFIGURACIÓN
// =================================================================
session_start();
require_once '../db/business_config.php';

// --- CONFIGURACIÓN ESPECÍFICA DE LA PÁGINA DE LOGIN ---
// Beneficio: Define los códigos de acceso y la imagen de fondo en un solo lugar.
// Para una organización perfecta, puedes mover estas líneas a tu archivo `db/business_config.php`.
define('LOGIN_ACCESS_CODES', [
    '777',
    'CLIENTE-VIP-2025',
    'ACCESO-OFERTA-30'
]);
define('LOGIN_BG_IMAGE_URL', 'https://crm.tunegociocrm.com/img/BG-FlowCRM.webp');


// =================================================================
// BLOQUE 2: LÓGICA DE NEGOCIO (PROCESO DE LOGIN)
// =================================================================

// Si el usuario ya ha iniciado sesión, no necesita estar aquí.
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    header('Location: dashboard.php');
    exit;
}

$error_message = '';

// Procesar el formulario cuando se envía.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submitted_code = $_POST['access_code'] ?? '';

    // Compara el código enviado (sin importar mayúsculas/minúsculas) con la lista de códigos válidos.
    if (in_array(strtoupper($submitted_code), array_map('strtoupper', LOGIN_ACCESS_CODES))) {
        // Código Válido: Inicia la sesión y redirige al panel.
        $_SESSION['logged_in'] = true;
        $_SESSION['access_code'] = $submitted_code;
        header('Location: dashboard.php');
        exit;
    } else {
        // Código Inválido: Muestra un mensaje de error.
        $error_message = 'Código De Acceso Inválido. Por Favor, Intenta De Nuevo';
    }
}

// =================================================================
// BLOQUE 3: PRESENTACIÓN (HTML)
// =================================================================
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SiteFlow Portal Para <?php echo BUSINESS_NAME; ?> | <?php echo PHONE_PRIMARY; ?> — OrozDesign Multimedia</title>
<meta name="description" content=" — Call Us At <?php echo PHONE_PRIMARY; ?> | <?php echo BUSINESS_NAME; ?> ">

<link rel="icon" type="image/png" sizes="32x32" href="<?php echo LOGO_FILENAME; ?>">
<link rel="icon" type="image/png" sizes="16x16" href="<?php echo LOGO_FILENAME; ?>">
<link rel="shortcut icon" href="<?php echo LOGO_FILENAME; ?>">

<link rel="apple-touch-icon" sizes="180x180" href="<?php echo LOGO_FILENAME; ?>">
<meta name="theme-color" content="#07162d">
    
<?php require_once '../gtm-head.php'; ?>
    
    <script src="https://cdn.tailwindcss.com"></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=Barlow:wght@400;700;900&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="../style.css">
    <style>
        /* Único estilo en línea necesario para el fondo dinámico */
        .bg-login-image {
            background-image: url('<?php echo htmlspecialchars(LOGIN_BG_IMAGE_URL); ?>');
            background-size: cover;
            background-position: center;
        }
    </style>
</head>

<body>

<?php require_once '../gtm-body.php'; ?>

    <div class="grid lg:grid-cols-2">
        
        <div class="bg-[var(--brand-light)] flex lg:items-center justify-center p-8 lg:p-12 lg:order-first">
            <div class="w-full max-w-md mx-auto">
                <center><img src="<?php echo htmlspecialchars(LOGO_FILENAME); ?>" alt="Logo de <?php echo htmlspecialchars(BUSINESS_NAME); ?>" class="h-16 mb-8" ></center>
                <h2 class="font-black text-3xl sm:text-4xl text-center text-[var(--brand-primary)]">
                    ACCESO AL <span class="text-[var(--brand-accent)]">PORTAL</span>
                </h2>
                <p class="text-gray-600 text-center mt-2 mb-8">Ingresa Tu Código De Acceso Único Para Continuar</p>

                <form method="POST" action="login.php" class="space-y-6">
                    <div>
                        <div class="relative">
    <i data-lucide="key-round" class="w-5 h-5 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2"></i>
    <input
        id="access_code"
        type="text" 
        name="access_code"
        placeholder="Escribe Tu Código Aquí"
        required
        class="block w-full h-14 pl-12 pr-12 text-base font-bold tracking-wider rounded-xl border-2 border-gray-300 shadow-sm focus:border-[var(--brand-primary)] focus:ring-1 focus:ring-[var(--brand-primary)] transition-all duration-300"
    >
    <button type="button" id="togglePassword" class="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-[var(--brand-primary)] transition-colors duration-200" aria-label="Mostrar/Ocultar Código">
        <i data-lucide="eye" id="toggleIcon" class="w-5 h-5"></i>
    </button>
</div>
                    </div>

                    <?php if ($error_message): ?>
                        <p class="text-red-600 text-center text-sm font-semibold"><?php echo $error_message; ?></p>
                    <?php endif; ?>

                    <button type="submit" class="w-full bg-[var(--brand-accent)] text-white font-extrabold text-lg uppercase py-4 rounded-xl shadow-lg shadow-[var(--brand-accent)]/20 hover:shadow-[var(--brand-accent)]/40 hover:brightness-110 transition-all duration-300 active:scale-95 flex items-center justify-center gap-3">
                        <span>Iniciar Sesión</span>
                        <i data-lucide="log-in" class="w-5 h-5"></i>
                    </button>
                </form>

                <div class="mt-8 pt-4 border-t border-gray-200">
                    <p class="text-xs text-gray-500 text-center">© <?php echo date('Y'); ?> <?php echo htmlspecialchars(BUSINESS_NAME); ?>. Todos Los Derechos Reservados.</p>
                    <div class="footer-logo-container flex justify-center mt-4">
        <a href="https://orozdesign.com/?utm_source=LinksWebs&amp;utm_medium=Organico&amp;utm_campaign=LocalCRM-ToolKit" target="_blank">
            <img src="https://orozdesign.net/admin/orozdesign/PoweredByOROZCO-Dark.png" alt="OrozDesign Multimedia" height="25px" width="auto" onerror="this.onerror=null; this.src='https://placehold.co/100x25/f5f5f5/2a9d8f?text=Powered+by+OROZCO';"/>
        </a>
        </div>
                </div>
            </div>
        </div>

        <div class="relative bg-login-image min-h-[400px] lg:min-h-screen">
            <div class="absolute inset-0 bg-gradient-to-br from-[var(--brand-dark)] to-[var(--brand-primary)] opacity-75"></div>
            <div class="relative z-10 flex flex-col justify-center h-full p-8 lg:p-12 text-white">
                <div>
                    <h1 class="font-black text-4xl lg:text-5xl leading-tight">Tu Centro De Marketing</h1>
                    <p class="mt-4 text-lg text-white/80">Herramientas Y Recursos Diseñados Para El Crecimiento De Tu Negocio</p>
                </div>
                <div class="mt-12">
                    <h2 class="font-bold text-xl mb-4 text-[var(--brand-secondary)] tracking-wider">INCLUYE</h2>
                    <div class="space-y-4">
                        <div class="flex items-center gap-4"><i data-lucide="megaphone" class="w-6 h-6 text-[var(--brand-secondary)]"></i><span class="text-white/90">Páginas De Generación De Prospectos</span></div>
                        <div class="flex items-center gap-4"><i data-lucide="star" class="w-6 h-6 text-[var(--brand-secondary)]"></i><span class="text-white/90">Sistema Para Solicitar Reseñas</span></div>
                        <div class="flex items-center gap-4"><i data-lucide="file-spreadsheet" class="w-6 h-6 text-[var(--brand-secondary)]"></i><span class="text-white/90">Herramienta Generador De Cotizaciones</span></div>
                        <div class="flex items-center gap-4"><i data-lucide="file-text" class="w-6 h-6 text-[var(--brand-secondary)]"></i><span class="text-white/90">Herramienta Generador De Facturas</span></div>
                        <div class="flex items-center gap-4"><i data-lucide="qr-code" class="w-6 h-6 text-[var(--brand-secondary)]"></i><span class="text-white/90">Material De Marketing Con Códigos QR</span></div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    
    <script>
        lucide.createIcons();
    </script>
    <script>
// Función para cambiar el tipo de campo entre 'text' y 'password'
document.addEventListener('DOMContentLoaded', () => {
    // Inicializa íconos de Lucide
    lucide.createIcons();

    const toggleButton = document.getElementById('togglePassword');
    const inputField = document.getElementById('access_code');
    const toggleIcon = document.getElementById('toggleIcon');

    if (toggleButton && inputField && toggleIcon) {
        toggleButton.addEventListener('click', () => {
            // Alternar el atributo 'type'
            const currentType = inputField.getAttribute('type');
            if (currentType === 'text') {
                inputField.setAttribute('type', 'password');
                toggleIcon.setAttribute('data-lucide', 'eye-off'); // Icono de ojo tachado
            } else {
                inputField.setAttribute('type', 'text');
                toggleIcon.setAttribute('data-lucide', 'eye'); // Icono de ojo normal
            }

            // Volver a crear los iconos para que Lucide los renderice
            lucide.createIcons(); 
            
            // Colocar el foco de nuevo en el campo
            inputField.focus(); 
        });
        
        // Configuración inicial: Inicia como PASSWORD
        inputField.setAttribute('type', 'password');
        toggleIcon.setAttribute('data-lucide', 'eye-off'); // Establece el icono inicial
        lucide.createIcons();
    }
});
</script>
</body>
</html>