<?php
// login.php
// Handles user login authentication using OTP.

// Ensure session is started at the very beginning
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once 'config/database.php';
require_once 'includes/auth_utils.php'; // Needed for check_persistent_login
check_persistent_login(); // Crucial: Check for remembered device before proceeding

$message = ''; // Message for success/error feedback.
$is_error = false; // Flag for message styling.

// Check if the user is already logged in. If so, redirect to their dashboard.
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
    if ($_SESSION['user_role'] === 'student') {
        header("Location: index.php?page=student_dashboard");
    } elseif ($_SESSION['user_role'] === 'admin' || $_SESSION['user_role'] === 'instructor') {
        header("Location: index.php?page=admin_landing");
    } else {
        header("Location: index.php?page=home");
    }
    exit(); // Crucial: Stop script execution after redirect!
}
?>
<div class="flex items-center justify-center min-h-screen bg-gray-100">
    <div class="bg-white p-8 rounded-lg shadow-xl w-full max-w-md">
        <h2 class="text-3xl font-extrabold mb-6 text-center text-gray-800">Welcome Back (OTP Login)</h2>

        <?php if (!empty($message)): ?>
            <div class="mb-4 p-3 rounded-md text-center font-medium
                <?php echo $is_error ? 'bg-red-100 text-red-700 border border-red-300' : 'bg-green-100 text-green-700 border border-green-300'; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <p class="mt-4 text-center text-sm text-gray-500">
            <span class="font-bold text-blue-600">First-time users:</span> Enter your email address below to receive your one-time verification code.
        </p>


        <form id="otpLoginForm" class="space-y-6">
            <div>
                <label for="username_email" class="block text-gray-700 text-sm font-semibold mb-2">Username or Email:</label>
                <input type="text" id="username_email" name="username_email" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-150"
                       placeholder="Enter your username or email">
            </div>

            <button type="button" id="sendOtpButton"
                    class="w-full py-2.5 px-4 bg-blue-600 text-white font-bold rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-4 focus:ring-blue-300 transition duration-300 ease-in-out transform hover:scale-[1.01]">
                Send Verification Code
            </button>

            <div id="otpInputSection" class="hidden space-y-6 pt-4 border-t border-gray-200">
                <div>
                    <label for="otp" class="block text-gray-700 text-sm font-semibold mb-2">Enter Verification Code:</label>
                    <input type="text" id="otp" name="otp" required 
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg text-lg text-center 
                                  focus:outline-none focus:ring-2 focus:ring-green-500 transition duration-150"
                           placeholder="Enter the code from your email">
                </div>
                
                <div class="flex items-center">
                    <input type="checkbox" id="remember_device" name="remember_device" 
                           class="h-4 w-4 text-green-600 border-gray-300 rounded focus:ring-green-500">
                    <label for="remember_device" class="ml-2 block text-sm text-gray-700">
                        Remember this device for 7 days (Only for verified accounts)
                    </label>
                </div>
                
                <button type="submit" id="verifyOtpButton"
                        class="w-full py-2.5 px-4 bg-green-600 text-white font-bold rounded-lg hover:bg-green-700 focus:outline-none focus:ring-4 focus:ring-green-300 transition duration-300 ease-in-out transform hover:scale-[1.01]">
                    Login
                </button>
            </div>
            <div id="loginMessage" class="mt-4 text-center text-sm font-semibold"></div>
        </form>

        </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const sendOtpButton = document.getElementById('sendOtpButton');
        const otpInputSection = document.getElementById('otpInputSection');
        const loginMessageDiv = document.getElementById('loginMessage');
        const usernameEmailInput = document.getElementById('username_email');
        const otpInput = document.getElementById('otp');
        const otpLoginForm = document.getElementById('otpLoginForm');
        const rememberDeviceCheckbox = document.getElementById('remember_device'); 

        // Function to display messages
        function displayMessage(message, isError = false) {
            loginMessageDiv.textContent = message;
            // Reset classes and apply base styling
            loginMessageDiv.className = 'mt-4 text-center text-sm font-semibold';
            if (isError) {
                loginMessageDiv.classList.add('text-red-600');
            } else {
                loginMessageDiv.classList.add('text-green-600');
            }
        }

        // Send OTP handler
        sendOtpButton.addEventListener('click', async function() {
            const identifier = usernameEmailInput.value.trim();
            if (identifier === '') {
                displayMessage('Please enter your username or email.', true);
                return;
            }

            displayMessage('Sending code...', false);
            sendOtpButton.disabled = true;

            try {
                const response = await fetch('api/send_otp.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ identifier: identifier })
                });

                const data = await response.json();

                if (data.success) {
                    displayMessage(data.message);
                    otpInputSection.classList.remove('hidden');
                    usernameEmailInput.disabled = true; 
                    
                    // 💡 CRITICAL: Adjust OTP input based on verification status
                    const isFirstLogin = data.data && data.data.is_first_login;
                    
                    if (isFirstLogin) {
                        // First-time login: Long alphanumeric/hex code
                        otpInput.setAttribute('maxlength', '64'); // Allow long hex
                        otpInput.style.letterSpacing = 'normal'; 
                        otpInput.setAttribute('placeholder', 'Enter the full verification code');
                        // Hide "Remember device" for first-time login
                        rememberDeviceCheckbox.closest('.flex').style.display = 'none';
                    } else {
                        // Regular login: 6-digit numeric OTP
                        otpInput.setAttribute('maxlength', '6');
                        otpInput.style.letterSpacing = '0.5em'; 
                        otpInput.setAttribute('pattern', '\\d{6}'); // Enforce 6 digits
                        otpInput.setAttribute('placeholder', '●●●●●●');
                        rememberDeviceCheckbox.closest('.flex').style.display = 'flex';
                    }
                    
                    otpInput.value = ''; // Clear previous value
                    otpInput.focus();

                } else {
                    displayMessage(data.message || 'Failed to send verification code. Please try again.', true);
                }
            } catch (error) {
                console.error('Error sending OTP:', error);
                displayMessage('Network error or server issue. Could not send verification code.', true);
            } finally {
                sendOtpButton.disabled = false;
            }
        });

        // Verify OTP and Login handler
        otpLoginForm.addEventListener('submit', async function(event) {
            event.preventDefault(); // Prevent default form submission

            const identifier = usernameEmailInput.value.trim();
            const otp = otpInput.value.trim();
            const rememberDevice = rememberDeviceCheckbox.checked; 

            if (identifier === '' || otp === '') {
                displayMessage('Please enter both your username/email and the code.', true);
                return;
            }

            displayMessage('Verifying code...', false);
            otpLoginForm.querySelector('button[type="submit"]').disabled = true;

            try {
                const response = await fetch('api/verify_otp.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        identifier: identifier, 
                        otp: otp,
                        remember_device: rememberDevice 
                    })
                });

                const data = await response.json();

                if (data.success) {
                    displayMessage(data.message || 'Login successful! Redirecting...', false);
                    window.location.href = data.redirect || 'index.php?page=home'; 
                } else {
                    displayMessage(data.message || 'Verification failed. Please try again.', true);
                }
            } catch (error) {
                console.error('Error verifying OTP:', error);
                displayMessage('Network error or server issue during verification.', true);
            } finally {
                otpLoginForm.querySelector('button[type="submit"]').disabled = false;
            }
        });
    });
</script>