<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '../core/init.php');

if (isset($_SESSION['client_id'])) {
    header('Location: dashboard.php'); 
    exit();
}

$error_message = '';
$access_code = '';

// 1.2. CONEXIÓN NECESARIA PARA EL PROCESO DE LOGIN DEL CLIENTE
$conn = @new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// 2. PROCESAR EL FORMULARIO DE INICIO DE SESIÓN
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $access_code = filter_input(INPUT_POST, 'access_code', FILTER_UNSAFE_RAW);

    if (empty($access_code) || strlen($access_code) != 5) {
        $error_message = 'The Access Code Is Incorrect. It Must Have 5 Digits';
    } else {
        // Verificar la conexión ANTES de intentar la consulta
        if ($conn->connect_error) {
            $error_message = 'Server Connection Error. Please Try Again Later';
        } else {
            // Preparar la consulta SQL para buscar el cliente por el código de acceso
            $stmt = $conn->prepare("SELECT id, first_name FROM clients WHERE access_code = ?");
            $stmt->bind_param('s', $access_code);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows === 1) {
                // Código encontrado: Inicio de sesión exitoso
                $client = $result->fetch_assoc();
                
                // 3. INICIAR SESIÓN DE USUARIO
                $_SESSION['client_id'] = $client['id'];
                $_SESSION['client_first_name'] = $client['first_name'];
                
                // Redirigir al portal
                header('Location: dashboard.php');
                exit();
            } else {
                // Código no encontrado o incorrecto
                $error_message = 'The Access Code Is Incorrect. Please Verify It And Try Again';
            }

            $stmt->close();
        }
    }
}

