<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require __DIR__ . '/../Login/config.php'; // config.php menyediakan $pdo
require __DIR__ . '/../lib/lib_notify.php'; // ⬅️ tambahkan ini

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil input
    $judul = trim($_POST['judul'] ?? '');

    // ✅ GANTI BAGIAN INI
    if (isset($_POST['kategori'])) {
        if (is_array($_POST['kategori'])) {
            // Jika kategori dikirim sebagai array (contoh: name="kategori[]")
            $kategori = implode(', ', array_filter($_POST['kategori']));
        } else {
            // Jika kategori dikirim sebagai string (seperti di form kamu sekarang)
            $kategori = trim((string)$_POST['kategori']);
        }
    } else {
        $kategori = '';
    }
    // ✅ SAMPAI SINI

    $penulis = trim($_POST['penulis'] ?? '');
    $sinopsis = trim($_POST['sinopsis'] ?? '');
    $halaman = intval($_POST['halaman'] ?? 0);
    $penerbit = trim($_POST['penerbit'] ?? '');
    $tahun_terbit = trim($_POST['tahun_terbit'] ?? '');
    $berat = intval($_POST['berat'] ?? 0);
    $panjang = floatval($_POST['panjang'] ?? 0);
    $lebar = floatval($_POST['lebar'] ?? 0);
    $bahasa = trim($_POST['bahasa'] ?? '');
    $isbn = trim($_POST['isbn'] ?? '');
    $stok = intval($_POST['stok'] ?? 0);
    $rak = trim($_POST['rak'] ?? 'A1'); // ✅ tambahan: lokasi rak


    // Validasi sederhana
    if ($judul === '') $errors[] = "Judul wajib diisi.";
    if ($penulis === '') $errors[] = "Penulis wajib diisi.";

    // Upload gambar
    $gambar_path = null;
    if (isset($_FILES['gambar']) && !empty($_FILES['gambar']['name'])) {
        $allowed = ['image/jpeg','image/png','image/webp'];
        if ($_FILES['gambar']['error'] !== UPLOAD_ERR_OK) {
            $errors[] = "Upload gambar gagal (kode: {$_FILES['gambar']['error']}).";
        } else {
            $mime = $_FILES['gambar']['type'];
            if (!in_array($mime, $allowed)) {
                $real_mime = @mime_content_type($_FILES['gambar']['tmp_name']);
                if (!in_array($real_mime, $allowed)) {
                    $errors[] = "Format gambar harus JPG/PNG/WEBP.";
                }
            }
            if (empty($errors)) {
                $upload_dir = __DIR__ . '/../Uploads';
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
                $ext = strtolower(pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION));
                $ext = preg_replace('/[^a-z0-9]/', '', $ext) ?: 'jpg';
                try {
                    $safe_name = 'cover_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
                } catch (Exception $e) {
                    $safe_name = 'cover_' . time() . '_' . uniqid() . '.' . $ext;
                }
                $dest = $upload_dir . '/' . $safe_name;
                if (move_uploaded_file($_FILES['gambar']['tmp_name'], $dest)) {
                    $gambar_path = 'Uploads/' . $safe_name;
                } else {
                    $errors[] = "Gagal memindahkan file gambar.";
                }
            }
        }
    }

    // Simpan ke database
    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // 1️⃣ Simpan ke tabel books
            $sql = "INSERT INTO books (judul, kategori, penulis, sinopsis, halaman, penerbit, tahun_terbit, berat, panjang, lebar, bahasa, isbn, stok, gambar, created_at) 
            VALUES (:judul, :kategori, :penulis, :sinopsis, :halaman, :penerbit, :tahun_terbit, :berat, :panjang, :lebar, :bahasa, :isbn, :stok, :gambar, NOW())";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':judul' => $judul,
        ':kategori' => $kategori,
        ':penulis' => $penulis,
        ':sinopsis' => $sinopsis,
        ':halaman' => $halaman,
        ':penerbit' => $penerbit,
        ':tahun_terbit' => $tahun_terbit,
        ':berat' => $berat,
        ':panjang' => $panjang,
        ':lebar' => $lebar,
        ':bahasa' => $bahasa,
        ':isbn' => $isbn,
        ':stok' => $stok,
        ':gambar' => $gambar_path
    ]);
    

            $book_id = $pdo->lastInsertId(); // ✅ ambil id buku baru

            // 2️⃣ Auto generate no_buku & simpan ke book_items
            $kode_awal = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $judul), 0, 2)); 
            for ($i = 1; $i <= $stok; $i++) {
                $nomor = str_pad($i, 3, '0', STR_PAD_LEFT);
                $no_buku = $kode_awal . '-' . $book_id . '-' . $nomor; // ✅ unik per buku

                $insert_item = "INSERT INTO book_items (book_id, no_buku, rak, status) 
                                VALUES (:book_id, :no_buku, :rak, 'tersedia')";
                $item_stmt = $pdo->prepare($insert_item);
                $item_stmt->execute([
                    ':book_id' => $book_id,
                    ':no_buku' => $no_buku,
                    ':rak' => $rak
                ]);
            }
            $pdo->commit();
            $success = true;
            $_POST = [];
           // 3️⃣ Broadcast notifikasi ke semua user (non-admin)
