<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Login - florAura</title>

    <!-- Fonts -->
    <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=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Tailwind CSS via CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Firebase SDK -->
    <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-database.js"></script>
    
    <style>
        .bg-gradient-custom {
            background: linear-gradient(to bottom, #052659, #021024);
        }
        
        body {
            background-image: url('{{ asset("images/bg-login.jpg") }}');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: fixed;
        }
        
        /* Overlay untuk background agar form lebih mudah dibaca */
        .bg-overlay {
            background-color: rgba(0, 0, 0, 0.5);
        }
    </style>
    
    <script>
        // Konfigurasi Firebase
        const firebaseConfig = {
            apiKey: "AIzaSyDf2QTksasAup4pzsNs9_JDpCXmBbUbywY",
            authDomain: "sensoranggrek-3d9ac.firebaseapp.com",
            databaseURL: "https://sensoranggrek-3d9ac-default-rtdb.firebaseio.com",
            projectId: "sensoranggrek-3d9ac",
            storageBucket: "sensoranggrek-3d9ac.firebasestorage.app",
            messagingSenderId: "16998798790",
            appId: "1:16998798790:web:885e1155255b24ab98cec7"
        };
        
        // Inisialisasi Firebase
        firebase.initializeApp(firebaseConfig);
    </script>
</head>
<body class="font-sans antialiased">
    <div class="min-h-screen flex items-center justify-center bg-overlay py-12 px-4 sm:px-6 lg:px-8">
        <div class="max-w-md w-full space-y-8">
            <div class="bg-gradient-custom p-8 rounded-lg shadow-lg text-white">
                <div class="text-center mb-6">
                    <h2 class="text-3xl font-extrabold">
                        florAura
                    </h2>
                    <p class="mt-2 text-sm text-gray-300">
                        Silakan login untuk melanjutkan
                    </p>
                </div>
                
                <div id="alert-message" class="hidden mb-4 p-4 rounded-md"></div>
                
                <!-- Tampilan status login saat ini -->
                <div id="current-login-status" class="hidden mb-4 p-4 bg-blue-900 bg-opacity-50 text-blue-100 rounded-md">
                    <p class="mb-2">Anda sudah login sebagai: <span id="current-user-email" class="font-semibold"></span></p>
                    <div class="flex space-x-2 mt-3">
                        <button id="continue-session" type="button" class="flex-1 py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            Lanjutkan
                        </button>
                        <button id="clear-session" type="button" class="flex-1 py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-white bg-transparent hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            Login dengan akun lain
                        </button>
                    </div>
                </div>
                
                <form id="login-form" class="space-y-6">
                    <div>
                        <label for="email" class="block text-sm font-medium text-gray-200">Email</label>
                        <div class="mt-1">
                            <input id="email" name="email" type="email" required autocomplete="email" class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm bg-gray-100 text-gray-900">
                        </div>
                    </div>

                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-200">Password</label>
                        <div class="mt-1">
                            <input id="password" name="password" type="password" required autocomplete="current-password" class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm bg-gray-100 text-gray-900">
                        </div>
                    </div>

                    <div class="flex items-center justify-between">
                        <div class="flex items-center">
                            <input id="remember_me" name="remember_me" type="checkbox" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded bg-gray-100">
                            <label for="remember_me" class="ml-2 block text-sm text-gray-200">
                                Ingat saya
                            </label>
                        </div>
                    </div>

                    <div>
                        <button type="submit" id="login-button" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                            Login
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Referensi elemen UI
            const loginForm = document.getElementById('login-form');
            const emailInput = document.getElementById('email');
            const passwordInput = document.getElementById('password');
            const rememberMeCheckbox = document.getElementById('remember_me');
            const loginButton = document.getElementById('login-button');
            const alertMessage = document.getElementById('alert-message');
            const currentLoginStatus = document.getElementById('current-login-status');
            const currentUserEmail = document.getElementById('current-user-email');
            const continueSessionButton = document.getElementById('continue-session');
            const clearSessionButton = document.getElementById('clear-session');
            
            // Tambahkan event listener untuk tombol "Lanjutkan" dan "Login dengan akun lain"
            if (continueSessionButton) {
                continueSessionButton.addEventListener('click', function() {
                    // Ambil user saat ini dan kirim ke server untuk membuat session
                    const user = firebase.auth().currentUser;
                    if (user) {
                        fetch("{{ route('login.process') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({
                                firebase_uid: user.uid,
                                email: user.email
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                window.location.href = data.redirect;
                            }
                        });
                    }
                });
            }
            
            if (clearSessionButton) {
                clearSessionButton.addEventListener('click', function() {
                    // Logout dari Firebase untuk menghapus state login
                    firebase.auth().signOut().then(function() {
                        // Sembunyikan status login, tampilkan form login
                        currentLoginStatus.classList.add('hidden');
                        loginForm.classList.remove('hidden');
                        
                        // Reset form inputs
                        if (loginForm.querySelector('input[type="email"]')) {
                            loginForm.querySelector('input[type="email"]').value = '';
                        }
                        if (loginForm.querySelector('input[type="password"]')) {
                            loginForm.querySelector('input[type="password"]').value = '';
                        }
                    });
                });
            }
            
            // Cek apakah user sudah login
            firebase.auth().onAuthStateChanged(function(user) {
                if (user) {
                    // Tampilkan info user saat ini dan sembunyikan form login
                    if (currentLoginStatus && currentUserEmail) {
                        currentUserEmail.textContent = user.email;
                        currentLoginStatus.classList.remove('hidden');
                        loginForm.classList.add('hidden');
                    }
                    
                    // Verifikasi status session hanya jika user memilih untuk melanjutkan
                    // dengan sesi yang ada (klik tombol "Lanjutkan")
                    // Kita tidak melakukan redirect otomatis lagi
                }
            });
            
            // Fungsi untuk menampilkan pesan error
            function showAlert(message, type = 'error') {
                alertMessage.textContent = message;
                alertMessage.classList.remove('hidden', 'bg-red-100', 'text-red-700', 'bg-green-100', 'text-green-700');
                
                if (type === 'error') {
                    alertMessage.classList.add('bg-red-900', 'bg-opacity-50', 'text-red-100');
                } else {
                    alertMessage.classList.add('bg-green-900', 'bg-opacity-50', 'text-green-100');
                }
            }
            
            // Event listener untuk form login
            loginForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // Disable button saat proses login
                loginButton.disabled = true;
                loginButton.textContent = 'Memproses...';
                
                const email = emailInput.value;
                const password = passwordInput.value;
                const rememberMe = rememberMeCheckbox.checked;
                
                // Set persistence berdasarkan remember me
                const persistence = rememberMe ? firebase.auth.Auth.Persistence.LOCAL : firebase.auth.Auth.Persistence.SESSION;
                
                firebase.auth().setPersistence(persistence)
                    .then(() => {
                        // Sign in dengan email dan password
                        return firebase.auth().signInWithEmailAndPassword(email, password);
                    })
                    .then((userCredential) => {
                        // Login berhasil
                        showAlert('Login berhasil! Mengalihkan...', 'success');
                        
                        // Kirim data user ke backend Laravel untuk membuat session
                        const user = userCredential.user;
                        
                        fetch("{{ route('login.process') }}", {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                            },
                            body: JSON.stringify({
                                firebase_uid: user.uid,
                                email: user.email
                            })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                // Redirect ke dashboard
                                window.location.href = data.redirect;
                            } else {
                                showAlert('Terjadi kesalahan saat memproses sesi login.');
                                loginButton.disabled = false;
                                loginButton.textContent = 'Login';
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showAlert('Terjadi kesalahan saat memproses sesi login.');
                            loginButton.disabled = false;
                            loginButton.textContent = 'Login';
                        });
                    })
                    .catch((error) => {
                        // Error handling
                        loginButton.disabled = false;
                        loginButton.textContent = 'Login';
                        
                        let errorMessage = 'Terjadi kesalahan saat login. Silakan coba lagi.';
                        
                        switch (error.code) {
                            case 'auth/invalid-email':
                                errorMessage = 'Format email tidak valid.';
                                break;
                            case 'auth/user-disabled':
                                errorMessage = 'Akun pengguna telah dinonaktifkan.';
                                break;
                            case 'auth/user-not-found':
                            case 'auth/wrong-password':
                                errorMessage = 'Email atau password tidak valid.';
                                break;
                            case 'auth/too-many-requests':
                                errorMessage = 'Terlalu banyak percobaan login. Silakan coba lagi nanti.';
                                break;
                        }
                        
                        showAlert(errorMessage);
                    });
            });
        });
    </script>
</body>
</html> 