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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password | Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            height: 100vh;
            display: flex;
            align-items: center;
        }

        .reset-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .btn-primary {
            background: #4e73df;
            border: none;
            padding: 10px;
        }

        .btn-primary:hover {
            background: #2e59d9;
        }

        .requirement-list {
            font-size: 0.8rem;
            list-style: none;
            padding-left: 0;
        }

        .requirement-list li {
            color: #6c757d;
        }

        .requirement-list li.valid {
            color: #198754;
        }

        .requirement-list li.invalid {
            color: #dc3545;
        }
    </style>
</head>

<body>

    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-5 col-lg-4">
                <div class="card reset-card p-4">
                    <div class="text-center mb-4">
                        <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center mb-3"
                            style="width: 60px; height: 60px;">
                            <i class="fas fa-key fa-2x"></i>
                        </div>
                        <h3 class="fw-bold">Forgot Password?</h3>
                        <p class="text-muted small">No worries, we'll send you reset instructions.</p>
                    </div>

                    <div id="responseMsg"></div>

                    <form id="forgotForm">
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Registered Email Address</label>
                            <div class="input-group">
                                <span class="input-group-text bg-white"><i
                                        class="fas fa-envelope text-muted"></i></span>
                                <input type="email" name="email" id="email" class="form-control"
                                    placeholder="admin@example.com" required>
                            </div>
                        </div>
                        <button type="submit" id="sendOtpBtn" class="btn btn-primary w-100 fw-bold">
                            <i class="fas fa-paper-plane me-2"></i>Send Reset Code
                        </button>
                        <div class="text-center mt-3">
                            <a href="login.php" class="text-decoration-none small text-muted"><i
                                    class="fas fa-arrow-left me-1"></i> Back to Login</a>
                        </div>
                    </form>

                    <form id="resetForm" style="display:none;">
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-danger">6-Digit Verification Code</label>
                            <input type="text" name="otp" id="otp"
                                class="form-control text-center fw-bold letter-spacing-2" maxlength="6"
                                placeholder="000000" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label small fw-bold">New Password</label>
                            <div class="input-group">
                                <input type="password" name="new_password" id="new_password" class="form-control"
                                    placeholder="Enter new password" required>
                                <button class="btn btn-outline-secondary" type="button" onclick="togglePass()"><i
                                        class="fas fa-eye"></i></button>
                            </div>
                            <ul class="requirement-list mt-2" id="rules">
                                <li id="rule-length"><i class="fas fa-circle small me-1"></i> At least 8 characters</li>
                                <li id="rule-upper"><i class="fas fa-circle small me-1"></i> One uppercase letter (A-Z)
                                </li>
                                <li id="rule-number"><i class="fas fa-circle small me-1"></i> One number (0-9)</li>
                                <li id="rule-special"><i class="fas fa-circle small me-1"></i> One special character
                                    (!@#$)</li>
                            </ul>
                        </div>

                        <button type="submit" id="resetBtn" class="btn btn-success w-100 fw-bold">
                            <i class="fas fa-check-circle me-2"></i>Update Password
                        </button>
                        <button type="submit" id="sendOtpBtn" class="btn btn-primary">Send Reset Code</button>

                        <button type="button" id="resendBtn" class="btn btn-link" disabled>
                            Resend in <span id="timer">60</span>
                        </button>
                    </form>

                </div>
            </div>
        </div>
    </div>

    <script>
        // Toggle Password Visibility

        // Variable to store the interval globally so we can clear/reset it
        let resendCountdown;

        /**
         * TOGGLE PASSWORD VISIBILITY
         * Switches the input type between 'password' and 'text'
         */
        function togglePass() {
            const passField = document.getElementById('new_password');
            // Simple ternary check to swap types
            passField.type = passField.type === 'password' ? 'text' : 'password';
        }

        /**
         * RESEND TIMER LOGIC
         * Disables the resend button and starts a 60-second countdown
         */
        function startResendTimer() {
            const resendBtn = document.getElementById('resendBtn');
            const timerSpan = document.getElementById('timer');
            let timeLeft = 60; // Standard 60-second wait time

            resendBtn.disabled = true;

            // Clear any existing timer to prevent overlapping intervals
            clearInterval(resendCountdown);

            resendCountdown = setInterval(() => {
                timeLeft--;
                timerSpan.innerText = timeLeft;

                if (timeLeft <= 0) {
                    clearInterval(resendCountdown);
                    resendBtn.disabled = false;
                    resendBtn.innerHTML = '<i class="fas fa-redo me-1"></i> Resend OTP';
                }
            }, 1000);
        }

        /**
         * LIVE PASSWORD VALIDATION
         * Checks requirements (8 chars, uppercase, number, special) as user types
         */
        document.getElementById('new_password').addEventListener('input', function () {
            const val = this.value;

            // Define validation rules using Regular Expressions
            const rules = {
                length: val.length >= 8,
                upper: /[A-Z]/.test(val),
                number: /[0-9]/.test(val),
                special: /[!@#$%^&*]/.test(val)
            };

            // Loop through rules and update UI colors/icons
            for (const key in rules) {
                const el = document.getElementById('rule-' + key);
                if (rules[key]) {
                    el.classList.remove('text-muted', 'text-danger');
                    el.classList.add('text-success'); // Green if valid
                    el.querySelector('i').classList.replace('fa-circle', 'fa-check-circle');
                } else {
                    el.classList.remove('text-success');
                    el.classList.add('text-danger'); // Red if invalid
                    el.querySelector('i').classList.replace('fa-check-circle', 'fa-circle');
                }
            }
        });

        /**
         * STEP 1: SEND OTP
         * Calls API to verify email and send reset code via SMTP
         */
        document.getElementById('forgotForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = document.getElementById('sendOtpBtn');
            const msgDiv = document.getElementById('responseMsg');

            // UI state: Loading
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Sending...';

            try {
                const resp = await fetch('api/adminLogin/forgot_password_send.php', {
                    method: 'POST',
                    body: new FormData(e.target)
                });
                const res = await resp.json();

                if (res.status === 'success') {
                    msgDiv.innerHTML = `<div class="alert alert-info small">${res.message}</div>`;
                    // Switch views: Hide email form, show OTP/Password form
                    document.getElementById('forgotForm').style.display = 'none';
                    document.getElementById('resetForm').style.display = 'block';
                    startResendTimer(); // Trigger countdown for the resend link
                } else {
                    msgDiv.innerHTML = `<div class="alert alert-danger small">${res.message}</div>`;
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fas fa-paper-plane me-2"></i>Send Reset Code';
                }
            } catch (err) {
                msgDiv.innerHTML = `<div class="alert alert-danger small">Network error. Check connection.</div>`;
                btn.disabled = false;
            }
        });

        /**
         * STEP 2: VERIFY & RESET
         * Validates OTP and updates password in the database
         */
        document.getElementById('resetForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = document.getElementById('resetBtn');
            const msgDiv = document.getElementById('responseMsg');

            // Ensure all rules are green before submitting
            const invalidRules = document.querySelectorAll('.requirement-list .text-danger');
            if (invalidRules.length > 0) {
                msgDiv.innerHTML = `<div class="alert alert-warning small">Please meet all password requirements first.</div>`;
                return;
            }

            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Updating...';

            try {
                const resp = await fetch('api/adminLogin/forgot_password_reset.php', {
                    method: 'POST',
                    body: new FormData(e.target)
                });
                const res = await resp.json();

                if (res.status === 'success') {
                    msgDiv.innerHTML = `<div class="alert alert-success small">${res.message}</div>`;
                    // Success: Redirect to login page
                    setTimeout(() => window.location.href = 'login.php', 3000);
                } else {
                    msgDiv.innerHTML = `<div class="alert alert-danger small">${res.message}</div>`;
                    btn.disabled = false;
                    btn.innerHTML = 'Update Password';
                }
            } catch (err) {
                msgDiv.innerHTML = `<div class="alert alert-danger small">Server error occurred.</div>`;
                btn.disabled = false;
            }
        });

        /**
         * RESEND BUTTON CLICK
         * Allows user to request a new code if the timer is finished
         */
        document.getElementById('resendBtn').addEventListener('click', async () => {
            const email = document.getElementById('email').value;
            const resendBtn = document.getElementById('resendBtn');

            resendBtn.innerHTML = "Resending...";
            resendBtn.disabled = true;

            const fd = new FormData();
            fd.append('email', email);

            try {
                const resp = await fetch('api/adminLogin/forgot_password_send.php', {
                    method: 'POST',
                    body: fd
                });
                const res = await resp.json();

                alert(res.message);
                if (res.status === 'success') {
                    startResendTimer(); // Reset the 60s clock
                } else {
                    resendBtn.disabled = false;
                }
            } catch (err) {
                alert("Network error.");
            }
        });
    </script>

</body>

</html>