<?php
// auth/forgot_password.php
session_start();
include '../config/database.php';

// Ambil Nama Aplikasi
$query_cfg = mysqli_query($conn, "SELECT nama_aplikasi FROM settings WHERE id = 1");
$cfg = mysqli_fetch_assoc($query_cfg);
$app_name = $cfg['nama_aplikasi'] ?? 'AI Workspace';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lupa Password | <?= htmlspecialchars($app_name) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    
    <style>
        :root { --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --glass-bg: rgba(255, 255, 255, 0.9); }
        body { background: #f1f5f9; background-image: radial-gradient(at 0% 0%, rgba(102, 126, 234, 0.1) 0px, transparent 50%), radial-gradient(at 100% 100%, rgba(118, 75, 162, 0.1) 0px, transparent 50%); height: 100dvh; display: flex; align-items: center; justify-content: center; font-family: 'Plus Jakarta Sans', sans-serif; margin: 0; padding: 20px; }
        .login-card { background: var(--glass-bg); backdrop-filter: blur(20px); padding: 40px; border-radius: 35px; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.1); width: 100%; max-width: 420px; border: 1px solid rgba(255, 255, 255, 0.6); animation: fadeIn 0.8s ease-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        .brand-icon { width: 70px; height: 70px; background: var(--primary-gradient); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; color: white; font-size: 35px; box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3); }
        h3 { color: #1e293b; font-weight: 800; }
        .form-label { font-weight: 700; font-size: 0.8rem; color: #64748b; text-transform: uppercase; margin-bottom: 8px; }
        .form-control { border-radius: 15px; padding: 12px 18px; border: 1px solid #e2e8f0; font-size: 1rem; }
        .form-control:focus { box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1); border-color: #667eea; }
        .btn-custom { background: var(--primary-gradient); border: none; border-radius: 15px; padding: 14px; font-weight: 700; color: white; transition: all 0.3s ease; width: 100%; }
        .btn-custom:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3); opacity: 0.95; }
        #form-otp { display: none; } /* Sembunyikan form OTP di awal */
    </style>
</head>
<body>

<div class="login-card">
    <div class="brand-icon"><i class="bi bi-shield-lock"></i></div>
    <div class="text-center mb-4">
        <h3>Reset Password</h3>
        <p class="text-muted small" id="deskripsi-form">Masukkan email Anda untuk menerima kode OTP.</p>
    </div>

    <div id="alert-msg" class="alert d-none border-0 rounded-3 small py-2 text-center mb-3"></div>

    <form id="form-request" onsubmit="requestOTP(event)">
        <div class="mb-3">
            <label class="form-label">Email Terdaftar</label>
            <input type="email" id="email" class="form-control" placeholder="contoh@domain.com" required>
        </div>
        <div class="mb-4">
            <label class="form-label">Password Baru</label>
            <input type="password" id="new_password" class="form-control" placeholder="Minimal 6 karakter" required minlength="6">
        </div>
        <button type="submit" id="btn-request" class="btn-custom shadow">KIRIM KODE OTP</button>
    </form>

    <form id="form-otp" onsubmit="verifyOTP(event)">
        <div class="mb-4">
            <label class="form-label text-success">Kode OTP (6 Digit)</label>
            <input type="text" id="otp_code" class="form-control text-center fw-bold fs-4" placeholder="XXXXXX" required maxlength="6" autocomplete="off">
        </div>
        <button type="submit" id="btn-verify" class="btn-custom shadow">VERIFIKASI & GANTI PASSWORD</button>
    </form>
    
    <div class="text-center mt-4">
        <a href="login_page.php" class="text-decoration-none fw-bold text-secondary"><i class="bi bi-arrow-left"></i> Kembali ke Login</a>
    </div>
</div>

<script>
    // Fungsi Menampilkan Notifikasi
    function showAlert(type, message) {
        const alertBox = document.getElementById('alert-msg');
        alertBox.className = `alert alert-${type} border-0 rounded-3 small py-2 text-center mb-3`;
        alertBox.innerHTML = message;
        alertBox.classList.remove('d-none');
    }

    // TAHAP 1: Kirim Request OTP ke Backend
    async function requestOTP(e) {
        e.preventDefault();
        const btn = document.getElementById('btn-request');
        const email = document.getElementById('email').value;
        
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Memproses...';
        btn.disabled = true;

        const formData = new FormData();
        formData.append('action', 'request_otp');
        formData.append('email', email);

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

            if (result.status === 'success') {
                showAlert('success', result.message);
                document.getElementById('form-request').style.display = 'none';
                document.getElementById('form-otp').style.display = 'block';
                document.getElementById('deskripsi-form').innerText = "Cek kotak masuk/spam email Anda untuk melihat kode OTP.";
            } else {
                showAlert('danger', result.message);
            }
        } catch (error) {
            showAlert('danger', 'Terjadi kesalahan jaringan.');
        } finally {
            btn.innerHTML = 'KIRIM KODE OTP';
            btn.disabled = false;
        }
    }

    // TAHAP 2: Verifikasi OTP dan Update Password
    async function verifyOTP(e) {
        e.preventDefault();
        const btn = document.getElementById('btn-verify');
        const email = document.getElementById('email').value;
        const new_password = document.getElementById('new_password').value;
        const otp_code = document.getElementById('otp_code').value;

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

        const formData = new FormData();
        formData.append('action', 'verify_otp');
        formData.append('email', email);
        formData.append('new_password', new_password);
        formData.append('otp_code', otp_code);

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

            if (result.status === 'success') {
                document.getElementById('form-otp').style.display = 'none';
                document.getElementById('deskripsi-form').innerText = "Reset Password Berhasil!";
                showAlert('success', '<b>Sukses!</b> Password Anda berhasil diubah. Silakan login.');
                setTimeout(() => { window.location.href = 'login_page.php'; }, 3000);
            } else {
                showAlert('danger', result.message);
            }
        } catch (error) {
            showAlert('danger', 'Terjadi kesalahan jaringan.');
        } finally {
            btn.innerHTML = 'VERIFIKASI & GANTI PASSWORD';
            btn.disabled = false;
        }
    }
</script>

</body>
</html>