// 4. CIERRE DE LA CONEXIÓN (al final del script)
if (isset($conn) && !empty($conn) && !$conn->connect_error) {
    $conn->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client Portal Login Of <?php echo htmlspecialchars($branding['business_name']); ?> <?php echo htmlspecialchars($branding['full_title']); ?></title>
        <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="../style.css">
</head>
<body class="bg-gray-100">

    <div class="min-h-screen grid grid-cols-1 lg:grid-cols-2">
        
        <div class="hidden lg:flex relative flex-col items-center justify-center bg-[var(--brand-primary)] p-12 text-center bg-cover bg-center" style="background-image: url('https://images.unsplash.com/photo-1581578731548-c64695cc6952?q=80&w=2070&auto=format&fit=crop');">
            <div class="absolute inset-0 bg-[var(--brand-primary)] opacity-80"></div>
            
            <div class="relative z-10 flex flex-col items-center">
                <h1 class="text-5xl font-black text-white leading-tight uppercase">
                    Your <span class="text-yellow-400">Exclusive</span> Portal
                    </h1>
                
                <ul class="mt-8 text-left space-y-4 max-w-sm">
                    <li class="flex items-start gap-3">
                        <i data-lucide="calendar-check" class="w-6 h-6 text-[var(--brand-secondary)] mt-1 flex-shrink-0"></i>
                        <span class="text-lg text-white/90">Manage Your Appointments 24/7</span>
                    </li>
                    <li class="flex items-start gap-3">
                        <i data-lucide="receipt-text" class="w-6 h-6 text-[var(--brand-secondary)] mt-1 flex-shrink-0"></i>
                        <span class="text-lg text-white/90">View Your Billing And Payment History</span>
                    </li>
                    <li class="flex items-start gap-3">
                        <i data-lucide="message-square-plus" class="w-6 h-6 text-[var(--brand-secondary)] mt-1 flex-shrink-0"></i>
                        <span class="text-lg text-white/90">Submit Feedback Or Report An Issue</span>
                    </li>
                    <li class="flex items-start gap-3">
                        <i data-lucide="user-cog" class="w-6 h-6 text-[var(--brand-secondary)] mt-1 flex-shrink-0"></i>
                        <span class="text-lg text-white/90">Update Your Contact Information</span>
                    </li>
                </ul>
            </div>
        </div>

        <div class="flex flex-col items-center justify-center p-6 sm:p-12">
            <div class="w-full max-w-md">
                <img src="<?php echo LOGO_FILENAME; ?>" alt="<?php echo BUSINESS_NAME; ?> Logo" class="w-40 mx-auto mb-6">
                <div class="text-center mb-10">
                    <script>
                        var day = new Date();
                        var currentHour = day.getHours();
                        var greetingText, iconName;
                        var styleClass = 'text-xl sm:text-2xl font-extrabold tracking-wider text-brand-primary'; 
                        if (currentHour >= 0 && currentHour < 12) {
                            greetingText = "Hello, Good Morning!"; iconName = "sun";
                        } else if (currentHour >= 12 && currentHour <= 17) {
                            greetingText = "Hello, Good Afternoon!"; iconName = "cloud-sun";
                        } else {
                            greetingText = "Hello, Good Evening!"; iconName = "moon";
                        }
                        // Se ha agregado el id="lucide-icon-container" para que el script final lo procese
                        document.write(`<span id="lucide-icon-container" class="inline-flex items-center gap-3 ${styleClass}"><i data-lucide="${iconName}" class="w-7 h-7 text-brand-accent"></i><span>${greetingText}</span></span>`);
                    </script>
                    
                    <h2 class="text-4xl font-black uppercase text-[var(--brand-primary)]">
                        Secure Client Login
                    </h2>
                </div>

                <?php if (!empty($error_message)): ?>
                    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded-xl relative mb-6" role="alert">
                        <span class="block sm:inline font-bold">Error:</span>
                        <span class="block sm:inline"><?php echo $error_message; ?></span>
                    </div>
                <?php endif; ?>

                <form class="space-y-6" method="POST" action="">
                    <div>
                        <label for="access_code" class="text-sm font-bold text-gray-700 tracking-wide">Personal Access Code</label>
                        <div class="relative mt-2">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-4 pointer-events-none">
                                <i data-lucide="key-round" class="w-5 h-5 text-gray-400"></i>
                            </span>
                            
                            <input id="access_code" name="access_code" type="password" required 
                                class="block w-full h-14 pl-14 pr-12 rounded-xl border-gray-300 shadow-sm focus:border-[var(--brand-secondary)] focus:ring-[var(--brand-secondary)]" 
                                placeholder="•••••" 
                                maxlength="5" 
                                value="<?php echo htmlspecialchars($access_code); ?>">
                            
                            <button type="button" id="toggle-visibility-btn" class="absolute inset-y-0 right-0 flex items-center pr-4 text-gray-500 hover:text-[var(--brand-primary)]">
                                <i id="toggle-icon" data-lucide="eye" class="w-5 h-5"></i>
                            </button>
                        </div>
                    </div>

                    <div>
                        <button type="submit" class="w-full flex justify-center items-center gap-3 py-4 px-4 border border-transparent rounded-xl shadow-lg text-lg font-bold text-white bg-red-600 hover:brightness-110 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-600 transition-transform active:scale-95 uppercase">
                            <i data-lucide="log-in" class="w-5 h-5"></i>
                            SECURE SIGN IN
                        </button>
                    </div>
                </form>

                <div class="mt-12 text-center">
                    <p class="text-sm text-gray-500">&copy; <?php echo date('Y'); ?> <?php echo BUSINESS_NAME; ?>. All Rights Reserved.</p>
                </div>
            </div>
        </div>
    </div>

<script>
const toggleBtn = document.getElementById('toggle-visibility-btn');
const accessCodeInput = document.getElementById('access_code');
const toggleIcon = document.getElementById('toggle-icon');

if (toggleBtn) {
    toggleBtn.addEventListener('click', () => {
        if (accessCodeInput.type === 'password') {
            accessCodeInput.type = 'text';
            
            toggleIcon.setAttribute('data-lucide', 'eye-off'); 
        } else {
            accessCodeInput.type = 'password';
            
            toggleIcon.setAttribute('data-lucide', 'eye');
        }
        
        lucide.createIcons();
    });
}
lucide.createIcons();
</script>
<script src="files/toast.js"></script>
</body>
</html>