<?php
require_once __DIR__ . '/../../admin/_nav.php';
$pageTitle  = 'Library';
$sidebarNav = adminNav();
$u = function($p) { return \Core\View::url($p); };
?>
<div class="page-header">
  <div><h1><i class="bi bi-book"></i> Library Management</h1><p>Books, borrowings & returns</p></div>
  <div style="display:flex;gap:8px">
    <a href="<?= $u('admin/library/borrowings') ?>" class="btn btn-secondary"><i class="bi bi-arrow-left-right"></i> Borrowings</a>
    <button onclick="openModal('addBookModal')" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Book</button>
  </div>
</div>

<!-- Stats -->
<div class="grid g4" style="margin-bottom:20px">
  <div class="stat-card">
    <div class="stat-icon si-blue"><i class="bi bi-book"></i></div>
    <div class="stat-info"><h3><?= $stats['total_books'] ?? 0 ?></h3><p>Total Titles</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-green"><i class="bi bi-stack"></i></div>
    <div class="stat-info"><h3><?= $stats['total_copies'] ?? 0 ?></h3><p>Total Copies</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-amber"><i class="bi bi-person-check"></i></div>
    <div class="stat-info"><h3><?= $stats['borrowed'] ?? 0 ?></h3><p>Currently Borrowed</p></div>
  </div>
  <div class="stat-card">
    <div class="stat-icon si-red"><i class="bi bi-exclamation-triangle"></i></div>
    <div class="stat-info"><h3><?= $stats['overdue'] ?? 0 ?></h3><p>Overdue</p></div>
    <?php if(($stats['overdue']??0)>0): ?>
    <div style="margin-left:auto"><a href="<?= $u('admin/library/borrowings?status=borrowed') ?>" class="btn btn-sm btn-secondary">View</a></div>
    <?php endif; ?>
  </div>
</div>

<!-- Filters -->
<div class="card" style="margin-bottom:16px">
  <div class="card-body" style="padding:12px 16px">
    <form method="GET" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
      <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search title, author, ISBN..." style="width:220px">
      <select name="category" style="width:160px">
        <option value="">All Categories</option>
        <?php foreach($categories as $c): ?>
        <option value="<?= htmlspecialchars($c['category']) ?>" <?= $cat===$c['category']?'selected':'' ?>><?= htmlspecialchars($c['category']) ?></option>
        <?php endforeach; ?>
      </select>
      <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i> Search</button>
      <?php if($search||$cat): ?><a href="<?= $u('admin/library') ?>" class="btn btn-secondary btn-sm"><i class="bi bi-x"></i> Clear</a><?php endif; ?>
    </form>
  </div>
</div>

<!-- Books Table -->
<div class="card">
  <div class="card-header">
    <h5><i class="bi bi-book"></i> Book Catalogue</h5>
    <span style="font-size:12px;color:var(--gray)"><?= $books['total'] ?? 0 ?> titles</span>
  </div>
  <div class="table-wrap"><table>
    <thead><tr><th>Title</th><th>Author</th><th>Category</th><th>ISBN</th><th>Shelf</th><th>Copies</th><th>Available</th><th>Actions</th></tr></thead>
    <tbody>
      <?php foreach($books['data'] as $b): ?>
      <tr>
        <td>
          <div style="font-weight:500"><?= htmlspecialchars($b['title']) ?></div>
          <?php if($b['publisher']): ?><div style="font-size:11px;color:var(--gray)"><?= htmlspecialchars($b['publisher']) ?> <?= $b['year'] ? '('.$b['year'].')' : '' ?></div><?php endif; ?>
        </td>
        <td style="font-size:13px"><?= htmlspecialchars($b['author'] ?? '—') ?></td>
        <td><?php if($b['category']): ?><span class="badge badge-info"><?= htmlspecialchars($b['category']) ?></span><?php else: ?>—<?php endif; ?></td>
        <td style="font-size:12px;font-family:monospace"><?= htmlspecialchars($b['isbn'] ?? '—') ?></td>
        <td style="font-size:12px"><?= htmlspecialchars($b['shelf'] ?? '—') ?></td>
        <td style="text-align:center"><strong><?= $b['total_copies'] ?></strong></td>
        <td style="text-align:center">
          <span class="badge <?= $b['available']>0?'badge-success':'badge-danger' ?>"><?= $b['available'] ?></span>
        </td>
        <td style="white-space:nowrap">
          <?php if($b['available']>0): ?>
          <button onclick="openBorrowModal(<?= $b['id'] ?>, '<?= htmlspecialchars($b['title'], ENT_QUOTES) ?>')" class="btn btn-sm btn-primary" title="Issue Book"><i class="bi bi-arrow-right-circle"></i> Issue</button>
          <?php endif; ?>
          <button onclick="openEditBook(<?= htmlspecialchars(json_encode($b), ENT_QUOTES) ?>)" class="btn btn-sm btn-secondary" title="Edit"><i class="bi bi-pencil"></i></button>
          <form method="POST" action="<?= $u('admin/library/'.$b['id'].'/delete') ?>" style="display:inline" onsubmit="return confirm('Delete this book?')">
            <?= \Core\View::csrf() ?>
            <button type="submit" class="btn btn-sm btn-danger" title="Delete"><i class="bi bi-trash"></i></button>
          </form>
        </td>
      </tr>
      <?php endforeach; ?>
      <?php if(empty($books['data'])): ?>
      <tr><td colspan="8" style="text-align:center;padding:40px;color:var(--gray)">
        <i class="bi bi-book" style="font-size:32px;display:block;margin-bottom:8px"></i>
        No books found. <button onclick="openModal('addBookModal')" class="btn btn-sm btn-primary" style="margin-left:8px">Add First Book</button>
      </td></tr>
      <?php endif; ?>
    </tbody>
  </table></div>
  <div style="padding:14px"><?= \Core\View::paginate($books, $u('admin/library')) ?></div>
