<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title>Sign in - <?php echo e(\App\Models\Setting::get('site_name', 'KiyoKart')); ?></title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="<?php echo e(asset('css/bootstrap.min.css')); ?>" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo e(asset('css/bootstrap-icons.css')); ?>">
    <link rel="stylesheet" href="<?php echo e(asset('css/homepage.css')); ?>">
    
    <style>
        .login-form-section {
            display: none;
        }
        .login-form-section.active {
            display: block;
        }
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
            display: none;
        }
        .error-message.show {
            display: block;
        }
        .alert-message {
            padding: 0.75rem 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            display: none;
            background: var(--color-primary-light) !important;
            border: 1px solid var(--color-primary-light) !important;
            color: var(--color-primary) !important;
        }
        .alert-message.show {
            display: block;
        }
        .alert-success {
            background: #d1fae5;
            border: 1px solid #059669;
            color: #065f46;
        }
        .alert-error {
            background: #fee2e2;
            border: 1px solid #dc2626;
            color: #991b1b;
        }
        .btn-continue:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        .loading-spinner {
            display: none;
            margin-left: 0.5rem;
        }
        .loading-spinner.show {
            display: inline-block;
        }
        .password-input-wrapper .form-control {
            padding-right: 2.5rem;
        }
        .password-toggle-icon {
            position: absolute;
            top: 73%;
            right: 15px;
            transform: translateY(-50%);
            cursor: pointer;
            color: #000;
            z-index: 3;
        }
    </style>
