<?php
// File: admin/forgot_password.php
// AUDIT FIX: Token tidak boleh pernah ditampilkan ke user (security leak).
// AUDIT FIX: Tambah rate limiting dan CSRF protection.

ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/../includes/security.php';
secureSessionStart();
require_once '../includes/db_connect.php';

// Rate limiting: maks 5 percobaan per 15 menit per IP
if (!checkRateLimit('forgot_password', 5, 900)) {
    http_response_code(429);
    die('<div style="font-family:sans-serif;padding:40px;text-align:center"><h2>Terlalu Banyak Percobaan</h2><p>Coba lagi dalam 15 menit.</p></div>');
}

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();

    // Sanitasi username
    $username = sanitizeInput($_POST['username'] ?? '', 50);

    // AUDIT FIX: Selalu tampilkan pesan yang SAMA untuk username valid & tidak valid
    // (cegah username enumeration attack)
    $genericMsg = "<div class='bg-green-100 text-green-700 p-4 rounded mb-4 text-sm'>
        <strong>Permintaan Diterima!</strong><br>
        Jika username tersebut terdaftar, Tim IT akan melakukan reset password melalui akses server.
        Hubungi Tim IT dengan menyebutkan <strong>nama Anda dan waktu permintaan ini</strong>.
    </div>";

    $stmt = $pdo->prepare("SELECT id FROM admin_users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user) {
        // Generate token — TIDAK ditampilkan ke user (AUDIT FIX)
        $token  = bin2hex(random_bytes(32));
        $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
        $pdo->prepare("UPDATE admin_users SET reset_token = ?, reset_expiry = ? WHERE id = ?")
            ->execute([$token, $expiry, $user['id']]);
        // Token disimpan di DB untuk digunakan Tim IT melalui panel server
        // TIDAK dikirim ke browser dalam bentuk apapun
        error_log("[Reset Password] Request untuk user ID: {$user['id']} — Token tersimpan di DB (akses via server).");
    }

    // Tampilkan pesan yang sama regardless username valid atau tidak
    $msg = $genericMsg;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex, nofollow">
    <title>Lupa Password</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 h-screen flex items-center justify-center">
    <div class="bg-white p-8 rounded-xl shadow-lg w-96">
        <h2 class="text-2xl font-bold mb-2 text-center text-gray-800">Reset Password</h2>
        <p class="text-center text-gray-500 text-sm mb-6">Masukkan username Anda</p>

        <?= $msg ?>

        <?php if (!$msg): ?>
        <form method="POST">
            <?= csrfInput() ?>
            <div class="mb-6">
                <label class="block text-gray-700 text-sm font-bold mb-2" for="username">Username</label>
                <input type="text" id="username" name="username"
                       class="w-full p-2.5 border rounded focus:ring-2 focus:ring-blue-500 focus:outline-none"
                       autocomplete="username" required>
            </div>
            <button type="submit"
                class="w-full bg-blue-600 text-white font-bold py-2.5 px-4 rounded hover:bg-blue-700 transition">
                Kirim Permintaan
            </button>
        </form>
        <?php endif; ?>

        <div class="text-center mt-4">
            <a href="login.php" class="text-sm text-gray-500 hover:text-gray-800">
                ← Kembali ke Login
            </a>
        </div>
    </div>
</body>
</html>
