<?php
// Web portal: login only. Create account is done in the app only.
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NROI Portal Login</title>
    <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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/loader.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="icon" type="image/png" href="assets/images/nroi_logo.png">
</head>

<body>
    <?php include 'includes/loader.php'; ?>

    <!-- Floating Side Logos -->
    <div class="floating-logo-container left">
        <img src="assets/images/nroi_logo.png" alt="NROI Logo" class="logo-img-floating">
    </div>
    <div class="floating-logo-container right">
        <img src="assets/images/ppsa_logo.png" alt="PPSA Logo" class="logo-img-floating">
    </div>

    <div class="container" style="max-width: 560px;">
        <!-- Mobile Logos -->
        <div class="mobile-logos" style="display:none;">
            <img src="assets/images/nroi_logo.png" alt="NROI Logo" class="mobile-logo-img">
            <img src="assets/images/ppsa_logo.png" alt="PPSA Logo" class="mobile-logo-img">
        </div>

        <h2><b>National Range Officers Institute</b></h2>
        <div class="subtitle">Security Authentication</div>


        <!-- Login Alert Indicator -->
        <div id="loginIndicator" class="login-indicator">
            <i id="indicatorIcon" class="fas fa-info-circle"></i>
            <span id="indicatorMessage"></span>
        </div>

        <form id="unifiedLoginForm">
            <div class="form-group">
                <label>NROI ID / Username</label>
                <input type="text" name="identity" required placeholder="Enter NROI ID or Username">
            </div>

            <div class="form-group" style="margin-bottom: 25px;">
                <label>Password</label>
                <div class="password-wrapper">
                    <input type="password" name="password" id="loginPassword" required
                        placeholder="Enter your password">
                    <i class="fas fa-eye toggle-password" id="togglePassword"></i>
                </div>
                <div style="text-align: right; margin-top: 10px;">
                    <a href="forgot_password.php"
                        style="color: #64748b; font-size: 13px; text-decoration: none; font-weight: 600;">Forgot
                        Password?</a>
                </div>
            </div>

            <input type="hidden" name="login_source" value="web">
            <button type="submit" class="btn-primary" style="margin-top: 10px;">Login</button>
        </form>
    </div>

    <script src="assets/js/loader.js"></script>
    <script>
        // Password Toggle
        const togglePassword = document.getElementById('togglePassword');
        const passwordInput = document.getElementById('loginPassword');

        togglePassword.addEventListener('click', function () {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            this.classList.toggle('fa-eye');
            this.classList.toggle('fa-eye-slash');
        });

        // Form Submission
        document.getElementById('unifiedLoginForm').addEventListener('submit', function (e) {
            e.preventDefault();

            const indicator = document.getElementById('loginIndicator');
            const icon = document.getElementById('indicatorIcon');
            const msgSpan = document.getElementById('indicatorMessage');

            // Reset indicator
            indicator.style.display = 'none';
            indicator.className = 'login-indicator';

            const formData = new FormData(this);
            const btn = this.querySelector('button');
            const originalText = btn.textContent;

            btn.textContent = 'Authenticating...';
            btn.disabled = true;

            const apiUrl = (window.location.origin + window.location.pathname).replace(/\/?index\.php\/?$/, '') + '/api/login.php';
            fetch(apiUrl, {
                method: 'POST',
                body: formData
            })
                .then(r => {
                    if (!r.ok) throw new Error('Server error ' + r.status);
                    return r.json();
                })
                .then(data => {
                    btn.textContent = originalText;
                    btn.disabled = false;

                    if (data.success) {
                        indicator.style.display = 'flex';
                        indicator.classList.add('indicator-success');
                        icon.className = 'fas fa-check-circle';
                        msgSpan.textContent = data.message || 'Access Granted. Redirecting...';

                        setTimeout(() => {
                            const role = (data.role || '').toUpperCase().replace(/\./g, '');

                            if (role === 'ADMIN') {
                                window.location.href = 'admin/dashboard.php';
                            } else if (['AC', 'AAC', 'NROI', 'PPSA'].includes(role)) {
                                window.location.href = 'officer/dashboard.php';
                            } else {
                                // Fallback: should not be reached with proper API whitelist
                                indicator.style.display = 'flex';
                                indicator.className = 'login-indicator indicator-error';
                                icon.className = 'fas fa-shield-halved';
                                msgSpan.textContent = 'Unauthorized Access';
                            }
                        }, 1200);
                    } else {
                        indicator.style.display = 'flex';
                        msgSpan.textContent = data.message;

                        if (data.code === 'pending') {
                            indicator.classList.add('indicator-warning');
                            icon.className = 'fas fa-clock';
                        } else if (data.code === 'email_not_confirmed') {
                            indicator.classList.add('indicator-warning');
                            icon.className = 'fas fa-envelope-open-text';
                        } else if (data.code === 'unauthorized') {
                            indicator.classList.add('indicator-error');
                            icon.className = 'fas fa-shield-halved';
                        } else if (data.code === 'deactivated') {
                            indicator.classList.add('indicator-error');
                            icon.className = 'fas fa-ban';
                        } else if (data.code === 'not_found') {
                            indicator.classList.add('indicator-error');
                            icon.className = 'fas fa-search';
                        } else if (data.code === 'invalid_password') {
                            indicator.classList.add('indicator-error');
                            icon.className = 'fas fa-key';
                        } else {
                            indicator.classList.add('indicator-error');
                            icon.className = 'fas fa-exclamation-circle';
                        }
                    }
                })
                .catch(err => {
                    console.error(err);
                    btn.textContent = originalText;
                    btn.disabled = false;

                    indicator.style.display = 'flex';
                    indicator.classList.add('indicator-error');
                    icon.className = 'fas fa-wifi';
                    msgSpan.textContent = (err.message && err.message.startsWith('Server error')) ? err.message : 'Connection error. Please try again.';
                });
        });
    </script>

</body>

</html>