<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}" dir="{{ app()->getLocale() == 'ar' ? 'rtl' : 'ltr' }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    
    <title>{{ __('auth.login_title') }}</title>
    
    <!-- Bootstrap CSS RTL -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- Google Fonts Arabic -->
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700&display=swap" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Cairo', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .login-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            max-width: 900px;
            width: 100%;
        }
        
        .login-form {
            padding: 60px 40px;
        }
        
        .login-header {
            text-align: center;
            margin-bottom: 40px;
        }
        
        .login-header h1 {
            color: #333;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .login-header p {
            color: #666;
            font-size: 1.1rem;
        }
        
        .form-floating {
            margin-bottom: 20px;
        }
        
        .form-control {
            border-radius: 15px;
            border: 2px solid #e9ecef;
            padding: 12px 20px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-login {
            background: linear-gradient(135deg, #667eea, #764ba2);
            border: none;
            border-radius: 15px;
            padding: 15px;
            font-size: 1.1rem;
            font-weight: 600;
            width: 100%;
            color: white;
            transition: all 0.3s ease;
        }
        
        .btn-login:hover {
            background: linear-gradient(135deg, #5a6fd8, #6a4190);
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
        }
        
        .login-image {
            background: linear-gradient(135deg, #667eea, #764ba2);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            text-align: center;
            padding: 60px 40px;
        }
        
        .login-image i {
            font-size: 6rem;
            margin-bottom: 20px;
            opacity: 0.9;
        }
        
        .login-image h3 {
            font-weight: 700;
            margin-bottom: 15px;
        }
        
        .login-image p {
            font-size: 1.1rem;
            opacity: 0.9;
            line-height: 1.6;
        }
        
        .alert {
            border-radius: 15px;
            border: none;
            margin-bottom: 25px;
        }
        
        .form-check {
            margin-bottom: 25px;
        }
        
        .form-check-input:checked {
            background-color: #667eea;
            border-color: #667eea;
        }
        
        /* QR Code Styles */
        .login-methods .btn-group {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .login-methods .btn {
            border-radius: 0;
            padding: 12px;
            font-weight: 500;
        }
        
        .qr-login-section {
            animation: fadeIn 0.3s ease-in-out;
        }
        
        .qr-code-container {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 30px;
            min-height: 250px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .qr-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }
        
        .qr-status-item {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            padding: 10px;
            border-radius: 10px;
            background: #f8f9fa;
        }
        
        .status-icon {
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .qr-info .alert {
            border-radius: 10px;
            border: none;
            background: rgba(102, 126, 234, 0.1);
            color: #495057;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        #qr-code-display svg {
            max-width: 180px;
            height: auto;
        }
        
        @media (max-width: 768px) {
            .login-container {
                margin: 20px;
                border-radius: 15px;
            }
            
            .login-form {
                padding: 40px 30px;
            }
            
            .login-image {
                padding: 40px 30px;
            }
            
            .login-image i {
                font-size: 4rem;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="row g-0">
            <!-- Login Form -->
            <div class="col-lg-6">
                <div class="login-form">
                    <div class="login-header">
                        <h1>{{ __('auth.welcome') }}</h1>
                        <p>{{ __('auth.login_subtitle') }}</p>
                    </div>
                    
                    @if($errors->any())
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            @foreach($errors->all() as $error)
                                {{ $error }}<br>
                            @endforeach
                        </div>
                    @endif
                    
                    <!-- Login Method Toggle -->
                    <div class="login-methods mb-4">
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="login-method" id="email-login" autocomplete="off" checked>
                            <label class="btn btn-outline-primary" for="email-login">
                                <i class="fas fa-envelope me-2"></i>{{ __('Email & Password') }}
                            </label>
                            
                            <input type="radio" class="btn-check" name="login-method" id="qr-login" autocomplete="off">
                            <label class="btn btn-outline-primary" for="qr-login">
                                <i class="fas fa-qrcode me-2"></i>{{ __('QR Code') }}
                            </label>
                        </div>
                    </div>
                    
                    <!-- Email/Password Form -->
                    <div id="email-form-container">
                        <form method="POST" action="{{ route('login') }}">
                            @csrf
                            
                            <div class="form-floating">
                                <input type="email" class="form-control" id="email" name="email" 
                                       placeholder="{{ __('auth.email') }}" value="{{ old('email') }}" required>
                                <label for="email">
                                    <i class="fas fa-envelope me-2"></i>{{ __('auth.email') }}
                                </label>
                            </div>
                            
                            <div class="form-floating">
                                <input type="password" class="form-control" id="password" name="password" 
                                       placeholder="{{ __('auth.password') }}" required>
                                <label for="password">
                                    <i class="fas fa-lock me-2"></i>{{ __('auth.password') }}
                                </label>
                            </div>
                            
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="remember" name="remember">
                                <label class="form-check-label" for="remember">
                                    {{ __('auth.remember_me') }}
                                </label>
                            </div>
                            
                            <button type="submit" class="btn btn-login">
                                <i class="fas fa-sign-in-alt me-2"></i>
                                {{ __('auth.login_button') }}
                            </button>
                        </form>
                    </div>
                    
                    <!-- QR Code Form -->
                    <div id="qr-form-container" style="display: none;">
                        <div class="qr-login-section">
                            <div class="text-center mb-4">
                                <h5>{{ __('Scan QR Code to Login') }}</h5>
                                <p class="text-muted small">{{ __('Use your mobile device to scan the QR code below') }}</p>
                            </div>
                            
                            <div class="qr-code-container text-center mb-4">
                                <div id="qr-loading" class="qr-placeholder">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                    <p class="mt-2 text-muted">{{ __('Generating QR Code...') }}</p>
                                </div>
                                <div id="qr-code-display" style="display: none;"></div>
                                <div id="qr-expired" class="qr-placeholder" style="display: none;">
                                    <i class="fas fa-times-circle text-danger" style="font-size: 3rem;"></i>
                                    <p class="text-danger mt-2">{{ __('QR Code Expired') }}</p>
                                    <button id="refresh-qr" class="btn btn-outline-primary btn-sm">
                                        <i class="fas fa-refresh me-2"></i>{{ __('Generate New QR') }}
                                    </button>
                                </div>
                            </div>
                            
                            <div id="qr-status" class="text-center">
                                <div id="status-pending" class="qr-status-item">
                                    <div class="status-icon">
                                        <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                                    </div>
                                    <span class="text-muted small">{{ __('Waiting for QR scan...') }}</span>
                                </div>
                                
                                <div id="status-scanned" class="qr-status-item" style="display: none;">
                                    <div class="status-icon text-warning">
                                        <i class="fas fa-mobile-alt"></i>
                                    </div>
                                    <span class="text-warning small">{{ __('QR Code scanned! Completing login...') }}</span>
                                </div>
                                
                                <div id="status-authenticated" class="qr-status-item" style="display: none;">
                                    <div class="status-icon text-success">
                                        <i class="fas fa-check-circle"></i>
                                    </div>
                                    <span class="text-success small">{{ __('Login successful! Redirecting...') }}</span>
                                </div>
                            </div>
                            
                            <div class="qr-info mt-4">
                                <div class="alert alert-info">
                                    <div class="d-flex align-items-center">
                                        <i class="fas fa-info-circle me-3"></i>
                                        <div>
                                            <strong>{{ __('How to use QR Login:') }}</strong><br>
                                            <small>{{ __('1. Scan the QR code with your mobile device') }}</small><br>
                                            <small>{{ __('2. Enter your credentials on your mobile') }}</small><br>
                                            <small>{{ __('3. Complete login automatically on this page') }}</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mt-4 text-center">
                        <small class="text-muted">
                            <strong>{{ __('auth.test_data') }}</strong><br>
                            {{ __('auth.admin_credentials') }}<br>
                            {{ __('auth.assistant_credentials') }}
                        </small>
                    </div>
                </div>
            </div>
            
            <!-- Login Image -->
            <div class="col-lg-6">
                <div class="login-image">
                    <div>
                        <i class="fas fa-users"></i>
                        <h3>{{ __('auth.management_system') }}</h3>
                        <p>
                            {{ __('auth.system_description') }}
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        let currentQrToken = null;
        let qrStatusInterval = null;
        let qrCountdownInterval = null;
        
        // Toggle between login methods
        document.addEventListener('DOMContentLoaded', function() {
            const emailLoginRadio = document.getElementById('email-login');
            const qrLoginRadio = document.getElementById('qr-login');
            const emailContainer = document.getElementById('email-form-container');
            const qrContainer = document.getElementById('qr-form-container');
            
            emailLoginRadio.addEventListener('change', function() {
                if (this.checked) {
                    emailContainer.style.display = 'block';
                    qrContainer.style.display = 'none';
                    stopQrLogin();
                }
            });
            
            qrLoginRadio.addEventListener('change', function() {
                if (this.checked) {
                    emailContainer.style.display = 'none';
                    qrContainer.style.display = 'block';
                    startQrLogin();
                }
            });
            
            // Refresh QR button
            document.getElementById('refresh-qr').addEventListener('click', function() {
                startQrLogin();
            });
        });
        
        async function startQrLogin() {
            stopQrLogin(); // Stop any existing process
            
            // Show loading state
            document.getElementById('qr-loading').style.display = 'flex';
            document.getElementById('qr-code-display').style.display = 'none';
            document.getElementById('qr-expired').style.display = 'none';
            showQrStatus('pending');
            
            try {
                const response = await fetch('/qr-login/generate', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({})
                });
                
                const data = await response.json();
                console.log('QR Generation Response:', data);
                
                if (data.success) {
                    currentQrToken = data.token;
                    
                    // Display QR code
                    document.getElementById('qr-loading').style.display = 'none';
                    document.getElementById('qr-code-display').innerHTML = data.qr_code;
                    document.getElementById('qr-code-display').style.display = 'block';
                    
                    // Start polling for status
                    startQrStatusPolling();
                    
                    // Start countdown
                    startQrCountdown(data.expires_in);
                } else {
                    showQrError('Failed to generate QR code. Please try again.');
                }
            } catch (error) {
                console.error('QR generation error:', error);
                console.error('Error details:', error.stack);
                showQrError('Failed to generate QR code. Please check your connection.');
            }
        }
        
        function startQrStatusPolling() {
            if (!currentQrToken) return;
            
            qrStatusInterval = setInterval(async () => {
                try {
                    const response = await fetch(`/qr-login/${currentQrToken}/status`);
                    const data = await response.json();
                    
                    if (!data.success) {
                        if (data.status === 'expired') {
                            showQrExpired();
                        }
                        stopQrLogin();
                        return;
                    }
                    
                    switch (data.status) {
                        case 'pending':
                            showQrStatus('pending');
                            break;
                        case 'scanned':
                            showQrStatus('scanned');
                            // Auto complete login after scan
                            setTimeout(() => completeQrLogin(), 2000);
                            break;
                        case 'authenticated':
                            showQrStatus('authenticated');
                            stopQrLogin();
                            // Redirect will be handled by completeQrLogin
                            break;
                    }
                } catch (error) {
                    console.error('Status polling error:', error);
                }
            }, 2000); // Poll every 2 seconds
        }
        
        async function completeQrLogin() {
            if (!currentQrToken) return;
            
            try {
                const response = await fetch(`/qr-login/${currentQrToken}/complete`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({})
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showQrStatus('authenticated');
                    setTimeout(() => {
                        window.location.href = data.redirect_url;
                    }, 1500);
                } else {
                    showQrError(data.message || 'Login failed. Please try again.');
                }
            } catch (error) {
                console.error('Login completion error:', error);
                showQrError('Failed to complete login. Please try again.');
            }
        }
        
        function startQrCountdown(seconds) {
            let timeLeft = seconds;
            
            qrCountdownInterval = setInterval(() => {
                timeLeft--;
                
                if (timeLeft <= 0) {
                    showQrExpired();
                    stopQrLogin();
                }
            }, 1000);
        }
        
        function showQrStatus(status) {
            document.getElementById('status-pending').style.display = status === 'pending' ? 'flex' : 'none';
            document.getElementById('status-scanned').style.display = status === 'scanned' ? 'flex' : 'none';
            document.getElementById('status-authenticated').style.display = status === 'authenticated' ? 'flex' : 'none';
        }
        
        function showQrExpired() {
            document.getElementById('qr-loading').style.display = 'none';
            document.getElementById('qr-code-display').style.display = 'none';
            document.getElementById('qr-expired').style.display = 'flex';
            showQrStatus('pending'); // Reset status
        }
        
        function showQrError(message) {
            document.getElementById('qr-loading').style.display = 'none';
            document.getElementById('qr-code-display').style.display = 'none';
            document.getElementById('qr-expired').style.display = 'flex';
            document.getElementById('qr-expired').innerHTML = `
                <i class="fas fa-exclamation-triangle text-danger" style="font-size: 3rem;"></i>
                <p class="text-danger mt-2">${message}</p>
                <button id="refresh-qr" class="btn btn-outline-primary btn-sm" onclick="startQrLogin()">
                    <i class="fas fa-refresh me-2"></i>{{ __('Try Again') }}
                </button>
            `;
        }
        
        function stopQrLogin() {
            if (qrStatusInterval) {
                clearInterval(qrStatusInterval);
                qrStatusInterval = null;
            }
            if (qrCountdownInterval) {
                clearInterval(qrCountdownInterval);
                qrCountdownInterval = null;
            }
            currentQrToken = null;
        }
        
        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            stopQrLogin();
        });
    </script>
</body>
</html>