</div>

<!-- Add Book Modal -->
<div class="modal" id="addBookModal"><div class="modal-box" style="max-width:580px">
  <div class="card-header"><h5><i class="bi bi-plus-lg"></i> Add Book</h5><button onclick="closeModal('addBookModal')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" action="<?= $u('admin/library/store') ?>">
      <?= \Core\View::csrf() ?>
      <div class="grid g2">
        <div class="form-group" style="grid-column:span 2"><label>Title *</label><input type="text" name="title" required placeholder="Book title"></div>
        <div class="form-group"><label>Author</label><input type="text" name="author" placeholder="Author name"></div>
        <div class="form-group"><label>ISBN</label><input type="text" name="isbn" placeholder="ISBN number"></div>
        <div class="form-group"><label>Category</label><input type="text" name="category" placeholder="e.g. Science, Literature, Math" list="catList"></div>
        <div class="form-group"><label>Publisher</label><input type="text" name="publisher" placeholder="Publisher name"></div>
        <div class="form-group"><label>Year Published</label><input type="number" name="year" min="1900" max="<?= date('Y') ?>" placeholder="<?= date('Y') ?>"></div>
        <div class="form-group"><label>Total Copies *</label><input type="number" name="total_copies" value="1" min="1" required></div>
        <div class="form-group"><label>Shelf / Location</label><input type="text" name="shelf" placeholder="e.g. A1, Science Shelf"></div>
      </div>
      <div class="form-group"><label>Description</label><textarea name="description" rows="2" placeholder="Optional description"></textarea></div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Add Book</button>
    </form>
    <datalist id="catList">
      <?php foreach($categories as $c): ?><option value="<?= htmlspecialchars($c['category']) ?>"><?php endforeach; ?>
    </datalist>
  </div>
</div></div>

<!-- Edit Book Modal -->
<div class="modal" id="editBookModal"><div class="modal-box" style="max-width:580px">
  <div class="card-header"><h5><i class="bi bi-pencil"></i> Edit Book</h5><button onclick="closeModal('editBookModal')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" id="editBookForm" action="">
      <?= \Core\View::csrf() ?>
      <div class="grid g2">
        <div class="form-group" style="grid-column:span 2"><label>Title *</label><input type="text" name="title" id="eb_title" required></div>
        <div class="form-group"><label>Author</label><input type="text" name="author" id="eb_author"></div>
        <div class="form-group"><label>ISBN</label><input type="text" name="isbn" id="eb_isbn"></div>
        <div class="form-group"><label>Category</label><input type="text" name="category" id="eb_category" list="catList"></div>
        <div class="form-group"><label>Publisher</label><input type="text" name="publisher" id="eb_publisher"></div>
        <div class="form-group"><label>Year</label><input type="number" name="year" id="eb_year"></div>
        <div class="form-group"><label>Total Copies *</label><input type="number" name="total_copies" id="eb_copies" min="1" required></div>
        <div class="form-group"><label>Shelf</label><input type="text" name="shelf" id="eb_shelf"></div>
      </div>
      <div class="form-group"><label>Description</label><textarea name="description" id="eb_desc" rows="2"></textarea></div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Save Changes</button>
    </form>
  </div>
