<?php 
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require __DIR__ . '/../Login/config.php'; // config.php menyediakan $pdo

$errors = [];
$success = false;

// Pastikan ada ISBN di URL
if (!isset($_GET['isbn']) || trim($_GET['isbn']) === '') {
    echo "<h3 style='color:red;text-align:center;margin-top:50px;'>ID buku tidak ditemukan.</h3>";
    exit;
}
$isbn = trim($_GET['isbn']);

// Ambil data buku dari database
$stmt = $pdo->prepare("SELECT * FROM books WHERE isbn = :isbn");
$stmt->execute([':isbn' => $isbn]);
$book = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$book) {
    echo "<h3 style='color:red;text-align:center;margin-top:50px;'>Data buku tidak ditemukan.</h3>";
    exit;
}

// ✅ Tambahan baru: hitung stok sebenarnya dari tabel book_items
$book_id_stmt = $pdo->prepare("SELECT id FROM books WHERE isbn = :isbn");
$book_id_stmt->execute([':isbn' => $isbn]);
$book_id = $book_id_stmt->fetchColumn();

$stok_stmt = $pdo->prepare("SELECT COUNT(*) FROM book_items WHERE book_id = :book_id");
$stok_stmt->execute([':book_id' => $book_id]);
$stok_saat_ini = (int)$stok_stmt->fetchColumn();

// Masukkan hasilnya ke array $book agar tampil di form
$book['stok'] = $stok_saat_ini;

// ✅ Update lokasi rak untuk semua eksemplar buku
if (!empty($_POST['rak'])) {
    $update_rak = $pdo->prepare("UPDATE book_items SET rak = :rak WHERE book_id = :book_id");
    $update_rak->execute([
        ':rak' => $_POST['rak'],
        ':book_id' => $book_id
    ]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil input baru (tetap gunakan $isbn dari URL untuk WHERE)
    $judul = trim($_POST['judul'] ?? '');
    $kategori = trim($_POST['kategori'] ?? '');
    $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'] ?? '');
    $stok = intval($_POST['stok'] ?? 0); // stok baru dari form
    $gambar_path = $book['gambar'];

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

    // Upload gambar baru jika ada
    if (isset($_FILES['gambar']) && !empty($_FILES['gambar']['name'])) {
        $allowed = ['image/jpeg', 'image/png', 'image/webp'];
        if ($_FILES['gambar']['error'] === UPLOAD_ERR_OK) {
            $mime = $_FILES['gambar']['type'];
            $real_mime = @mime_content_type($_FILES['gambar']['tmp_name']);
            if (!in_array($mime, $allowed) && !in_array($real_mime, $allowed)) {
                $errors[] = "Format gambar harus JPG/PNG/WEBP.";
            } else {
                $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';
                $safe_name = 'cover_' . time() . '_' . uniqid() . '.' . $ext;
                $dest = $upload_dir . '/' . $safe_name;
                if (move_uploaded_file($_FILES['gambar']['tmp_name'], $dest)) {
                    // Hapus gambar lama jika ada
                    if (!empty($book['gambar']) && file_exists(__DIR__ . '/../' . $book['gambar'])) {
                        @unlink(__DIR__ . '/../' . $book['gambar']);
                    }
                    $gambar_path = 'Uploads/' . $safe_name;
                } else {
                    $errors[] = "Gagal mengunggah gambar.";
                }
            }
        } else {
            $errors[] = "Upload gambar gagal (kode: {$_FILES['gambar']['error']}).";
        }
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // Simpan perubahan data buku (termasuk stok kolom yang ada di db-mu)
            $sql = "UPDATE books SET 
                        judul = :judul,
                        kategori = :kategori,
                        penulis = :penulis,
                        sinopsis = :sinopsis,
                        halaman = :halaman,
                        penerbit = :penerbit,
                        tahun_terbit = :tahun_terbit,
                        berat = :berat,
                        panjang = :panjang,
                        lebar = :lebar,
                        bahasa = :bahasa,
                        stok = :stok,
                        gambar = :gambar
                    WHERE isbn = :isbn";
            $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,
                ':stok' => $stok,
                ':gambar' => $gambar_path,
                ':isbn' => $isbn
            ]);

            // ----------------------------
            // LOGIKA STOK FISIK (book_items)
            // ----------------------------
            // Ambil book_id berdasarkan ISBN
            $findBook = $pdo->prepare("SELECT id FROM books WHERE isbn = :isbn");
            $findBook->execute([':isbn' => $isbn]);
            $book_data = $findBook->fetch(PDO::FETCH_ASSOC);
            $book_id = $book_data['id'];

            // Hitung stok fisik saat ini (jumlah baris di book_items)
            $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM book_items WHERE book_id = :book_id");
            $count_stmt->execute([':book_id' => $book_id]);
            $stok_lama = (int)$count_stmt->fetchColumn();

            if ($stok > $stok_lama) {
                // Tambah stok baru sesuai selisih
                $selisih = $stok - $stok_lama;
            
                // Ambil dua huruf pertama judul (bersihkan karakter non-huruf)
                $kode_awal = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $judul), 0, 2)) ?: 'BK';
            
                // Cari nomor terakhir di book_items untuk buku ini
                $last_no_stmt = $pdo->prepare("SELECT no_buku FROM book_items WHERE book_id = :book_id ORDER BY id DESC LIMIT 1");
                $last_no_stmt->execute([':book_id' => $book_id]);
                $last_no = $last_no_stmt->fetchColumn();
            
                $start_num = 1;
                if ($last_no && preg_match('/-(\d{3})$/', $last_no, $matches)) {
                    $start_num = (int)$matches[1] + 1;
                }
            
                for ($i = 0; $i < $selisih; $i++) {
                    $nomor = str_pad($start_num + $i, 3, '0', STR_PAD_LEFT);
                    $no_buku = "{$kode_awal}-{$book_id}-{$nomor}"; // ⚡ Sama persis dengan sistem tambah buku
            
                    $insert_item = $pdo->prepare("INSERT INTO book_items (book_id, no_buku, rak, status) VALUES (:book_id, :no_buku, :rak, 'tersedia')");
                    $insert_item->execute([
                        ':book_id' => $book_id,
                        ':no_buku' => $no_buku,
                        ':rak' => $_POST['rak'] ?? 'A1'
                    ]);
                }
            

            } elseif ($stok < $stok_lama) {
                // Kurangi stok: hanya boleh menghapus eksemplar yang status = 'tersedia'
                $selisih = $stok_lama - $stok;

                // Ambil semua id eksemplar yang tersedia (urut dari paling baru)
                $avail_stmt = $pdo->prepare("SELECT id FROM book_items WHERE book_id = :book_id AND status = 'tersedia' ORDER BY id DESC");
                $avail_stmt->execute([':book_id' => $book_id]);
                $available_ids = $avail_stmt->fetchAll(PDO::FETCH_COLUMN);

                if (count($available_ids) < $selisih) {
                    // Tidak cukup eksemplar tersedia untuk dihapus -> batalkan transaksi dan beri pesan
                    throw new Exception("Tidak dapat mengurangi stok. Hanya " . count($available_ids) . " eksemplar 'tersedia', sedangkan diminta mengurangi $selisih. Pastikan buku yang dipinjam dikembalikan terlebih dahulu.");
                }

                // Hapus sejumlah id yang diperlukan (pilih yang terbaru/terakhir ditambahkan)
                $to_delete = array_slice($available_ids, 0, $selisih);
                // buat in-list yang aman (integer)
                $in = implode(',', array_map('intval', $to_delete));
                if (!empty($in)) {
                    $del_stmt = $pdo->prepare("DELETE FROM book_items WHERE id IN ($in)");
                    $del_stmt->execute();
                }
            }

            // commit transaksi jika semua berhasil
            $pdo->commit();
            $success = true;

            header("Location: daftarbuku.php?updated=1");
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = "Gagal memperbarui 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>Edit Buku - Pustakaia</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* --- CSS persis dari add_book.php --- */
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;}
img.preview { margin-top:10px; max-width:160px; border-radius:6px; }