</head>
<body class="login-page text-white">
    <div class="login-container">
        <div class="login-card">
            <!-- Logo Section -->
            <div class="login-logo">
                <?php
                    $logoUrl = \App\Models\Setting::getLogoUrl('light');
                    $siteName = \App\Models\Setting::get('site_name', 'KIYOKART');
                ?>
                <?php if($logoUrl): ?>
                    <img src="<?php echo e($logoUrl); ?>" alt="<?php echo e($siteName); ?>">
                    <!-- <span class="brand-text"><?php echo e(strtoupper($siteName)); ?></span> -->
                <?php else: ?>
                    <div class="brand-icon"><?php echo e(substr(strtoupper($siteName), 0, 1)); ?></div>
                    <!-- <span class="brand-text"><?php echo e(strtoupper($siteName)); ?></span> -->
                <?php endif; ?>
            </div>
            
            <h1 class="login-heading">Sign in</h1>
            
            <!-- Alert Messages -->
            <div id="alert-message" class="alert-message"></div>
            
            <!-- Login Mode Toggle -->
            <div class="login-toggle">
                <button type="button" class="login-toggle-btn active" data-mode="otp" id="toggle-otp">
                    OTP
                </button>
                <button type="button" class="login-toggle-btn" data-mode="password" id="toggle-password">
                    Password
                </button>
            </div>

            <!-- OTP Login Form Section -->
            <div id="otp-form-section" class="login-form-section active">
                <!-- Request OTP Form -->
                <div id="otp-request-form">
                    <p class="login-subtitle mb-3">Enter your mobile number and we'll send you a verification code</p>
                    
                    <form id="otp-request-form-element">
                        <div class="mb-3">
                            <label class="form-label">Mobile Number</label>
                            <div class="input-group">
                                <span class="input-group-text">+91</span>
                                <input type="tel" name="mobile" id="otp-mobile" class="form-control" 
                                       placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" 
                                       autocomplete="tel-national" required>
                            </div>
                            <div class="error-message" id="otp-mobile-error"></div>
                            <small class="form-text text-white">Enter 10-digit mobile number</small>
                        </div>
                        <button type="submit" class="btn-continue mt-2" id="otp-request-btn">
                            Continue
                            <span class="loading-spinner spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                        </button>
                    </form>
                </div>

                <!-- Verify OTP Form (hidden initially) -->
                <div id="otp-verify-form" style="display: none;">
                    <p class="login-subtitle">Enter the verification code sent to <span id="otp-verify-mobile"></span></p>
                    
                    <form id="otp-verify-form-element">
                        <input type="hidden" name="mobile" id="otp-verify-mobile-input">
                        <div class="mb-3">
                            <label class="form-label">Enter OTP</label>
                            <input type="text" name="otp" id="otp-code" class="form-control" 
                                   placeholder="6-digit OTP" maxlength="6" required>
                            <div class="error-message" id="otp-code-error"></div>
                        </div>
                        <button type="submit" class="btn-continue mt-2" id="otp-verify-btn">
                            Verify & Login
                            <span class="loading-spinner spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                        </button>
                    </form>

                    <button type="button" class="resend-otp-btn mb-3" id="resend-otp-btn">
                        Resend OTP
                    </button>
                </div>
            </div>

            <!-- Password Login Form Section -->
            <div id="password-form-section" class="login-form-section">
                <p class="login-subtitle mb-3">Enter your mobile number and password to sign in</p>
                
                <form id="password-form-element">
                    <div class="mb-3">
                        <label class="form-label">Mobile Number</label>
                        <div class="input-group">
                            <span class="input-group-text">+91</span>
                            <input type="tel" name="mobile" id="password-mobile" class="form-control" 
                                   placeholder="9876543210" maxlength="10" pattern="[6-9]\d{9}" 
                                   autocomplete="tel-national" required>
                        </div>
                        <div class="error-message" id="password-mobile-error"></div>
                        <small class="form-text text-white">Enter 10-digit mobile number</small>
                    </div>

                    <div class="mb-3 position-relative password-input-wrapper">
                        <label class="form-label">Password</label>
                        <input type="password" name="password" id="password-input" class="form-control" 
                               placeholder="Enter your password" required>
                        <i class="bi bi-eye-slash password-toggle-icon" id="togglePassword" aria-label="Toggle password visibility" role="button" tabindex="0"></i>
                        <div class="error-message" id="password-password-error"></div>
                    </div>

                    <button type="submit" class="btn-continue mt-2" id="password-submit-btn">
                        Continue
                        <span class="loading-spinner spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    </button>
                </form>

                <div class="forgot-password-link mb-3">
                    <a href="javascript:void(0);" class="text-link" id="switch-to-otp-link">
                        <i class="bi bi-phone"></i> Login with OTP instead?
                    </a>
                </div>
            </div>
            
            <!-- Footer Links -->
            <div class="footer-links">
                <a href="<?php echo e(route('policy.privacy')); ?>" class="text-link">Privacy policy</a>
                <a href="<?php echo e(route('policy.terms')); ?>" class="text-link">Terms of service</a>
            </div>
        </div>
    </div>

    <!-- JSEncrypt Library for RSA Encryption -->
    <script src="<?php echo e(asset('js/jsencrypt.min.js')); ?>"></script>

    <script>
    (function() {
        // Global state
        let currentMode = 'otp';
        let rsaPublicKey = null;
        let otpMobile = null;

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            initializeRSA();
            setupModeToggle();
            setupForms();
            setupPasswordToggle();
        });

        // Initialize RSA encryption
        async function initializeRSA() {
            try {
                const url = '<?php echo e(route("api.login.public-key")); ?>';
                console.log('Fetching RSA public key from:', url);
                
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    credentials: 'same-origin'
                });
                
                console.log('Response status:', response.status, response.statusText);
                
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('Response error:', errorText);
                    throw new Error(`HTTP error! status: ${response.status} - ${errorText}`);
                }
                
                const data = await response.json();
                console.log('Response data:', data);
                
                if (data.error) {
                    console.error('RSA key error:', data.error);
                    throw new Error(data.error);
                }
                
                if (!data.public_key) {
                    throw new Error('Public key not found in response');
                }
                
                // Use the public key directly (it's already in PEM format)
                rsaPublicKey = data.public_key;
                console.log('RSA public key loaded successfully');
                
                // Verify the key format
                if (!rsaPublicKey.includes('BEGIN PUBLIC KEY')) {
                    throw new Error('Invalid public key format');
                }
            } catch (error) {
                console.error('Failed to load RSA public key:', error);
                const errorMsg = error.message || 'Unknown error';
                showAlert('Failed to initialize encryption: ' + errorMsg + '. Please refresh the page or contact support.', 'error');
            }
        }

        // Setup mode toggle
        function setupModeToggle() {
            const otpToggle = document.getElementById('toggle-otp');
            const passwordToggle = document.getElementById('toggle-password');
            const switchToOtpLink = document.getElementById('switch-to-otp-link');
            const otpSection = document.getElementById('otp-form-section');
            const passwordSection = document.getElementById('password-form-section');

            function switchToMode(mode) {
                currentMode = mode;
                
                if (mode === 'otp') {
                    otpToggle.classList.add('active');
                    passwordToggle.classList.remove('active');
                    otpSection.classList.add('active');
                    passwordSection.classList.remove('active');
                } else {
                    passwordToggle.classList.add('active');
                    otpToggle.classList.remove('active');
                    passwordSection.classList.add('active');
                    otpSection.classList.remove('active');
                }
                
                clearErrors();
                hideAlert();
            }

            otpToggle.addEventListener('click', () => switchToMode('otp'));
            passwordToggle.addEventListener('click', () => switchToMode('password'));
            switchToOtpLink?.addEventListener('click', () => switchToMode('otp'));
        }

        // Setup form handlers
        function setupForms() {
            // OTP Request Form
            document.getElementById('otp-request-form-element').addEventListener('submit', handleOtpRequest);
            
            // OTP Verify Form
            document.getElementById('otp-verify-form-element').addEventListener('submit', handleOtpVerify);
            
            // Resend OTP
            document.getElementById('resend-otp-btn').addEventListener('click', handleResendOtp);
            
            // Password Form
            document.getElementById('password-form-element').addEventListener('submit', handlePasswordLogin);

            // Mobile number normalization
            setupMobileNormalization();
        }

        function setupPasswordToggle() {
            const togglePassword = document.getElementById('togglePassword');
            const passwordInput = document.getElementById('password-input');

            if (!togglePassword || !passwordInput) {
                return;
            }

            const toggle = () => {
                const isPassword = passwordInput.type === 'password';
                passwordInput.type = isPassword ? 'text' : 'password';
                togglePassword.classList.toggle('bi-eye');
                togglePassword.classList.toggle('bi-eye-slash');
            };

            togglePassword.addEventListener('click', toggle);
            togglePassword.addEventListener('keydown', (event) => {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    toggle();
                }
            });
        }

        // Mobile number normalization
        function setupMobileNormalization() {
            const mobileInputs = document.querySelectorAll('input[type="tel"][name="mobile"]');
            
            mobileInputs.forEach(input => {
                input.addEventListener('input', function(e) {
                    let value = this.value.replace(/\D/g, '').substring(0, 10);
                    if (this.value !== value) {
                        this.value = value;
                    }
                });

                input.addEventListener('blur', function() {
                    let value = this.value.replace(/\D/g, '').substring(0, 10);
                    this.value = value;
                });
            });
        }

        // Handle OTP Request
        async function handleOtpRequest(e) {
            e.preventDefault();
            clearErrors();
            hideAlert();

            const mobile = document.getElementById('otp-mobile').value.trim();
            
            if (!validateMobile(mobile)) {
                showError('otp-mobile-error', 'Please enter a valid 10-digit mobile number starting with 6-9');
                return;
            }

            const btn = document.getElementById('otp-request-btn');
            setLoading(btn, true);

            try {
                const response = await fetch('<?php echo e(route("api.login.request-otp")); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ mobile: mobile })
                });

                const data = await response.json();

                if (data.success) {
                    otpMobile = data.mobile;
                    showOtpVerifyForm(data.mobile);
                    showAlert('OTP sent to your mobile number.', 'success');
                } else {
                    if (data.errors) {
                        Object.keys(data.errors).forEach(field => {
                            showError(`otp-${field}-error`, data.errors[field][0]);
                        });
                    } else {
                        showAlert(data.message || 'Failed to send OTP. Please try again.', 'error');
                    }
                }
            } catch (error) {
                showAlert('An error occurred. Please try again.', 'error');
            } finally {
                setLoading(btn, false);
            }
        }

        // Handle OTP Verify
        async function handleOtpVerify(e) {
            e.preventDefault();
            clearErrors();
            hideAlert();

            const otp = document.getElementById('otp-code').value.trim();
            
            if (!otp || otp.length !== 6) {
                showError('otp-code-error', 'Please enter a valid 6-digit OTP');
                return;
            }

            const btn = document.getElementById('otp-verify-btn');
            setLoading(btn, true);

            try {
                const response = await fetch('<?php echo e(route("api.login.verify-otp")); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ 
                        mobile: otpMobile,
                        otp: otp
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showAlert('Login successful! Redirecting...', 'success');
                    setTimeout(() => {
                        window.location.href = data.redirect_url || '<?php echo e(route("home")); ?>';
                    }, 1000);
                } else {
                    if (data.errors) {
                        Object.keys(data.errors).forEach(field => {
                            showError(`otp-${field}-error`, data.errors[field][0]);
                        });
                    } else {
                        showAlert(data.message || 'Invalid or expired OTP.', 'error');
                    }
                }
            } catch (error) {
                showAlert('An error occurred. Please try again.', 'error');
            } finally {
                setLoading(btn, false);
            }
        }

        // Handle Resend OTP
        async function handleResendOtp() {
            if (!otpMobile) return;

            clearErrors();
            hideAlert();

            const btn = document.getElementById('resend-otp-btn');
            btn.disabled = true;
            btn.textContent = 'Sending...';

            try {
                const response = await fetch('<?php echo e(route("api.login.request-otp")); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ mobile: otpMobile })
                });

                const data = await response.json();

                if (data.success) {
                    showAlert('OTP resent to your mobile number.', 'success');
                } else {
                    showAlert(data.message || 'Failed to resend OTP. Please try again.', 'error');
                }
            } catch (error) {
                showAlert('An error occurred. Please try again.', 'error');
            } finally {
                btn.disabled = false;
                btn.textContent = 'Resend OTP';
            }
        }

        // Handle Password Login
        async function handlePasswordLogin(e) {
            e.preventDefault();
            clearErrors();
            hideAlert();

            const mobile = document.getElementById('password-mobile').value.trim();
            const password = document.getElementById('password-input').value;

            if (!validateMobile(mobile)) {
                showError('password-mobile-error', 'Please enter a valid 10-digit mobile number starting with 6-9');
                return;
            }

            if (!password) {
                showError('password-error', 'Password is required');
                return;
            }

            // Encrypt password
            if (!rsaPublicKey) {
                showAlert('Encryption not ready. Please wait a moment and try again.', 'error');
                return;
            }

            let encryptedPassword;
            try {
                const encrypt = new JSEncrypt();
                encrypt.setPublicKey(rsaPublicKey);
                encryptedPassword = encrypt.encrypt(password);
                
                if (!encryptedPassword) {
                    throw new Error('Encryption failed');
                }
            } catch (error) {
                showAlert('Failed to encrypt password. Please try again.', 'error');
                return;
            }

            const btn = document.getElementById('password-submit-btn');
            setLoading(btn, true);

            try {
                const response = await fetch('<?php echo e(route("api.login.password")); ?>', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({ 
                        mobile: mobile,
                        encrypted_password: encryptedPassword,
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showAlert('Login successful! Redirecting...', 'success');
                    setTimeout(() => {
                        window.location.href = data.redirect_url || '<?php echo e(route("home")); ?>';
                    }, 1000);
                } else {
                    if (data.errors) {
                        Object.keys(data.errors).forEach(field => {
                            showError(`password-${field}-error`, data.errors[field][0]);
                        });
                    } else {
                        showAlert(data.message || 'Login failed. Please try again.', 'error');
                    }
                }
            } catch (error) {
                showAlert('An error occurred. Please try again.', 'error');
            } finally {
                setLoading(btn, false);
            }
        }

        // Helper functions
        function validateMobile(mobile) {
            return /^[6-9]\d{9}$/.test(mobile);
        }

        function showOtpVerifyForm(mobile) {
            document.getElementById('otp-request-form').style.display = 'none';
            document.getElementById('otp-verify-form').style.display = 'block';
            document.getElementById('otp-verify-mobile').textContent = mobile;
            document.getElementById('otp-verify-mobile-input').value = mobile;
            document.getElementById('otp-code').focus();
        }

        function showError(elementId, message) {
            const errorEl = document.getElementById(elementId);
            if (errorEl) {
                errorEl.textContent = message;
                errorEl.classList.add('show');
            }
        }

        function clearErrors() {
            document.querySelectorAll('.error-message').forEach(el => {
                el.classList.remove('show');
                el.textContent = '';
            });
        }

        function showAlert(message, type) {
            const alertEl = document.getElementById('alert-message');
            alertEl.textContent = message;
            alertEl.className = `alert-message alert-${type} show`;
        }

        function hideAlert() {
            document.getElementById('alert-message').classList.remove('show');
        }

        function setLoading(btn, loading) {
            btn.disabled = loading;
            const spinner = btn.querySelector('.loading-spinner');
            if (spinner) {
                spinner.classList.toggle('show', loading);
            }
        }
    })();
    </script>
</body>
</html>
<?php /**PATH /var/www/html/sudheerkt_uat/resources/views/auth/otp-login.blade.php ENDPATH**/ ?>