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

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

if (empty($_SESSION['pwd_reset_id']) || empty($_SESSION['pwd_reset_email'])) {
    header('Location: verify_password_code.php');
    exit;
}

$resetId = (int) $_SESSION['pwd_reset_id'];
$email   = $_SESSION['pwd_reset_email'];
$error   = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $pw  = $_POST['password'] ?? '';
    $pw2 = $_POST['password2'] ?? '';

    if ($pw === '' || $pw2 === '') {
        $error = "Form tidak lengkap.";
    } elseif ($pw !== $pw2) {
        $error = "Password konfirmasi tidak cocok.";
    } elseif (strlen($pw) < 6) {
        $error = "Password minimal 6 karakter.";
    } else {
        try {
            // cek token
            $stmt = $pdo->prepare("SELECT id, token_hash, expires_at 
                                   FROM password_resets 
                                   WHERE id = ? AND email = ? LIMIT 1");
            $stmt->execute([$resetId, $email]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$row) {
                $error = "Token tidak ditemukan. Proses ulang dari awal.";
            } elseif (strtotime($row['expires_at']) < time()) {
                $error = "Token sudah kadaluarsa. Proses ulang dari awal.";
            } else {
                // update password
                $hash = password_hash($pw, PASSWORD_DEFAULT);
                $upd  = $pdo->prepare("UPDATE users SET password = ? WHERE email = ?");
                $upd->execute([$hash, $email]);

                // bersihkan token
                delete_tokens_for_email($pdo, $email, 'reset');

                unset($_SESSION['pwd_reset_id'], $_SESSION['pwd_reset_email']);

                header('Location: ../Login/login.php?reset=1');
                exit;
            }
        } catch (Throwable $e) {
            error_log("set_new_password error: " . $e->getMessage());
            $error = "Terjadi kesalahan server.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8">
  <title>Buat Password Baru - Pustakaia</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 */
    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 */
    main{
      flex:1;
      display:flex;
      align-items:center;
      justify-content:center;
      padding:36px 20px
    }
    .box{
      width:100%;
      max-width:520px;
      background:#fff;
      padding:24px;
      border-radius:10px;
      box-shadow:0 6px 18px rgba(0,0,0,0.06)
    }
    h2{color:var(--accent);margin-bottom:10px}
    .msg{padding:12px;border-radius:8px;margin-bottom:12px}
    .msg.error{background:#ffecec;color:#900;border:1px solid #f5c2c2}
    label{display:block;margin-bottom:6px;color:#333}
    input{
      width:100%;
      padding:10px;
      border:1px solid #ddd;
      border-radius:6px;
      margin-bottom:10px
    }
    button{
      background:var(--accent);
      color:#fff;
      padding:10px 14px;
      border-radius:8px;
      border:0;
      cursor:pointer
    }

    /* FOOTER */
    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}

    @media(max-width:700px){
      header,footer{padding:14px 18px};
      main{padding:20px 12px}
    }
  </style>
</head>
<body>

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

  <!-- MAIN CONTENT -->
  <main>
    <div class="box">
      <h2>Buat Password Baru</h2>

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

      <form method="post">
        <label>Email</label>
        <input type="email" value="<?= htmlspecialchars($email) ?>" disabled>

        <label>Password baru</label>
        <input type="password" name="password" required minlength="6" placeholder="Minimal 6 karakter">

        <label>Ulangi password</label>
        <input type="password" name="password2" required minlength="6" placeholder="Ulangi password">

        <div style="margin-top:10px">
          <button type="submit">Simpan Password Baru</button>
        </div>
      </form>
    </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>