if ($judul !== '') {
    send_broadcast_to_all_users(
      $pdo,
      'Buku baru ditambahkan: "' . $judul . '". Yuk cek sekarang!',
      'BROADCAST'
    );
  }
         
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = "Gagal menyimpan data: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tambah Buku - Pustakaia</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body { margin:0; font-family:"Poppins", Arial, sans-serif; line-height:1.6; background:#f4f7f9; color:#222; display:flex; min-height:100vh; flex-direction:column; }
a { text-decoration:none; }
.container { display:flex; flex:1; }
main { flex:1; padding:20px; margin-left:250px; }

/* kategori */
.kategori-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
}
.kategori-item {
  padding: 8px 12px;
  border: 1px solid #069797;
  border-radius: 4px; /* full kotak */
  color: #069797;
  background: #fff;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 13px;
}
.kategori-item:hover {
  background: #e0f7f7;
}
.kategori-item.selected {
  background: #069797;
  color: #fff;
  font-weight: 600;
}


/* Sidebar */
.sidebar { width:250px; height:100vh; background:#fff; border-right:1px solid #ddd; padding:10px 0; position:fixed; top:0; left:0; overflow-y:auto; }
.sidebar-header { padding:15px 20px; border-bottom:1px solid #ddd; }
.sidebar-header h2 { margin:0; font-size:18px; color:#069797; }
.sidebar-header p { margin:0; font-size:12px; color:#777; }
.sidebar-menu { list-style:none; padding:0; margin:0; }
.sidebar-menu li { font-size:14px; position:relative; }
.sidebar-menu li > a { display:flex; align-items:center; padding:12px 20px; color:#444; width:100%; transition: background 0.2s; }
.sidebar-menu li > a i { margin-right:10px; font-size:16px; color:#666; }
.sidebar-menu li > a:hover { background:#f5f5f5; border-radius:6px; }
.sidebar-menu li > a.active { background:#e0ebff; color:#069797; font-weight:600; border-radius:6px; }
.sidebar-menu li > a.active i { color:#069797; }
.submenu { list-style:none; padding-left:0; margin:0; display:none; }
.submenu li a { display:flex; align-items:center; padding:8px 40px; font-size:13px; color:#444; }
.submenu li a:hover { background:#f5f5f5; border-radius:6px; }

/* Form Card */
.form-card {
    background:#fff;
    padding:20px;
    border-radius:8px;
    box-shadow:0 2px 6px rgba(0,0,0,0.1);
    max-width:1600px;
    margin:auto;
    box-sizing:border-box;
}
.form-card label{display:block;margin-top:12px;font-weight:600;color:#069797;}
.form-card input[type=text], .form-card input[type=number], .form-card input[type=file], .form-card textarea, .form-card select {
    width:100%; padding:10px; margin-top:6px; border:1px solid #ddd; border-radius:4px; box-sizing:border-box;
}
.form-card button{background:#069797;color:#fff;padding:10px 16px;border:none;border-radius:6px;margin-top:12px;cursor:pointer;font-weight:700;}
.errors{background:#ffe6e6;border:1px solid #ffcccc;padding:10px;margin-bottom:12px;}
.success{background:#e6ffef;border:1px solid #c7f0d6;padding:10px;margin-bottom:12px;}

/* Footer */
footer { background:#fff; border-top:1px solid #ddd; padding:15px 30px; font-size:14px; display:flex; justify-content:space-between; align-items:center; margin-top:auto; margin-left:250px; color:#555; }
.footer-right a { margin-left:15px; color:#555; font-weight:500; }
.footer-right a:hover { text-decoration:underline; }
</style>
</head>
<body>
<div class="container">
    <!-- Sidebar -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <h2>📚 Pustakaia</h2>
            <p>Admin Panel</p>
        </div>
        <ul class="sidebar-menu">
            <li><a href="dsadmin.php"><i class="fa fa-tachometer-alt"></i> Dashboard</a></li>
            <li class="has-submenu active">
                <a href="#"><i class="fa fa-book"></i> Kelola Buku <span class="arrow"></span></a>
                <ul class="submenu" style="display:block;">
                    <li><a href="daftarbuku.php"><i class="fa fa-list"></i> Daftar Buku</a></li>
                    <li><a href="add_book.php" class="active"><i class="fa fa-plus"></i> Tambahkan Buku</a></li>
                </ul>
            </li>
            <li class="has-submenu">
                <a href="#"><i class="fa fa-users"></i> Kelola Anggota</a>
                <ul class="submenu">
                    <li><a href="daftaranggota.php"><i class="fa fa-list"></i> Daftar Anggota</a></li>
                    <li><a href="add_anggota.php"><i class="fa fa-user-plus"></i> Tambahkan Anggota</a></li>
                </ul>
            </li>
            <li><a href="borrow_requests.php"><i class="fa fa-exchange-alt"></i> Kelola Peminjaman</a></li>
        </ul>
        <hr>
        <ul class="sidebar-menu">
            <li><a href="#"><i class="fa fa-cog"></i> Pengaturan</a></li>
            <li><a href="../index2.php"><i class="fa fa-sign-out-alt"></i> Keluar</a></li>
        </ul>
    </aside>

    <!-- Main Content -->
    <main>
        <h1>Tambah Buku Baru</h1>
        <div class="form-card">
            <?php if ($success): ?>
                <div class="success">Buku berhasil ditambahkan & notifikasi dibuat.</div>
            <?php endif; ?>
            <?php if (!empty($errors)): ?>
                <div class="errors">
                    <ul>
                        <?php foreach ($errors as $e): ?>
                            <li><?= htmlspecialchars($e) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form method="post" enctype="multipart/form-data">
                <label>Judul</label>
                <input type="text" name="judul" value="<?= htmlspecialchars($_POST['judul'] ?? '') ?>" required>
                <label>Kategori</label>
<div class="kategori-container">
  <?php
  $opsi = [
    'Novel','Sains','Teknologi','Komputer','Matematika','Fisika','Kimia','Biologi',
    'Psikologi','Ekonomi','Bisnis','Sejarah','Agama','Sastra','Politik','Pendidikan',
    'Anak-anak','Remaja','Inspiratif','Hukum','Geografi','Kesehatan','Komik','Ensiklopedia','Filsafat'
  ];
  foreach ($opsi as $opt): ?>
    <div class="kategori-item" data-value="<?= htmlspecialchars($opt) ?>"><?= htmlspecialchars($opt) ?></div>
  <?php endforeach; ?>
</div>
<input type="hidden" name="kategori" id="kategoriInput">
<small>Klik kategori untuk memilih. Bisa lebih dari satu.</small>



                <label>Penulis</label>
                <input type="text" name="penulis" value="<?= htmlspecialchars($_POST['penulis'] ?? '') ?>" required>

                <label>Sinopsis</label>
                <textarea name="sinopsis" rows="6"><?= htmlspecialchars($_POST['sinopsis'] ?? '') ?></textarea>

                <label>Halaman</label>
                <input type="number" name="halaman" value="<?= htmlspecialchars($_POST['halaman'] ?? '') ?>">

                <label>Penerbit</label>
                <input type="text" name="penerbit" value="<?= htmlspecialchars($_POST['penerbit'] ?? '') ?>">

                <label>Tahun Terbit</label>
                <input type="text" name="tahun_terbit" placeholder="YYYY" value="<?= htmlspecialchars($_POST['tahun_terbit'] ?? '') ?>">

                <label>Berat (gram)</label>
                <input type="number" name="berat" value="<?= htmlspecialchars($_POST['berat'] ?? '') ?>">

                <label>Panjang (cm)</label>
                <input type="text" name="panjang" value="<?= htmlspecialchars($_POST['panjang'] ?? '') ?>">

                <label>Lebar (cm)</label>
                <input type="text" name="lebar" value="<?= htmlspecialchars($_POST['lebar'] ?? '') ?>">

                <label>Bahasa</label>
                <input type="text" name="bahasa" value="<?= htmlspecialchars($_POST['bahasa'] ?? '') ?>">

                <label>ISBN</label>
                <input type="text" name="isbn" value="<?= htmlspecialchars($_POST['isbn'] ?? '') ?>">

                <label>Stok</label>
                <input type="number" name="stok" value="<?= htmlspecialchars($_POST['stok'] ?? '1') ?>">

                <!-- ✅ tambahan input rak -->
                <label>Rak Penyimpanan</label>
                <input type="text" name="rak" placeholder="contoh: A1" value="<?= htmlspecialchars($_POST['rak'] ?? 'A1') ?>">

                <label>Gambar Cover (JPG/PNG/WEBP)</label>
                <input type="file" name="gambar" accept="image/*">

                <button type="submit">Simpan Buku</button>
            </form>

        </div>
    </main>
</div>

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

<script>
document.querySelectorAll('.has-submenu > a').forEach(menu => {
    menu.addEventListener('click', e => {
        e.preventDefault();
        const submenu = menu.nextElementSibling;
        submenu.style.display = submenu.style.display === 'block' ? 'none' : 'block';
    });
});

document.querySelectorAll('.kategori-item').forEach(item => {
  item.addEventListener('click', () => {
    item.classList.toggle('selected');
    const selected = [...document.querySelectorAll('.kategori-item.selected')].map(el => el.dataset.value);
    document.getElementById('kategoriInput').value = selected.join(', ');
  });
});

</script>
</body>
</html>
