// A. Real-time Password Check
document.getElementById('old_password').addEventListener('blur', async function () {
    const password = this.value;
    const errorDiv = document.getElementById('passwordError');

    if (password.length < 1) return;

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

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

    if (res.status === 'error') {
        this.classList.add('is-invalid');
        errorDiv.innerText = res.message;
        errorDiv.style.display = 'block';
    } else {
        this.classList.remove('is-invalid');
        this.classList.add('is-valid');
        errorDiv.style.display = 'none';
    }
});

//============ for new password ================

document.getElementById('new_password').addEventListener('input', function () {
    const newPass = this.value;
    const errorDiv = document.getElementById('newPassError');
    const regex = /^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$/;

    if (newPass.length > 0 && !regex.test(newPass)) {
        this.classList.add('is-invalid');
        errorDiv.innerText = "Must be 8+ chars, 1 Uppercase, 1 Number, 1 Special character.";
        errorDiv.style.display = 'block';
    } else {
        this.classList.remove('is-invalid');
        this.classList.add('is-valid');
        errorDiv.style.display = 'none';
    }
});
// B. Send OTP (Only if password was valid)
async function sendUpdateOTP() {
    const btn = document.getElementById('otpBtn');
    const oldPassInput = document.querySelector('input[name="old_password"]');
    const newPassInput = document.getElementById('new_password');

    // 1. Check if Current Password is empty
    if (!oldPassInput.value) {
        alert("Please enter your current password first.");
        oldPassInput.focus();
        return;
    }

    // 2. CHECK FOR ERRORS BEFORE SENDING
    // If the new password field has the 'is-invalid' class, stop!
    if (newPassInput.value.length > 0 && newPassInput.classList.contains('is-invalid')) {
        alert("Please fix the New Password requirements before requesting an OTP.");
        newPassInput.focus();
        return;
    }

    btn.disabled = true;
    btn.innerHTML = 'Sending...';

    const formData = new FormData();
    formData.append('old_password', oldPassInput.value);

    try {
        const response = await fetch('api/adminLogin/send_update_otp.php', {
            method: 'POST',
            body: formData
        });

        const res = await response.json();
        if (res.status === 'success') {
            alert(res.message);
        } else {
            alert(res.message);
            btn.disabled = false;
        }
    } catch (error) {
        alert("Connection error.");
        btn.disabled = false;
    } finally {
        btn.innerHTML = 'Send OTP';
    }
}

// 3. FINAL FORM SUBMISSION
// Updates Username, Email, and Password after OTP verification
document.getElementById('secureUpdateForm').addEventListener('submit', async (e) => {
    e.preventDefault();

    const saveBtn = document.getElementById('saveBtn');
    const msgDiv = document.getElementById('responseMsg');
    const otpInput = document.getElementById('update_otp').value;
    const newPass = document.querySelector('input[name="new_password"]').value;

    // 1. Validate Password Strength (Only if a new password is provided)
    if (newPass.length > 0) {
        /**
         * Regex Breakdown:
         * ^(?=.*[A-Z])     -> Starts with at least 1 uppercase letter
         * (?=.*[0-9])      -> At least 1 number
         * (?=.*[!@#$%^&*]) -> At least 1 special character
         * .{8,}            -> Minimum 8 characters in total
         */
        const passwordRegex = /^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$/;

        if (!passwordRegex.test(newPass)) {
            msgDiv.innerHTML = `
                <div class="alert alert-danger">
                    <strong>Weak Password!</strong> Must be 8+ characters with at least one uppercase letter, one number, and one special character (!@#$%^&*).
                </div>`;
            return; // STOP submission
        }
    }

    // 2. Validate OTP length
    if (otpInput.length < 6) {
        msgDiv.innerHTML = `<div class="alert alert-warning">Please enter the 6-digit OTP code.</div>`;
        return;
    }

    // Start UI Loading State
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Processing...';

    const formData = new FormData(e.target);

    try {
        const resp = await fetch('api/adminLogin/update_profile_action.php', {
            method: 'POST',
            body: formData
        });

        const res = await resp.json();

        if (res.status === 'success') {
            msgDiv.innerHTML = `<div class="alert alert-success">${res.message}</div>`;
            // Refresh page after 2 seconds to show updated info
            setTimeout(() => {
               window.location.href = 'logout.php';
            }, 2500);
        } else {
            msgDiv.innerHTML = `<div class="alert alert-danger">${res.message}</div>`;
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="fas fa-user-check me-2"></i>Verify & Save Changes';
        }
    } catch (err) {
        msgDiv.innerHTML = `<div class="alert alert-danger">Critical connection error.</div>`;
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fas fa-user-check me-2"></i>Verify & Save Changes';
    }
});