<?php
// emailakun.php
require_once __DIR__ . '/../Login/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();

// pastikan user login
if (!isset($_SESSION['user_id'])) {
    header('Location: ../Login/login.php');
    exit;
}

$userId = (int) $_SESSION['user_id'];
$errors = [];
$success = '';

// ambil data user terkini
$stmt = $pdo->prepare("SELECT id, username, email, fullname FROM users WHERE id = ? LIMIT 1");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
    // user tidak ditemukan -> logout
    session_destroy();
    header('Location: ../Login/login.php');
    exit;
}
$currentEmail = $user['email'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newEmail = trim($_POST['new_email'] ?? '');
    $password  = $_POST['password'] ?? '';

    // validasi sederhana
    if ($newEmail === '') {
        $errors[] = "Masukkan email baru.";
    } elseif (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Format email tidak valid.";
    }

    if ($password === '') {
        $errors[] = "Masukkan password untuk konfirmasi.";
    }

    if (empty($errors)) {
        try {
            // cek password user saat ini
            $stmtp = $pdo->prepare("SELECT password FROM users WHERE id = ? LIMIT 1");
            $stmtp->execute([$userId]);
            $rowp = $stmtp->fetch(PDO::FETCH_ASSOC);
            if (!$rowp || !password_verify($password, $rowp['password'])) {
                $errors[] = "Password salah. Tidak dapat mengubah email.";
            } else {
                // cek apakah email baru sudah dipakai user lain
                $stmtc = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ? LIMIT 1");
                $stmtc->execute([$newEmail, $userId]);
                if ($stmtc->fetch()) {
                    $errors[] = "Email sudah digunakan oleh pengguna lain.";
                } else {
                    // update email (tanpa konfirmasi)
                    $up = $pdo->prepare("UPDATE users SET email = ? WHERE id = ?");
                    $up->execute([$newEmail, $userId]);

                    // update session (opsional)
                    $_SESSION['email'] = $newEmail;

                    $success = "Email berhasil diubah menjadi " . htmlspecialchars($newEmail) . ".";
                    // perbarui currentEmail agar tampil ke user
                    $currentEmail = $newEmail;
                }
            }
        } catch (Throwable $e) {
            error_log("emailakun error: " . $e->getMessage());
            $errors[] = "Terjadi kesalahan server. Coba lagi nanti.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Ubah Email - 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{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:640px;background:#fff;padding:22px;border-radius:10px;box-shadow:0 6px 18px rgba(0,0,0,0.06)}
    h2{color:var(--accent);margin-bottom:8px}
    p.lead{color:#666;margin-bottom:14px}
    .input-group{margin-bottom:12px}
    label{display:block;margin-bottom:6px;color:#333;font-size:14px}
    input[type="email"], input[type="password"]{width:100%;padding:10px;border:1px solid #ddd;border-radius:6px;font-size:14px}
    .btn{display:inline-block;padding:10px 14px;border-radius:8px;border:0;cursor:pointer;font-weight:600}
    .btn-primary{background:var(--accent);color:#fff}
    .btn-link{background:#fff;border:1px solid var(--accent);color:var(--accent)}
    .msg{padding:10px;border-radius:8px;margin-bottom:12px}
    .msg.success{background:#e8f7f6;color:var(--accent);border:1px solid #bfeae8}
    .msg.error{background:#ffecec;color:#b00000;border:1px solid #f5c2c2}
    .note{font-size:13px;color:#666;margin-top:8px}
    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>
    <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" role="main">
      <h2>Ubah Email Akun</h2>
      <p class="lead">Di sini kamu bisa mengganti email yang terhubung ke akunmu. Untuk keamanan, masukkan password saat ini untuk konfirmasi.</p>

      <?php if (!empty($errors)): ?>
        <?php foreach ($errors as $e): ?>
          <div class="msg error"><?= htmlspecialchars($e) ?></div>
        <?php endforeach; ?>
      <?php endif; ?>

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

      <form method="post" novalidate>
        <div class="input-group">
          <label for="current_email">Email Saat Ini</label>
          <input id="current_email" type="email" value="<?= htmlspecialchars($currentEmail) ?>" disabled>
        </div>

        <div class="input-group">
          <label for="new_email">Email Baru</label>
          <input id="new_email" name="new_email" type="email" required placeholder="email@domain.com" value="<?= isset($newEmail) ? htmlspecialchars($newEmail) : '' ?>">
        </div>

        <div class="input-group">
          <label for="password">Password (konfirmasi)</label>
          <input id="password" name="password" type="password" required placeholder="Masukkan password saat ini">
        </div>

        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:8px">
          <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
          <a href="../user/akun.php" class="btn btn-link" style="text-align:center;line-height:30px;padding:10px 12px">Kembali</a>
        </div>

        <div class="note">Catatan: perubahan email akan tersimpan langsung tanpa verifikasi email baru. Pastikan email baru valid dan milikmu.</div>
      </form>
    </div>
  </main>

  <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>
