<?php
// request_password_reset.php
// Terima POST email dari form (forgot.php). Buat kode 6 digit, simpan, kirim email.
// Setelah itu redirect ke verify_password_code.php (netral).

require_once __DIR__ . '/../Login/config.php';
require_once __DIR__ . '/mail_helper.php';
require_once __DIR__ . '/password_utils.php';

if (session_status() === PHP_SESSION_NONE) session_start();

// helper redirect netral
function redirect_neutral() {
    header('Location: forgot.php?sent=1');
    exit;
}

$email = trim($_POST['email'] ?? '');
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    redirect_neutral();
}

try {
    // cek apakah email terdaftar (jangan bocorkan ke user)
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) {
        redirect_neutral();
    }

    // rate-limit sederhana per jam
    $window = date('Y-m-d H:i:s', time() - 3600);
    $cnt = $pdo->prepare("SELECT COUNT(*) FROM password_resets WHERE email = ? AND created_at >= ?");
    $cnt->execute([$email, $window]);
    $count = (int)$cnt->fetchColumn();
    if ($count >= 5) {
        // netral, namun bisa set session pesan
        $_SESSION['forgot_msg'] = "Terlalu banyak permintaan. Coba lagi nanti.";
        redirect_neutral();
    }

    // buat kode dan simpan hash
    $code = generate_code_6();
    $saved = save_password_token($pdo, $email, $code, 15*60, 'reset'); // 15 menit
    if (!$saved) {
        // tetap netral
        redirect_neutral();
    }

    // kirim email (kode)
    $subject = "Kode Reset Password - Pustakaia";
    $html = "<p>Kami menerima permintaan reset password untuk akun ini.</p>
             <p>Kode verifikasi 6 digit:</p>
             <h2 style='letter-spacing:6px;'>$code</h2>
             <p>Kode berlaku 15 menit. Jika Anda tidak meminta, abaikan email ini.</p>
             <p>Salam,<br>Pustakaia</p>";

    @sendMail($email, $subject, $html);

    // simpan email sementara di session agar form verifikasi dapat menampilkan default (opsional)
    $_SESSION['pwd_reset_email_prefill'] = $email;

    // arahkan ke form verifikasi kode (netral)
    header('Location: verify_password_code.php?sent=1');
    exit;

} catch (Throwable $e) {
    error_log("request_password_reset error: " . $e->getMessage());
    redirect_neutral();
}
