<?php
// forgot_submit.php
// Terima POST dari forgot.php -> buat token & kirim email reset (jika user ada)

require __DIR__ . '/../Login/config.php';
require __DIR__ . '/mail_helper.php'; // pastikan mail_helper.php di folder yang sama

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

// helper: redirect netral ke form lupa password
function redirect_neutral($extra = '') {
    $qs = $extra ? ('?' . $extra) : '?sent=1';
    header('Location: forgot.php' . $qs);
    exit;
}

// Ambil email dari POST
$email = trim($_POST['email'] ?? '');

if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // format email tidak valid -> redirect netral
    redirect_neutral('sent=1');
}

try {
    // Cek apakah email terdaftar
    $stmt = $pdo->prepare("SELECT id, username FROM users WHERE email = ? LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        // Jika tidak terdaftar: jangan tunjukkan ke user. Redirect netral.
        redirect_neutral('sent=1');
    }

    // --- Buat token acak (kirim token mentah lewat email; simpan HASH-nya di DB) ---
    $token = bin2hex(random_bytes(16)); // 32-char hex token
    $token_hash = password_hash($token, PASSWORD_DEFAULT);
    $expires_at = date('Y-m-d H:i:s', time() + 60*60); // 1 jam dari sekarang

    // --- Simpan ke tabel password_resets ---
    // Pastikan tabel password_resets sudah ada. Kalau belum, kamu bisa buat tabel ini:
    // CREATE TABLE password_resets (
    //   id INT AUTO_INCREMENT PRIMARY KEY,
    //   email VARCHAR(255) NOT NULL,
    //   token_hash VARCHAR(255) NOT NULL,
    //   expires_at DATETIME NOT NULL,
    //   created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    //   INDEX(email)
    // );
    $insert = $pdo->prepare("INSERT INTO password_resets (email, token_hash, expires_at) VALUES (?, ?, ?)");
    $insert->execute([$email, $token_hash, $expires_at]);

    // --- Siapkan link reset ---
    // Gunakan absolute URL sesuai domain + path reset.php
    // Ubah domain jika perlu. Contoh lokal: http://localhost/1/pengaturan/reset.php
    $base = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
            . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
    // pastikan remove trailing slash
    $base = rtrim($base, '/\\');

    $resetLink = $base . '/reset.php?email=' . urlencode($email) . '&token=' . urlencode($token);

    // --- Siapkan isi email (HTML) ---
    $subject = 'Reset Password - Pustakaia';
    $html = "
      <p>Halo,</p>
      <p>Kami menerima permintaan untuk mereset password akun Anda di Pustakaia.</p>
      <p>Jika Anda yang meminta, klik tombol di bawah ini untuk membuat password baru (link berlaku 1 jam):</p>
      <p style=\"margin:18px 0;\">
        <a href=\"{$resetLink}\" style=\"display:inline-block;padding:10px 16px;background:#069797;color:#fff;border-radius:6px;text-decoration:none;font-weight:600;\">Reset Password</a>
      </p>
      <p>Atau gunakan link berikut jika tombol tidak bekerja:<br><small>{$resetLink}</small></p>
      <p>Jika Anda tidak meminta reset, abaikan email ini.</p>
      <p>Salam,<br>Pustakaia</p>
    ";

    // --- Kirim email via mail_helper.php -> sendMail()
    $sent = sendMail($email, $subject, $html);

    // Jangan beri tahu user apakah email valid; cukup redirect netral
    redirect_neutral('sent=1');

} catch (Throwable $e) {
    // Log error server-side (file log atau sistem logging) — jangan tampilkan ke user
    error_log("forgot_submit error: " . $e->getMessage());

    // Redirect netral juga (atau jika mau debug, gunakan ?error=...)
    redirect_neutral('sent=1');
}
