<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lupa Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        /* Re-use atau sesuaikan CSS Anda */
        body {
            font-family: 'Poppins', sans-serif;
            background: white;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 90vh;
            margin: 0;
            padding: 20px;
        }
        .form-container {
            background-color: #FFFFFF;
            border-radius: 15px;
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
            padding: 40px;
            max-width: 450px;
            width: 100%;
            text-align: center;
        }
        .form-container h2 {
            color: #2c3e50;
            margin-bottom: 30px;
            font-weight: 700;
        }
        .form-control {
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 20px;
            border: 1px solid #ced4da;
        }
        .form-control:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }
        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
            border-radius: 8px;
            padding: 12px 20px;
            font-size: 1.1em;
            font-weight: 600;
            width: 100%;
            transition: background-color 0.3s ease;
        }
        .btn-primary:hover {
            background-color: #0056b3;
            border-color: #0056b3;
        }
        .message-area {
            margin-top: 15px;
            padding: 10px;
            border-radius: 8px;
            font-size: 0.95em;
            text-align: left;
            word-wrap: break-word;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .success-message {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .hidden {
            display: none;
        }
        .back-to-login {
            margin-top: 20px;
            font-size: 0.9em;
        }
        .back-to-login a {
            color: #007bff;
            text-decoration: none;
        }
        .back-to-login a:hover {
            text-decoration: underline;
        }
                /* Modifikasi untuk tombol utama (btn-primary) */
        .btn-primary {
            /* Hapus background-color dan border-color yang lama jika ada */
            background: linear-gradient(135deg, #4dab25, #024d52); /* Gradasi baru */
            border: none; /* Hapus border default Bootstrap agar gradasi terlihat penuh */
            color: #FFFFFF; /* Pastikan teks tetap terlihat jelas */
            border-radius: 8px;
            padding: 12px 20px;
            font-size: 1.1em;
            font-weight: 600;
            width: 100%;
            transition: background 0.3s ease; /* Transisi agar halus saat hover */
        }
        .btn-primary:hover {
            /* Sesuaikan efek hover jika diinginkan, misalnya gradasi sedikit lebih gelap */
            background: linear-gradient(135deg, #3a8c1f, #013a3e); /* Gradasi sedikit berbeda saat hover */
            border-color: none; /* Pastikan tidak ada border yang muncul saat hover */
        }
    </style>
</head>
<body>
    <div class="form-container">
        <h2>Lupa Password</h2>

        <form id="forgotPasswordStage1">
            <div class="mb-3">
                <input type="tel" class="form-control" id="contactInfo" placeholder="Nomor Telepon (contoh: 6281234567890)" required>
            </div>
            <button type="submit" class="btn btn-primary" id="sendResetOtpBtn">Kirim Kode Verifikasi</button>
            <div id="forgotPasswordMessage1" class="message-area hidden"></div>
        </form>

        <form id="forgotPasswordStage2" class="hidden">
            <p class="text-center" style="font-size: 0.9em; color: #555; margin-bottom: 25px;">Kode verifikasi telah dikirim ke WhatsApp Anda. Masukkan kode dan password baru.</p>
            <div class="mb-3">
                <input type="text" class="form-control" id="otpCode" placeholder="Kode OTP" maxlength="6" required>
            </div>
            <div class="mb-3">
                <input type="password" class="form-control" id="newPassword" placeholder="Password Baru" required>
            </div>
            <div class="mb-3">
                <input type="password" class="form-control" id="confirmNewPassword" placeholder="Konfirmasi Password Baru" required>
            </div>
            <button type="submit" class="btn btn-primary" id="verifyOtpBtn">Verifikasi & Atur Ulang</button>
            <button type="button" class="btn btn-link mt-2" id="resendOtpBtn">Kirim Ulang Kode (dalam <span id="countdown">60</span>s)</button>
            <div id="forgotPasswordMessage2" class="message-area hidden"></div>
        </form>

        <div class="back-to-login">
            Ingat password Anda? <a href="login.php">Login di sini</a>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const forgotPasswordStage1 = document.getElementById('forgotPasswordStage1');
            const forgotPasswordStage2 = document.getElementById('forgotPasswordStage2');
            const contactInfoInput = document.getElementById('contactInfo');
            const sendResetOtpBtn = document.getElementById('sendResetOtpBtn');
            const forgotPasswordMessage1 = document.getElementById('forgotPasswordMessage1');
            const otpCodeInput = document.getElementById('otpCode');
            const newPasswordInput = document.getElementById('newPassword');
            const confirmNewPasswordInput = document.getElementById('confirmNewPassword');
            const verifyOtpBtn = document.getElementById('verifyOtpBtn');
            const resendOtpBtn = document.getElementById('resendOtpBtn');
            const countdownSpan = document.getElementById('countdown');
            const forgotPasswordMessage2 = document.getElementById('forgotPasswordMessage2');

            let userPhoneNumberTemp = ''; // Untuk menyimpan nomor telepon sementara antar tahap
            let countdownInterval;

            function showMessage(element, message, type) {
                element.innerHTML = message;
                element.className = 'message-area ' + (type === 'success' ? 'success-message' : 'error-message');
                element.classList.remove('hidden');
            }

            function hideMessage(element) {
                element.innerHTML = '';
                element.className = 'message-area hidden';
            }

            function startCountdown(duration) {
                let timer = duration;
                resendOtpBtn.disabled = true; // Nonaktifkan tombol kirim ulang
                countdownSpan.textContent = timer;

                countdownInterval = setInterval(() => {
                    timer--;
                    countdownSpan.textContent = timer;
                    if (timer <= 0) {
                        clearInterval(countdownInterval);
                        resendOtpBtn.disabled = false; // Aktifkan kembali
                        countdownSpan.textContent = '0';
                    }
                }, 1000);
            }

            // Tahap 1: Minta Kirim OTP Reset
            forgotPasswordStage1.addEventListener('submit', function(e) {
                e.preventDefault();
                hideMessage(forgotPasswordMessage1);
                sendResetOtpBtn.disabled = true;
                sendResetOtpBtn.textContent = 'Memproses...';

                userPhoneNumberTemp = contactInfoInput.value.trim(); // Hapus spasi di awal/akhir

                // Client-side validation: pastikan hanya angka dan dimulai dengan '62'
                if (!userPhoneNumberTemp.match(/^\d+$/)) {
                    showMessage(forgotPasswordMessage1, 'Nomor telepon hanya boleh mengandung angka.', 'error');
                    sendResetOtpBtn.disabled = false;
                    sendResetOtpBtn.textContent = 'Kirim Kode Verifikasi';
                    return;
                }
                if (!userPhoneNumberTemp.startsWith('62')) {
                    showMessage(forgotPasswordMessage1, 'Nomor telepon harus diawali dengan 62 (contoh: 6281234567890).', 'error');
                    sendResetOtpBtn.disabled = false;
                    sendResetOtpBtn.textContent = 'Kirim Kode Verifikasi';
                    return;
                }
                if (userPhoneNumberTemp.length < 10 || userPhoneNumberTemp.length > 15) { // Sesuaikan panjang nomor WA
                    showMessage(forgotPasswordMessage1, 'Panjang nomor telepon tidak valid. Minimal 10 digit, maksimal 15 digit setelah 62.', 'error');
                    sendResetOtpBtn.disabled = false;
                    sendResetOtpBtn.textContent = 'Kirim Kode Verifikasi';
                    return;
                }

                fetch('../api/forgot_password_initiate.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ phone_number: userPhoneNumberTemp })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(forgotPasswordMessage1, data.message, 'success');
                        forgotPasswordStage1.classList.add('hidden'); // Sembunyikan tahap 1
                        forgotPasswordStage2.classList.remove('hidden'); // Tampilkan tahap 2
                        startCountdown(60); // Mulai countdown 60 detik
                    } else {
                        showMessage(forgotPasswordMessage1, data.message, 'error');
                    }
                    sendResetOtpBtn.disabled = false;
                    sendResetOtpBtn.textContent = 'Kirim Kode Verifikasi';
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage(forgotPasswordMessage1, 'Terjadi kesalahan jaringan atau server. Silakan coba lagi.', 'error');
                    sendResetOtpBtn.disabled = false;
                    sendResetOtpBtn.textContent = 'Kirim Kode Verifikasi';
                });
            });

            // Tahap 2: Verifikasi OTP dan Atur Ulang Password
            forgotPasswordStage2.addEventListener('submit', function(e) {
                e.preventDefault();
                hideMessage(forgotPasswordMessage2);
                verifyOtpBtn.disabled = true;
                verifyOtpBtn.textContent = 'Memverifikasi...';

                const otpCode = otpCodeInput.value;
                const newPassword = newPasswordInput.value;
                const confirmNewPassword = confirmNewPasswordInput.value;

                if (newPassword !== confirmNewPassword) {
                    showMessage(forgotPasswordMessage2, 'Password baru dan konfirmasi password tidak cocok.', 'error');
                    verifyOtpBtn.disabled = false;
                    verifyOtpBtn.textContent = 'Verifikasi & Atur Ulang';
                    return;
                }
                if (newPassword.length < 6) { // Minimal 6 karakter
                    showMessage(forgotPasswordMessage2, 'Password baru minimal 6 karakter.', 'error');
                    verifyOtpBtn.disabled = false;
                    verifyOtpBtn.textContent = 'Verifikasi & Atur Ulang';
                    return;
                }
                if (otpCode.length !== 6 || !otpCode.match(/^\d{6}$/)) {
                    showMessage(forgotPasswordMessage2, 'Kode OTP harus 6 digit angka.', 'error');
                    verifyOtpBtn.disabled = false;
                    verifyOtpBtn.textContent = 'Verifikasi & Atur Ulang';
                    return;
                }

                fetch('../api/forgot_password_verify_otp.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        phone_number: userPhoneNumberTemp, // Menggunakan nomor telepon yang disimpan dari tahap 1
                        otp_code: otpCode,
                        new_password: newPassword
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(forgotPasswordMessage2, data.message + ' Anda akan dialihkan ke halaman login.', 'success');
                        clearInterval(countdownInterval); // Hentikan countdown
                        setTimeout(() => {
                            window.location.href = 'login.php';
                        }, 2000);
                    } else {
                        showMessage(forgotPasswordMessage2, data.message, 'error');
                    }
                    verifyOtpBtn.disabled = false;
                    verifyOtpBtn.textContent = 'Verifikasi & Atur Ulang';
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage(forgotPasswordMessage2, 'Terjadi kesalahan jaringan atau server. Silakan coba lagi.', 'error');
                    verifyOtpBtn.disabled = false;
                    verifyOtpBtn.textContent = 'Verifikasi & Atur Ulang';
                });
            });

            // Tombol Kirim Ulang OTP
            resendOtpBtn.addEventListener('click', function() {
                hideMessage(forgotPasswordMessage2);
                resendOtpBtn.disabled = true;
                resendOtpBtn.textContent = 'Mengirim Ulang...';

                fetch('../api/forgot_password_initiate.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ phone_number: userPhoneNumberTemp }) // Menggunakan nomor telepon yang disimpan
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(forgotPasswordMessage2, data.message, 'success');
                        startCountdown(60); // Mulai countdown lagi
                    } else {
                        showMessage(forgotPasswordMessage2, data.message, 'error');
                        resendOtpBtn.disabled = false; // Aktifkan kembali jika ada error
                        countdownSpan.textContent = '0'; // Reset tampilan
                    }
                    resendOtpBtn.textContent = 'Kirim Ulang Kode (dalam ' + countdownSpan.textContent + 's)'; // Kembalikan teks asli
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage(forgotPasswordMessage2, 'Terjadi kesalahan jaringan atau server saat mengirim ulang. Silakan coba lagi.', 'error');
                    resendOtpBtn.disabled = false;
                    countdownSpan.textContent = '0';
                    resendOtpBtn.textContent = 'Kirim Ulang Kode (dalam ' + countdownSpan.textContent + 's)';
                });
            });
        });
    </script>
</body>
</html>