<?php
// verify_password_code.php
require_once __DIR__ . '/../Login/config.php';
require_once __DIR__ . '/password_utils.php';
require_once __DIR__ . '/mail_helper.php';

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

// Pesan info dan error
$info = '';
$error = '';

// Prefill email (jika sebelumnya pernah isi)
$prefillEmail = $_SESSION['pwd_reset_email_prefill'] ?? '';

// ===========================================================
// BAGIAN A: KIRIM KODE
// ===========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'send_code') {
    $email = trim($_POST['email'] ?? '');

    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Masukkan email yang valid.";
    } else {
        try {
            // cek apakah email ada (tapi tetap netral)
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                $info = "Jika email terdaftar, kode akan dikirim. Cek inbox/spam.";
            } else {
                // rate limit 5x 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) {
                    $info = "Permintaan terlalu sering. Coba lagi nanti.";
                } else {
                    // buat kode 6 digit
                    $code = generate_code_6();
                    $saved = save_password_token($pdo, $email, $code, 15 * 60, 'reset');

                    if (!$saved) {
                        $error = "Gagal membuat kode. Coba lagi.";
                    } else {
                        // kirim email
                        $subject = "Kode Reset Password - Pustakaia";
                        $html = "<p>Kode verifikasi Anda:</p>
                                <h2 style='letter-spacing:6px;'>$code</h2>
                                <p>Berlaku 15 menit.</p>";
                        @sendMail($email, $subject, $html);

                        $_SESSION['pwd_reset_email_prefill'] = $email;
                        $prefillEmail = $email;

                        $info = "Jika email terdaftar, kode sudah dikirim.";
                    }
                }
            }
        } catch (Throwable $e) {
            error_log("verify send_code error: " . $e->getMessage());
            $error = "Terjadi kesalahan server.";
        }
    }
}

// ===========================================================
// BAGIAN B: VERIFIKASI KODE
// ===========================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'verify_code') {
    $email = trim($_POST['email'] ?? '');
    $token = trim($_POST['token'] ?? '');

    if ($email === '' || $token === '') {
        $error = "Form tidak lengkap.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Format email tidak valid.";
    } elseif (!preg_match('/^\d{6}$/', $token)) {
        $error = "Kode harus 6 digit.";
    } else {
        try {
            $row = get_latest_token_row($pdo, $email, 'reset');
            if (!$row) {
                $error = "Kode tidak ditemukan.";
            } elseif (strtotime($row['expires_at']) < time()) {
                $error = "Kode kadaluarsa.";
            } elseif (!verify_code_with_hash($token, $row['token_hash'])) {
                $error = "Kode salah.";
            } else {
                $_SESSION['pwd_reset_id'] = $row['id'];
                $_SESSION['pwd_reset_email'] = $email;

                unset($_SESSION['pwd_reset_email_prefill']);

                header("Location: set_new_password.php");
                exit;
            }
        } catch (Throwable $e) {
            error_log("verify verify_code error: " . $e->getMessage());
            $error = "Terjadi kesalahan server.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8">
  <title>Reset Password - Verifikasi Kode</title>
  <style>
    :root{--accent:#069797;}
    *{box-sizing:border-box;margin:0;padding:0}
    body{
        font-family:"Poppins",Arial,sans-serif;
        background:linear-gradient(135deg,#f9f9f9,#e9f5ec);
        color:#222;
        min-height:100vh;
        display:flex;
        flex-direction:column;
    }
    header{
        display:flex;
        justify-content:space-between;
        align-items:center;
        padding:15px 30px;
        background:#fff;
        border-bottom:1px solid #ddd;
        position:sticky;
        top:0;
        z-index:100;
        width:100%;
    }
    .logo{
        font-size:20px;
        font-weight:bold;
        color:var(--accent);
        display:flex;
        align-items:center;
        gap:10px;
    }
    main{
        flex:1;
        display:flex;
        align-items:center;
        justify-content:center;
        padding:36px 20px;
    }
    .card{
        width:100%;
        max-width:620px;
        background:#fff;
        padding:22px;
        border-radius:10px;
        box-shadow:0 6px 18px rgba(0,0,0,0.06);
    }
    h2{color:var(--accent); margin-bottom:10px}
    label{display:block;margin-bottom:6px;color:#333;font-size:14px}
    input{
        width:100%;padding:10px;border:1px solid #ddd;
        border-radius:6px;margin-bottom:12px;
    }
    button{
        background:var(--accent);color:#fff;padding:10px 14px;
        border-radius:8px;border:0;cursor:pointer;font-size:14px;
    }
    .msg{
        padding:10px;border-radius:8px;margin-bottom:12px;font-size:14px
    }
    .msg.info{background:#e8f7f6;color:#066;border:1px solid #bfeae8}
    .msg.error{background:#ffecec;color:#b00000;border:1px solid #f5c2c2}
    footer{
        background:#fff;padding:20px 40px;font-size:14px;
        color:#222;border-top:1px solid #ddd;margin-top:auto
    }
    .footer-bottom{
        display:flex;justify-content:space-between;align-items:center;
        flex-wrap:wrap;font-size:13px
    }
    .footer-links a{
        margin-left:15px;color:#222;font-weight:500;text-decoration:none
    }
    .footer-links a:hover{text-decoration:underline}
  </style>
</head>
<body>

<!-- ========================================== -->
<!--                HEADER                      -->
<!-- ========================================== -->
<header>
  <div class="logo">
    <a href="../user/akun.php" style="text-decoration:none;color:var(--accent);font-size:18px;margin-right:8px">⬅</a>
    📚 Pustakaia
  </div>
</header>

<main>
  <div class="card">

    <h2>Reset Password – Verifikasi Kode</h2>

    <?php if ($info): ?>
      <div class="msg info"><?= htmlspecialchars($info) ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
      <div class="msg error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <!-- FORM KIRIM KODE -->
    <form method="post">
      <input type="hidden" name="action" value="send_code">

      <label>Email untuk menerima kode</label>
      <input type="email" name="email" required placeholder="email@domain.com"
             value="<?= htmlspecialchars($prefillEmail) ?>">

      <button type="submit">Kirim Kode</button>
    </form>

    <hr style="margin:16px 0; border:0; border-top:1px solid #eee;">

    <!-- FORM VERIFIKASI KODE -->
    <form method="post">
      <input type="hidden" name="action" value="verify_code">

      <label>Email</label>
      <input type="email" name="email" required 
             value="<?= htmlspecialchars($prefillEmail) ?>">

      <label>Kode (6 digit)</label>
      <input type="text" name="token" maxlength="6" pattern="\d{6}" required
             placeholder="123456">

      <button type="submit">Verifikasi Kode</button>
    </form>

    <p style="font-size:13px;color:#666;margin-top:10px">
      Jika belum menerima kode, klik "Kirim Kode" lagi. Kode berlaku 15 menit.
    </p>

  </div>
</main>

<!-- ========================================== -->
<!--                 FOOTER                     -->
<!-- ========================================== -->
<footer>
  <div class="footer-bottom">
    <p>© <?= date('Y') ?>, Pustakaia | Website developed by Grup 3</p>
    <div class="footer-links">
      <a href="#">Terms of Use</a>
      <a href="#">Privacy Policy</a>
    </div>
  </div>
</footer>

</body>
</html>
