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

// Cek akses admin
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../Login/Login.php');
    exit;
}

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $judul        = trim($_POST['judul'] ?? '');
    $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);

    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) {
            $mime = mime_content_type($_FILES['gambar']['tmp_name']);
            if (in_array($mime, $allowed)) {
                $upload_dir = __DIR__ . '/../../Uploads';
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);

                $ext = strtolower(pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION));
                $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.";
                }
            } else {
                $errors[] = "Format gambar harus JPG/PNG/WEBP.";
            }
        } else {
            $errors[] = "Upload gambar gagal.";
        }
    }

    if (empty($errors)) {
        try {
            $sql = "INSERT INTO books 
                (judul, penulis, sinopsis, halaman, penerbit, tahun_terbit, berat, panjang, lebar, bahasa, isbn, stok, gambar, created_at) 
                VALUES 
                (:judul, :penulis, :sinopsis, :halaman, :penerbit, :tahun_terbit, :berat, :panjang, :lebar, :bahasa, :isbn, :stok, :gambar, NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                ':judul'        => $judul,
                ':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
            ]);

            $success = true;
        } catch (Exception $e) {
            $errors[] = "Gagal menambahkan buku: " . $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; }

/* 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 */
.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; }

/* Heading (hitam, besar, simple – sama kayak delete_book.php) */
main h1 {
  font-size:24px;
  color:#000;
  margin-bottom:20px;
  font-weight:600;
  border-bottom:2px solid #ddd;
  padding-bottom:10px;
}

/* Form nempel langsung, tanpa card */
.form-box {
  background:none;
  box-shadow:none;
  padding:0;
  border-radius:0;
  max-width:100%;
  margin-top:0;
}

/* Form fields */
.form-row { display:flex; gap:12px; flex-wrap:wrap; margin-bottom:12px; }
.form-col { flex:1 1 240px; min-width:200px; display:flex; flex-direction:column; }
label.field-label { font-weight:600; margin-bottom:6px; color:#333; font-size:14px; }

input[type="text"], input[type="number"], textarea, input[type="file"] {
  padding:8px 10px;
  border:1px solid #ddd;
  border-radius:4px;
  font-size:14px;
  background:#fff;
  width:100%;
  box-sizing:border-box;
}
textarea { min-height:100px; resize:vertical; }

input:focus, textarea:focus {
  border-color:#069797;
  box-shadow:0 0 4px rgba(6,151,151,0.12);
  outline:none;
}

/* Button */
.btn {
  padding:10px 14px;
  border-radius:6px;
  border:none;
  background:#069797;
  color:#fff;
  font-weight:600;
  cursor:pointer;
  font-size:14px;
}
.btn:hover { background:#056666; }

/* Pesan */
.msg-success { color:green; margin-bottom:10px; }
.msg-error { color:#a33a3a; margin-bottom: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;
    text-decoration:none;
}
.footer-right a:hover {
    text-decoration:underline;
    color:#069797;
}

/* Responsive */
@media (max-width:900px) {
  main { padding:16px; margin-left:0; }
  .container { flex-direction:column; }
  .sidebar { position:relative; width:100%; height:auto; border-right:none; border-bottom:1px solid #ddd; }
  footer { margin-left:0; }
}
</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">
                <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>
                    <li><a href="delete_book.php"><i class="fa fa-trash"></i> Hapus 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="#"><i class="fa fa-sign-out-alt"></i> Keluar</a></li>
        </ul>
    </aside>

    <!-- Main Content -->
    <main>
        <h1>Tambah Buku</h1>

        <?php if ($success): ?>
            <p class="msg-success">✅ Buku berhasil ditambahkan.</p>
        <?php endif; ?>
        <?php foreach ($errors as $err): ?>
            <p class="msg-error">⚠️ <?= htmlspecialchars($err) ?></p>
        <?php endforeach; ?>

        <div class="form-box">
            <form method="post" enctype="multipart/form-data">
                <div class="form-row">
                    <div class="form-col">
                        <label class="field-label">Judul</label>
                        <input type="text" name="judul" required>
                    </div>
                    <div class="form-col">
                        <label class="field-label">Penulis</label>
                        <input type="text" name="penulis" required>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-col" style="flex:1 1 100%;">
                        <label class="field-label">Sinopsis</label>
                        <textarea name="sinopsis" rows="4"></textarea>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-col">
                        <label class="field-label">Halaman</label>
                        <input type="number" name="halaman">
                    </div>
                    <div class="form-col">
                        <label class="field-label">Penerbit</label>
                        <input type="text" name="penerbit">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-col">
                        <label class="field-label">Tahun Terbit</label>
                        <input type="text" name="tahun_terbit">
                    </div>
                    <div class="form-col">
                        <label class="field-label">Bahasa</label>
                        <input type="text" name="bahasa">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-col">
                        <label class="field-label">Berat (gr)</label>
                        <input type="number" name="berat">
                    </div>
                    <div class="form-col">
                        <label class="field-label">Stok</label>
                        <input type="number" name="stok">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-col">
                        <label class="field-label">Panjang (cm)</label>
                        <input type="number" step="0.1" name="panjang">
                    </div>
                    <div class="form-col">
                        <label class="field-label">Lebar (cm)</label>
                        <input type="number" step="0.1" name="lebar">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-col">
                        <label class="field-label">ISBN</label>
                        <input type="text" name="isbn">
                    </div>
                    <div class="form-col">
                        <label class="field-label">Gambar Sampul</label>
                        <input type="file" name="gambar">
                    </div>
                </div>

                <div style="margin-top:10px;">
                    <button type="submit" class="btn">Tambah Buku</button>
                </div>
            </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>
// Toggle submenu
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';
    });
});
</script>
</body>
</html>
