<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - NROI Portal</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">
    <style>
        .timer-container {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            margin: 20px 0;
        }

        .timer-text {
            font-size: 32px;
            font-weight: 800;
            color: #1e3a8a;
            font-family: monospace;
        }

        .timer-label {
            font-size: 11px;
            font-weight: 700;
            color: #64748b;
            letter-spacing: 1px;
            text-transform: uppercase;
        }

        .step-container {
            display: none;
        }

        .step-active {
            display: block;
        }

        .resend-link {
            font-size: 13px;
            color: #3b82f6;
            cursor: pointer;
            text-decoration: none;
            font-weight: 600;
        }

        .resend-link.disabled {
            color: #cbd5e1;
            cursor: not-allowed;
        }

        input:disabled {
            background-color: #f1f5f9;
            cursor: not-allowed;
        }
    </style>
</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;">
        <div class="header-section" style="text-align: center; margin-bottom: 30px;">
            <i class="fas fa-lock-open" style="font-size: 40px; color: #1e3a8a; margin-bottom: 15px;"></i>
            <h2 style="margin: 0; color: #1e3a8a;"><b>Account Recovery</b></h2>
            <div id="stepSubtitle" class="subtitle">Enter your NROI ID and registered email</div>
        </div>

        <!-- Alert Indicator -->
        <div id="alertIndicator" class="login-indicator" style="display: none;">
            <i id="indicatorIcon" class="fas fa-info-circle"></i>
            <span id="indicatorMessage"></span>
        </div>

        <!-- STEP 1: Identification -->
        <div id="step1" class="step-container step-active">
            <form id="idForm">
                <div class="form-group">
                    <label>NROI ID / Username</label>
                    <input type="text" id="nroi_id" required placeholder="Enter NROI ID or Username">
                </div>
                <div class="form-group">
                    <label>Email Address</label>
                    <input type="email" id="email" required placeholder="Enter registered email">
                </div>
                <button type="submit" class="btn-primary" style="margin-top: 20px;">Send Recovery Code</button>
                <div style="text-align: center; margin-top: 20px;">
                    <a href="index.php" style="color: #64748b; font-size: 14px; text-decoration: none;"><i
                            class="fas fa-arrow-left"></i> Back to Login</a>
                </div>
            </form>
        </div>

        <!-- STEP 2: OTP Verification -->
        <div id="step2" class="step-container">
            <div class="timer-container">
                <div class="timer-label" id="timerLabel">OTP Expires In</div>
                <div class="timer-text" id="timerDisplay">10:00</div>
            </div>

            <form id="otpForm">
                <div class="form-group">
                    <label>Verification Code</label>
                    <input type="text" id="otp" required maxlength="6" placeholder="Enter 6-digit code"
                        style="text-align: center; letter-spacing: 8px; font-size: 20px; font-weight: bold;">
                </div>
                <button type="submit" class="btn-primary" style="margin-top: 10px;">Verify Code</button>
                <div style="text-align: center; margin-top: 15px;">
                    <span id="resendBtn" class="resend-link disabled">Resend Code</span>
                </div>
            </form>
        </div>

        <!-- STEP 3: Password Update -->
        <div id="step3" class="step-container">
            <form id="resetForm">
                <div class="form-group">
                    <label>New Password</label>
                    <div class="password-wrapper">
                        <input type="password" id="new_password" required placeholder="Minimum 6 characters">
                        <i class="fas fa-eye toggle-password" data-target="new_password"></i>
                    </div>
                </div>
                <div class="form-group">
                    <label>Confirm Password</label>
                    <div class="password-wrapper">
                        <input type="password" id="confirm_password" required placeholder="Re-enter new password">
                        <i class="fas fa-eye toggle-password" data-target="confirm_password"></i>
                    </div>
                </div>
                <button type="submit" class="btn-primary" style="margin-top: 20px;">Update Password</button>
            </form>
        </div>
    </div>

    <script src="assets/js/loader.js"></script>
    <script>
        let currentStep = 1;
        let countdownTimer;
        let secondsRemaining = 0;
        let savedNroiId = '';
        let savedEmail = '';

        const forms = {
            id: document.getElementById('idForm'),
            otp: document.getElementById('otpForm'),
            reset: document.getElementById('resetForm')
        };

        const steps = {
            1: document.getElementById('step1'),
            2: document.getElementById('step2'),
            3: document.getElementById('step3')
        };

        const indicator = document.getElementById('alertIndicator');
        const icon = document.getElementById('indicatorIcon');
        const msgSpan = document.getElementById('indicatorMessage');
        const subtitle = document.getElementById('stepSubtitle');

        function showAlert(msg, type = 'error') {
            indicator.style.display = 'flex';
            indicator.className = 'login-indicator indicator-' + type;
            msgSpan.textContent = msg;
            icon.className = type === 'success' ? 'fas fa-check-circle' : 'fas fa-exclamation-circle';
        }

        function hideAlert() {
            indicator.style.display = 'none';
        }

        function switchStep(step) {
            Object.values(steps).forEach(s => s.classList.remove('step-active'));
            steps[step].classList.add('step-active');
            currentStep = step;

            if (step === 1) {
                subtitle.textContent = 'Enter your NROI ID and registered email';
            } else if (step === 2) {
                subtitle.textContent = 'Enter the 6-digit code sent to your email';
            } else if (step === 3) {
                subtitle.textContent = 'Create a secure new password for your account';
            }
        }

        function formatTime(seconds) {
            const m = Math.floor(seconds / 60);
            const s = seconds % 60;
            return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
        }

        function startTimer(seconds) {
            clearInterval(countdownTimer);
            secondsRemaining = seconds;
            const display = document.getElementById('timerDisplay');
            const label = document.getElementById('timerLabel');
            const resend = document.getElementById('resendBtn');

            display.textContent = formatTime(secondsRemaining);
            label.textContent = 'OTP Expires In';
            label.style.color = '#64748b';
            display.style.color = '#1e3a8a';
            resend.classList.add('disabled');

            countdownTimer = setInterval(() => {
                secondsRemaining--;
                display.textContent = formatTime(secondsRemaining);

                if (secondsRemaining <= 10) {
                    display.style.color = '#ef4444';
                }

                if (secondsRemaining <= 0) {
                    clearInterval(countdownTimer);
                    label.textContent = 'OTP EXPIRED';
                    label.style.color = '#ef4444';
                    resend.classList.remove('disabled');
                }
            }, 1000);
        }

        // STEP 1 Submission
        forms.id.addEventListener('submit', function (e) {
            e.preventDefault();
            const btn = this.querySelector('button');
            const nroiId = document.getElementById('nroi_id').value;
            const email = document.getElementById('email').value;

            btn.disabled = true;
            btn.textContent = 'Processing...';
            hideAlert();

            fetch('api/forgot_password.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ nroi_id: nroiId, email: email })
            })
                .then(r => r.json())
                .then(data => {
                    btn.disabled = false;
                    btn.textContent = 'Send Recovery Code';

                    if (data.success) {
                        savedNroiId = nroiId;
                        savedEmail = email;
                        localStorage.setItem('web_otp_expiry', data.expires_at);
                        localStorage.setItem('web_otp_nroi_id', nroiId);
                        localStorage.setItem('web_otp_email', email);

                        switchStep(2);
                        const expiry = new Date(data.expires_at).getTime();
                        const now = new Date().getTime();
                        startTimer(Math.floor((expiry - now) / 1000));
                        showAlert('OTP sent successfully to your email.', 'success');
                    } else {
                        showAlert(data.message);
                    }
                })
                .catch(err => {
                    btn.disabled = false;
                    btn.textContent = 'Send Recovery Code';
                    showAlert('Connection error. Please try again.');
                });
        });

        // STEP 2 Verification
        forms.otp.addEventListener('submit', function (e) {
            e.preventDefault();
            const btn = this.querySelector('button');
            const otp = document.getElementById('otp').value;

            if (otp.length !== 6) return showAlert('Please enter a 6-digit code');

            btn.disabled = true;
            btn.textContent = 'Verifying...';
            hideAlert();

            fetch('api/verify_otp.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ nroi_id: savedNroiId, otp: otp })
            })
                .then(r => r.json())
                .then(data => {
                    btn.disabled = false;
                    btn.textContent = 'Verify Code';

                    if (data.success) {
                        switchStep(3);
                        showAlert('Code verified. Please set your new password.', 'success');
                    } else {
                        showAlert(data.message);
                    }
                })
                .catch(err => {
                    btn.disabled = false;
                    btn.textContent = 'Verify Code';
                    showAlert('Connection error. Please try again.');
                });
        });

        // Resend OTP
        document.getElementById('resendBtn').addEventListener('click', function () {
            if (this.classList.contains('disabled')) return;

            const btn = document.querySelector('#idForm button');
            this.classList.add('disabled');

            fetch('api/forgot_password.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ nroi_id: savedNroiId, email: savedEmail })
            })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        const expiry = new Date(data.expires_at).getTime();
                        const now = new Date().getTime();
                        startTimer(Math.floor((expiry - now) / 1000));
                        showAlert('A new recovery code has been sent.', 'success');
                    } else {
                        this.classList.remove('disabled');
                        showAlert(data.message);
                    }
                });
        });

        // STEP 3 Reset
        forms.reset.addEventListener('submit', function (e) {
            e.preventDefault();
            const btn = this.querySelector('button');
            const pass = document.getElementById('new_password').value;
            const confirm = document.getElementById('confirm_password').value;
            const otp = document.getElementById('otp').value;

            if (pass.length < 6) return showAlert('Password must be at least 6 characters');
            if (pass !== confirm) return showAlert('Passwords do not match');

            btn.disabled = true;
            btn.textContent = 'Updating...';
            hideAlert();

            fetch('api/reset_password.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    nroi_id: savedNroiId,
                    otp: otp,
                    new_password: pass
                })
            })
                .then(r => r.json())
                .then(data => {
                    btn.disabled = false;
                    btn.textContent = 'Update Password';

                    if (data.success) {
                        localStorage.removeItem('web_otp_expiry');
                        localStorage.removeItem('web_otp_nroi_id');
                        showAlert(data.message + ' Redirecting to login...', 'success');
                        setTimeout(() => window.location.href = 'index.php', 2500);
                    } else {
                        showAlert(data.message);
                    }
                })
                .catch(err => {
                    btn.disabled = false;
                    btn.textContent = 'Update Password';
                    showAlert('Connection error. Please try again.');
                });
        });

        // Password Toggles
        document.querySelectorAll('.toggle-password').forEach(icon => {
            icon.addEventListener('click', function () {
                const targetId = this.getAttribute('data-target');
                const input = document.getElementById(targetId);
                const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
                input.setAttribute('type', type);
                this.classList.toggle('fa-eye');
                this.classList.toggle('fa-eye-slash');
            });
        });

        // Check for existing session
        window.onload = () => {
            const expiryStr = localStorage.getItem('web_otp_expiry');
            const savedId = localStorage.getItem('web_otp_nroi_id');
            const savedMail = localStorage.getItem('web_otp_email');

            if (expiryStr && savedId) {
                const expiry = new Date(expiryStr).getTime();
                const now = new Date().getTime();

                if (expiry > now) {
                    savedNroiId = savedId;
                    savedEmail = savedMail || '';
                    // We can still proceed with verification
                    switchStep(2);
                    startTimer(Math.floor((expiry - now) / 1000));
                    showAlert('Resuming your recovery session.', 'info');
                } else {
                    localStorage.removeItem('web_otp_expiry');
                    localStorage.removeItem('web_otp_nroi_id');
                }
            }
        };
    </script>
</body>

</html>