</div></div>

<!-- Issue/Borrow Modal -->
<div class="modal" id="borrowModal"><div class="modal-box" style="max-width:460px">
  <div class="card-header"><h5><i class="bi bi-arrow-right-circle"></i> Issue Book</h5><button onclick="closeModal('borrowModal')" style="background:none;border:none;cursor:pointer;font-size:20px">&times;</button></div>
  <div class="card-body">
    <form method="POST" action="<?= $u('admin/library/borrow') ?>">
      <?= \Core\View::csrf() ?>
      <input type="hidden" name="book_id" id="borrow_book_id">
      <div style="background:var(--light);border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:13px;font-weight:600" id="borrow_book_title"></div>

      <!-- Borrower type toggle -->
      <div class="form-group">
        <label>Issue To</label>
        <div style="display:flex;gap:8px;margin-bottom:10px">
          <button type="button" id="btn_student" onclick="toggleBorrower('student')" class="btn btn-primary btn-sm">Student</button>
          <button type="button" id="btn_teacher" onclick="toggleBorrower('teacher')" class="btn btn-secondary btn-sm">Teacher</button>
        </div>
        <input type="hidden" name="borrower_type" id="borrower_type" value="student">
      </div>

      <div class="form-group" id="student_picker">
        <label>Select Student *</label>
        <select name="borrower_id" id="student_select" required>
          <option value="">-- Select Student --</option>
          <?php foreach($students as $s): ?>
          <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?> (<?= htmlspecialchars($s['assessment_no']) ?>)</option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="form-group" id="teacher_picker" style="display:none">
        <label>Select Teacher *</label>
        <select name="borrower_id" id="teacher_select" disabled>
          <option value="">-- Select Teacher --</option>
          <?php foreach($teachers as $t): ?>
          <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?><?= $t['ref'] ? ' ('.$t['ref'].')' : '' ?></option>
          <?php endforeach; ?>
        </select>
      </div>

      <div class="form-group">
        <label>Due Date *</label>
        <input type="date" name="due_date" value="<?= date('Y-m-d', strtotime('+14 days')) ?>" required>
      </div>
      <button type="submit" class="btn btn-primary"><i class="bi bi-arrow-right-circle"></i> Issue Book</button>
    </form>
  </div>
</div></div>

<?php
$bookBase = $u('admin/library/');
$extraScripts = '<script>
function openBorrowModal(id, title) {
    document.getElementById("borrow_book_id").value = id;
    document.getElementById("borrow_book_title").textContent = title;
    toggleBorrower("student");
    openModal("borrowModal");
}
function toggleBorrower(type) {
    document.getElementById("borrower_type").value = type;
    var isStudent = type === "student";
    document.getElementById("student_picker").style.display  = isStudent ? "block" : "none";
    document.getElementById("teacher_picker").style.display  = isStudent ? "none"  : "block";
    document.getElementById("student_select").disabled = !isStudent;
    document.getElementById("teacher_select").disabled =  isStudent;
    document.getElementById("student_select").required =  isStudent;
    document.getElementById("teacher_select").required = !isStudent;
    document.getElementById("btn_student").className = isStudent ? "btn btn-primary btn-sm" : "btn btn-secondary btn-sm";
    document.getElementById("btn_teacher").className = isStudent ? "btn btn-secondary btn-sm" : "btn btn-primary btn-sm";
}
function openEditBook(b) {
    document.getElementById("editBookForm").action = "'.$bookBase.'" + b.id + "/update";
    document.getElementById("eb_title").value     = b.title;
    document.getElementById("eb_author").value    = b.author || "";
    document.getElementById("eb_isbn").value      = b.isbn || "";
    document.getElementById("eb_category").value  = b.category || "";
    document.getElementById("eb_publisher").value = b.publisher || "";
    document.getElementById("eb_year").value      = b.year || "";
    document.getElementById("eb_copies").value    = b.total_copies;
    document.getElementById("eb_shelf").value     = b.shelf || "";
    document.getElementById("eb_desc").value      = b.description || "";
    openModal("editBookModal");
}
</script>';
?>