/* 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; }
/* --- end CSS --- */
</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;">
                    <!-- Di sini DAFTAR BUKU yang aktif (hijau) -->
                    <li><a href="daftarbuku.php" class="active"><i class="fa fa-list"></i> Daftar Buku</a></li>
                    <li><a href="add_book.php"><i class="fa fa-plus"></i> Tambahkan Buku</a></li>
                </ul>
            </li>
            <li><a href="#"><i class="fa fa-users"></i> Kelola Anggota</a></li>
            <li><a href="#"><i class="fa fa-exchange-alt"></i> Kelola Peminjaman</a></li>
            <li><a href="#"><i class="fa fa-bell"></i> Notifikasi</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>Edit Buku</h1>
        <div class="form-card">
            <?php if ($success): ?>
                <div class="success">Data buku berhasil diperbarui.</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($book['judul']) ?>" required>

                <label>Kategori</label>
<div class="kategori-container">
  <?php
  $kategori_tersimpan = isset($book['kategori']) ? explode(', ', $book['kategori']) : [];
  $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):
      $selected = in_array($opt, $kategori_tersimpan) ? 'selected' : '';
  ?>
    <div class="kategori-item <?= $selected ?>" data-value="<?= htmlspecialchars($opt) ?>">
      <?= htmlspecialchars($opt) ?>
    </div>
  <?php endforeach; ?>
</div>
<input type="hidden" name="kategori" id="kategoriInput" value="<?= htmlspecialchars($book['kategori']) ?>">
<small>Klik kategori untuk memilih / membatalkan.</small>

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

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

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

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

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

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

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

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

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

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

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

                <label>Rak Penyimpanan</label>
                <input type="text" name="rak" placeholder="contoh: A1" value="<?php 
                      // ambil rak pertama dari book_items
                $rak_stmt = $pdo->prepare('SELECT rak FROM book_items WHERE book_id = :book_id LIMIT 1');
                $rak_stmt->execute([':book_id' => $book_id]);
                echo htmlspecialchars($rak_stmt->fetchColumn() ?: '');
                 ?>">

                <label>Gambar Cover Saat Ini</label><br>
                <?php if (!empty($book['gambar'])): ?>
                    <img src="../<?= htmlspecialchars($book['gambar']) ?>" class="preview" alt="Cover Buku">
                <?php else: ?>
                    <p><em>Tidak ada gambar</em></p>
                <?php endif; ?>

                <label>Ganti Gambar (opsional)</label>
                <input type="file" name="gambar" accept="image/*">

                <button type="submit">Simpan Perubahan</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>
