<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Setel Ulang Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        /* Re-use atau sesuaikan CSS dari forgot_password.php */
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #f0f8ff, #e0ffff);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            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;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <h2 id="formTitle">Setel Ulang Password</h2>
        <p id="formInstruction" style="font-size: 0.9em; color: #555; margin-bottom: 25px;">Masukkan password baru Anda.</p>

        <div id="statusMessage" class="message-area hidden"></div>

        <form id="resetPasswordForm" class="hidden">
            <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="updatePasswordBtn">Update Password</button>
            <div id="resetPasswordMessage" 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"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const resetPasswordForm = document.getElementById('resetPasswordForm');
            const newPasswordInput = document.getElementById('newPassword');
            const confirmNewPasswordInput = document.getElementById('confirmNewPassword');
            const updatePasswordBtn = document.getElementById('updatePasswordBtn');
            const resetPasswordMessage = document.getElementById('resetPasswordMessage');
            const statusMessage = document.getElementById('statusMessage');
            const formTitle = document.getElementById('formTitle');
            const formInstruction = document.getElementById('formInstruction');

            const urlParams = new URLSearchParams(window.location.search);
            const token = urlParams.get('token');

            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';
            }

            // Langkah 1: Verifikasi token saat halaman dimuat
            if (!token) {
                showMessage(statusMessage, 'Tautan reset password tidak valid atau tidak ada token.', 'error');
                formTitle.textContent = 'Tautan Tidak Valid';
                formInstruction.textContent = 'Mohon gunakan tautan yang benar dari email Anda.';
                resetPasswordForm.classList.add('hidden'); // Sembunyikan form password
            } else {
                showMessage(statusMessage, 'Memverifikasi tautan reset password Anda...', 'success'); // Gunakan success untuk loading
                resetPasswordForm.classList.add('hidden'); // Sembunyikan dulu form password

                fetch('../api/reset_password_verify_token.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ token: token })
                })
                .then(response => response.json())
                .then(data => {
                    hideMessage(statusMessage); // Sembunyikan pesan loading
                    if (data.success) {
                        showMessage(resetPasswordMessage, data.message || 'Tautan valid. Silakan masukkan password baru Anda.', 'success');
                        resetPasswordForm.classList.remove('hidden'); // Tampilkan form password
                    } else {
                        showMessage(statusMessage, data.message || 'Tautan reset password tidak valid atau sudah kedaluwarsa.', 'error');
                        formTitle.textContent = 'Tautan Tidak Valid';
                        formInstruction.textContent = 'Mohon minta tautan reset baru.';
                        resetPasswordForm.classList.add('hidden'); // Sembunyikan form password
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    hideMessage(statusMessage);
                    showMessage(statusMessage, 'Terjadi kesalahan jaringan atau server saat memverifikasi tautan.', 'error');
                    formTitle.textContent = 'Error Jaringan';
                    formInstruction.textContent = 'Tidak dapat memverifikasi tautan saat ini. Coba lagi nanti.';
                    resetPasswordForm.classList.add('hidden');
                });
            }

            // Langkah 2: Proses update password
            resetPasswordForm.addEventListener('submit', function(e) {
                e.preventDefault();
                hideMessage(resetPasswordMessage);
                updatePasswordBtn.disabled = true;
                updatePasswordBtn.textContent = 'Mengupdate...';

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

                if (newPassword !== confirmNewPassword) {
                    showMessage(resetPasswordMessage, 'Password baru dan konfirmasi password tidak cocok.', 'error');
                    updatePasswordBtn.disabled = false;
                    updatePasswordBtn.textContent = 'Update Password';
                    return;
                }
                if (newPassword.length < 6) {
                    showMessage(resetPasswordMessage, 'Password baru minimal 6 karakter.', 'error');
                    updatePasswordBtn.disabled = false;
                    updatePasswordBtn.textContent = 'Update Password';
                    return;
                }

                fetch('../api/reset_password_update.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        token: token,
                        new_password: newPassword
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage(resetPasswordMessage, data.message || 'Password berhasil direset! Anda akan dialihkan ke halaman login.', 'success');
                        setTimeout(() => {
                            window.location.href = 'login.php'; // Arahkan ke halaman login
                        }, 2000);
                    } else {
                        showMessage(resetPasswordMessage, data.message || 'Gagal mengupdate password. Tautan mungkin sudah tidak valid.', 'error');
                        updatePasswordBtn.disabled = false;
                        updatePasswordBtn.textContent = 'Update Password';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage(resetPasswordMessage, 'Terjadi kesalahan jaringan atau server saat mengupdate password. Coba lagi.', 'error');
                    updatePasswordBtn.disabled = false;
                    updatePasswordBtn.textContent = 'Update Password';
                });
            });
        });
    </script>
</body>
</html>