<?php
/**
 * Template Library Page Multi OPAC
 * Path: plugins/multi_opac_path/template/library_page.tpl
 * Version: 1.1.2 (Fixed News Section & Lib ID Variable)
 */

if (!defined('INDEX_AUTH')) {
    die("Direct access not allowed");
}

// ============================================================
// AMBIL DATA LIBRARY
// ============================================================
$library = $GLOBALS['current_library'] ?? null;
if (!$library) {
    $lib_slug = $_GET['lib'] ?? 'pusat';
    $library = getLibraryBySlug($lib_slug);
}
if (!$library) {
    echo "<div class='container mt-5'><div class='alert alert-danger'>Perpustakaan tidak ditemukan</div></div>";
    exit;
}

$library_id   = $library['library_id'];
$library_name = $library['library_name'];
$library_slug = $library['url_slug'] ?? '';

// ============================================================
// AMBIL QUERY PENCARIAN & FILTER SELEKSI
// ============================================================
$searchQuery     = $_GET['search_query'] ?? $_GET['keywords'] ?? $GLOBALS['search_query'] ?? '';
$selectedAuthor  = $_GET['author'] ?? '';
$selectedTopic = $_GET['topic'] ?? '';
$selectedGmd     = $_GET['gmd'] ?? '';

// DETEKSI TAMPILAN: true jika user sedang mencari/memfilter sesuatu
$isSearching = !empty($searchQuery) || !empty($selectedAuthor) || !empty($selectedTopic) || !empty($selectedGmd) || isset($_GET['callnumber']);

// ============================================================
// AMBIL TEMA DARI DATABASE
// ============================================================
$themeFromDb = getTheme($library_id);
if ($themeFromDb) {
    $themeData = [
        'primary_color'   => $themeFromDb['primary_color'] ?? '#0d6efd',
        'secondary_color' => $themeFromDb['secondary_color'] ?? '#212529',
        'header_text'     => $themeFromDb['header_text'] ?? $library_name,
        'footer_text'     => $themeFromDb['footer_text'] ?? '© ' . date('Y') . ' ' . $library_name,
        'logo'            => $themeFromDb['logo'] ?? ''
    ];
} else {
    $themeData = [
        'primary_color'   => '#0d6efd',
        'secondary_color' => '#212529',
        'header_text'     => $library_name,
        'footer_text'     => '© ' . date('Y') . ' ' . $library_name,
        'logo'            => ''
    ];
}

// ============================================================
// AMBIL DATA KOLEKSI
// ============================================================
$biblios    = getBibliosByLibrary($library_id, 10);
$contents   = getContentByLibrary($library_id, 10);
$librarians = getLibrariansByLibrary($library_id, 10);
$popular    = getPopularCollections($library_id, 5);
$topReaders = getTopReaders($library_id, 5);

// SEARCH & FACET
$searchResults = [];
if ($isSearching) {
    $searchResults = searchBibliosByLibrary($searchQuery, $library_id, 20);
} elseif (isset($GLOBALS['search_results']) && !empty($GLOBALS['search_results'])) {
    $searchResults = $GLOBALS['search_results'];
}

// GENERATE FACETS UNTUK FILTER SIDEBAR
$facets = ['authors' => [], 'topics' => [], 'gmd' => []];
if (!empty($searchResults)) {
    $authCounts = [];
    $subjCounts = [];
    $gmdCounts  = [];

    foreach ($searchResults as $res) {
        if (!empty($res['author'])) {
            $authCounts[$res['author']] = ($authCounts[$res['author']] ?? 0) + 1;
        }
if (!empty($res['topic'])) {
    $subjCounts[$res['topic']] = ($subjCounts[$res['topic']] ?? 0) + 1;
}
        if (!empty($res['gmd_name'])) {
            $gmdCounts[$res['gmd_name']] = ($gmdCounts[$res['gmd_name']] ?? 0) + 1;
        }
    }

    foreach ($authCounts as $name => $count) {
        $facets['authors'][] = ['name' => $name, 'count' => $count];
    }
foreach ($topicCounts as $name => $count) {
    $facets['topics'][] = ['name' => $name, 'count' => $count];
}
    foreach ($gmdCounts as $name => $count) {
        $facets['gmd'][] = ['name' => $name, 'count' => $count];
    }
}

// ============================================================
// AMBIL KONFIGURASI
// ============================================================
$allLibraries   = getAllLibraries();
$config          = getMultiOpacConfig();
$showBadge       = $config['show_library_badge'] ?? 1;
$enableSwitcher  = $config['enable_library_switcher'] ?? 1;

// TOPIC ICONS DENGAN GAMBAR
$topics = [
    ['id' => 0, 'name' => 'Computer Science', 'icon' => '0-chemical.png'],
    ['id' => 1, 'name' => 'Philosophy & Psychology', 'icon' => '1-memory.png'],
    ['id' => 2, 'name' => 'Religion', 'icon' => '2-mosque.png'],
    ['id' => 3, 'name' => 'Social Sciences', 'icon' => '3-diploma.png'],
    ['id' => 4, 'name' => 'Language', 'icon' => '4-translation.png'],
    ['id' => 5, 'name' => 'Pure Science', 'icon' => '5-math.png'],
    ['id' => 6, 'name' => 'Applied Sciences', 'icon' => '6-blackboard.png'],
    ['id' => 7, 'name' => 'Art & Recreation', 'icon' => '7-quill.png'],
    ['id' => 8, 'name' => 'Literature', 'icon' => '8-books.png'],
    ['id' => 9, 'name' => 'History & Geography', 'icon' => '9-return-to-the-past.png'],
];

$navLibSlug = $library_slug;

// DETEKSI STATUS LOGIN MEMBER (Native SLiMS)
$isMemberPage = isset($_GET['p']) &&
    in_array($_GET['p'], ['member', 'member-login']);

$isMemberLoggedIn = class_exists('utility')
    ? utility::isMemberLogin()
    : !empty($_SESSION['mid']);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($library_name) ?> | OPAC Multi Perpustakaan</title>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="<?= SWB ?>template/default/assets/plugin/font-awesome/css/fontawesome-all.min.css">
    
    <!-- Bootstrap CSS -->
    <link href="<?= SWB ?>template/default/assets/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- CSS Kustom -->
    <link rel="stylesheet" href="<?= SWB ?>plugins/multi_opac_path/assets/css/opac-style.css">
    <link rel="stylesheet" href="<?= SWB ?>plugins/multi_opac_path/assets/css/landing_page.css">
    
    <style>
        :root {
            --primary-color: <?= htmlspecialchars($themeData['primary_color']) ?>;
            --secondary-color: <?= htmlspecialchars($themeData['secondary_color']) ?>;
        }
    </style>    
</head>
<body>

<!-- ============================================================
NAVBAR LIBRARY (PAKAI NAVBAR LIBRARY TERPIFAH)
============================================================ -->
<?php
// Ambil lib slug dari parameter URL atau Session agar navbar tetap membaca state perpustakaan aktif
$current_lib_slug = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? $library_slug ?? '';
if (!empty($current_lib_slug)) {
    $_SESSION['multi_opac']['last_library_slug'] = $current_lib_slug;
}

$GLOBALS['nav_lib_slug']     = $current_lib_slug;
$GLOBALS['nav_library_name'] = $library_name ?? 'Perpustakaan';
$GLOBALS['nav_theme']        = $themeData ?? [];

// POINT PERBAIKAN: Memanggil _navbar_library.inc.php secara konsisten
$navbar_file = __DIR__ . '/_navbar_library.inc.php';
if (file_exists($navbar_file)) {
    include $navbar_file;
} else {
    // Fallback jika file _navbar_library.inc.php tidak ditemukan
    if (file_exists(__DIR__ . '/_navbar_plugin.inc.php')) {
        include __DIR__ . '/_navbar_plugin.inc.php';
    }
}
?>

<!-- HERO HEADER -->
<header class="landing-header py-5">
    <div class="container">
        <div class="row justify-content-center text-center mb-4">
            <div class="col-lg-8">
                <div class="header-brand d-flex align-items-center justify-content-center gap-3 mb-2">
                    <?php if (!empty($themeData['logo'])): ?>
                        <img src="<?= htmlspecialchars($themeData['logo']) ?>" alt="Logo" class="header-logo" style="max-height: 60px;">
                    <?php endif; ?>
                    <h1 class="header-title text-white mb-0 fw-bold">
                        <?= htmlspecialchars($themeData['header_text']) ?>
                    </h1>
                </div>
                <p class="lead text-white-50">Jelajahi dan temukan koleksi buku dari <?= htmlspecialchars($library_name) ?>.</p>
            </div>
        </div>

        <!-- FORM PENCARIAN -->
        <div class="row justify-content-center">
            <div class="col-lg-10">
                <form action="index.php" method="get">
                    <input type="hidden" name="p" value="multi-opac">
                    <input type="hidden" name="lib" value="<?= htmlspecialchars($library_slug) ?>">
                    <div class="integrated-search-box">
                        <div class="search-input-group ms-2">
                            <i class="fa-solid fa-magnifying-glass text-muted ms-2"></i>
                            <input type="text" name="search_query" class="form-control" placeholder="Ketik judul buku, pengarang, ISBN, atau subjek..." value="<?= htmlspecialchars($searchQuery) ?>" autocomplete="off">
                        </div>
                        <button type="submit" class="btn btn-search text-white">
                            <i class="fa-solid fa-magnifying-glass me-1"></i> Cari
                        </button>
                    </div>
                </form>
                
                <div class="text-center mt-3">
                    <button type="button" class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#adv-modal-plugin">
                        <i class="fa-solid fa-sliders me-1"></i> Advanced Search
                    </button>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- MAIN CONTENT LAYOUT -->
<main class="container my-4">

    <!-- 1. AREA MEMBER (ADOPSI - PAKAI member_content.tpl) -->
    <?php if (!empty($_SESSION['m_id']) && (isset($_GET['p']) && $_GET['p'] === 'member')): ?>
        
        <div class="row justify-content-center">
            <div class="col-lg-12">
                <div class="card border-0 shadow-sm p-4 rounded-3">
                    <?= $GLOBALS['custom_page_content'] ?? '<div class="alert alert-info">' . __('Konten member tidak tersedia.') . '</div>' ?>
                </div>
            </div>
        </div>
    
    
        <!-- 2. AREA KONTEN KUSTOM (Berita, Profil, Halaman Ekstra) -->
        <?php elseif (!empty($GLOBALS['custom_page_content'])): ?>
    
            <div class="row justify-content-center">
                <div class="col-lg-10">
                    <div class="card border-0 shadow-sm p-4 rounded-3">
                        <?= $GLOBALS['custom_page_content'] ?>
                    </div>
                </div>
            </div>

    <!-- 3. AREA KONTEN UTAMA (Pencarian & Halaman Depan Perpustakaan) -->
    <?php else: ?>

        <div class="row <?= $isSearching ? '' : 'justify-content-center' ?>">
            
            <!-- SIDEBAR FILTER (Hanya Muncul Jika Sedang Mencari) -->
            <?php if ($isSearching): ?>
                <aside class="col-lg-3 mb-4">
                    <div class="card border-0 shadow-sm rounded-3 p-3 filter-sidebar">
                        <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                            <h5 class="fw-bold mb-0 fs-6"><i class="fa-solid fa-filter me-2 text-primary"></i>Filter Hasil</h5>
                            <?php if (!empty($selectedAuthor) || !empty($selectedTopic) || !empty($selectedGmd)): ?>
                                <a href="index.php?p=multi-opac&lib=<?= htmlspecialchars($library_slug) ?>&search_query=<?= urlencode($searchQuery) ?>" class="btn btn-sm btn-outline-danger py-0 px-2" style="font-size: 0.75rem;">Reset</a>
                            <?php endif; ?>
                        </div>

                        <!-- Filter Pengarang -->
                        <?php if (!empty($facets['authors'])): ?>
                            <div class="filter-group mb-3">
                                <h6 class="filter-group-title"><i class="fa-solid fa-user me-1"></i> Pengarang</h6>
                                <ul class="filter-list">
                                    <?php foreach ($facets['authors'] as $auth): ?>
                                        <li>
                                            <a href="index.php?p=multi-opac&lib=<?= htmlspecialchars($library_slug) ?>&search_query=<?= urlencode($searchQuery) ?>&author=<?= urlencode($auth['name']) ?>" 
                                               class="<?= ($selectedAuthor === $auth['name']) ? 'fw-bold text-primary active' : '' ?>">
                                                <span class="text-truncate" style="max-width: 140px;"><?= htmlspecialchars($auth['name']) ?></span>
                                                <span class="badge bg-light text-dark rounded-pill"><?= $auth['count'] ?></span>
                                            </a>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>

                        <!-- Filter Topik / Subjek -->
                        <?php if (!empty($facets['topics']) && is_array($facets['topics'])): ?>
                            <div class="filter-group mb-3">
                                <h6 class="filter-group-title"><i class="fa-solid fa-tag me-1"></i> Topik / Subjek</h6>
                                <ul class="filter-list">
                                    <?php 
                                    $currLibSlug     = is_string($library_slug ?? null) ? $library_slug : ($library['library_slug'] ?? '');
                                    $currSearchQuery = is_string($searchQuery ?? null) ? $searchQuery : '';
                                    $currSelTopic    = is_string($selectedTopic ?? null) ? $selectedTopic : '';

                                    foreach ($facets['topics'] as $topic): 
                                        $rawName = $topic['name'] ?? $topic['topic'] ?? (is_string($topic) ? $topic : '');
                                        $topicName = is_array($rawName) ? reset($rawName) : (string)$rawName;
                                        $topicCount = is_array($topic['count'] ?? null) ? ($topic['count'][0] ?? 0) : ($topic['count'] ?? 0);

                                        if (empty($topicName)) continue;
                                    ?>
                                        <li>
                                            <a href="index.php?p=multi-opac&lib=<?= htmlspecialchars($currLibSlug) ?>&search_query=<?= urlencode($currSearchQuery) ?>&topic=<?= urlencode($topicName) ?>" 
                                               class="<?= ($currSelTopic === $topicName) ? 'fw-bold text-primary active' : '' ?>">
                                                <span class="text-truncate d-inline-block" style="max-width: 140px; vertical-align: middle;">
                                                    <?= htmlspecialchars($topicName) ?>
                                                </span>
                                                <span class="badge bg-light text-dark rounded-pill"><?= htmlspecialchars((string)$topicCount) ?></span>
                                            </a>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>

                        <!-- Filter Format / GMD -->
                        <?php if (!empty($facets['gmd'])): ?>
                            <div class="filter-group">
                                <h6 class="filter-group-title"><i class="fa-solid fa-compact-disc me-1"></i> Format (GMD)</h6>
                                <ul class="filter-list">
                                    <?php foreach ($facets['gmd'] as $gmd): ?>
                                        <li>
                                            <a href="index.php?p=multi-opac&lib=<?= htmlspecialchars($library_slug) ?>&search_query=<?= urlencode($searchQuery) ?>&gmd=<?= urlencode($gmd['name']) ?>" 
                                               class="<?= ($selectedGmd === $gmd['name']) ? 'fw-bold text-primary active' : '' ?>">
                                                <span class="text-truncate" style="max-width: 140px;"><?= htmlspecialchars($gmd['name']) ?></span>
                                                <span class="badge bg-light text-dark rounded-pill"><?= $gmd['count'] ?></span>
                                            </a>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                    </div>
                </aside>
            <?php endif; ?>

            <!-- KONTEN UTAMA (Kanan Sidebar) -->
            <div class="<?= $isSearching ? 'col-lg-9' : 'col-lg-10 col-xl-9' ?>">
                
<!-- TOPIC ICONS - HANYA TAMPIL SAAT TIDAK MENCARI -->
<?php if (!$isSearching && !empty($topics)): ?>
    <section class="mb-4">
        <ul class="topic-grid">
            <?php foreach ($topics as $topic): ?>
                <li>
                    <a href="<?= buildLibraryUrl('multi-opac', $library_slug, ['callnumber' => $topic['id'], 'search' => 'search']) ?>">
                        <img src="<?= SWB ?>template/default/assets/images/<?= $topic['icon'] ?>" alt="<?= htmlspecialchars($topic['name']) ?>" loading="lazy">
                        <span><?= htmlspecialchars($topic['name']) ?></span>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
    </section>
<?php endif; ?>

                <!-- KONDISI A: HASIL PENCARIAN -->
                <?php if ($isSearching): ?>
                    <section class="mb-5">
                        <div class="section-header d-flex justify-content-between align-items-center mb-3">
                            <h3 class="section-title h4 mb-0">
                                <i class="fa-solid fa-list-check text-primary me-2"></i>Hasil Pencarian: "<?= htmlspecialchars($searchQuery) ?>"
                                <span class="badge bg-info text-dark fs-6 font-normal ms-2">
                                    <?= htmlspecialchars($library_name) ?>
                                </span>
                            </h3>
                            <span class="text-muted small"><?= count($searchResults) ?> hasil ditemukan</span>
                        </div>
                        
                        <?php if (count($searchResults) > 0): ?>
                            <div class="row g-4">
                                <?php foreach ($searchResults as $b): ?>
                                    <div class="col-sm-6 col-md-4 <?= $isSearching ? 'col-lg-4' : 'col-lg-3' ?>">
                                        <div class="card-modern h-100 d-flex flex-column justify-content-between">
                                            <div>
                                                <div class="book-cover">
                                                    <?php if (!empty($b['image'])): ?>
                                                        <img src="<?= SWB . 'images/docs/' . htmlspecialchars($b['image']) ?>" alt="<?= htmlspecialchars($b['title']) ?>">
                                                    <?php else: ?>
                                                        <i class="fa-solid fa-book-open"></i>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="p-3">
                                                    <h6 class="card-title text-truncate-2 fw-semibold mb-2 text-dark" title="<?= htmlspecialchars($b['title'] ?? 'Tanpa Judul') ?>">
                                                        <?= htmlspecialchars($b['title'] ?? 'Tanpa Judul') ?>
                                                    </h6>
                                                    <?php if (!empty($b['author'])): ?>
                                                        <small class="text-muted d-block mb-1">
                                                            <i class="fa-regular fa-user me-1"></i> <?= htmlspecialchars($b['author']) ?>
                                                        </small>
                                                    <?php endif; ?>
                                                    <?php if (!empty($showBadge) && !empty($b['library_id'])): ?>
                                                        <span class="library-badge"><?= htmlspecialchars(getLibraryNameById($b['library_id'])) ?></span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            <div class="p-3 pt-0">
                                                <a href="index.php?p=multi-opac&lib=<?= htmlspecialchars($library_slug) ?>&action=detail&id=<?= $b['biblio_id'] ?>" class="btn btn-sm btn-outline-primary w-100 rounded-pill">
                                                    Lihat Detail
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <!-- PAGINASI PENCARIAN -->
                            <?php
                            $limit = 20;
                            $currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
                            $totalResults = isset($GLOBALS['total_search_results']) ? $GLOBALS['total_search_results'] : count($searchResults);
                            $totalPages = ceil($totalResults / $limit);
                            ?>
                            
                            <?php if ($totalPages > 1): ?>
                                <nav aria-label="Page navigation" class="mt-4">
                                    <ul class="pagination justify-content-center">
                                        <!-- Tombol Sebelumnya -->
                                        <?php if ($currentPage > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="<?= buildLibraryUrl('multi-opac', $library_slug, ['search_query' => $searchQuery, 'page' => $currentPage - 1]) ?>">
                                                    <i class="fa-solid fa-chevron-left"></i> Sebelumnya
                                                </a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled">
                                                <span class="page-link"><i class="fa-solid fa-chevron-left"></i> Sebelumnya</span>
                                            </li>
                                        <?php endif; ?>
                                        
                                        <!-- Nomor Halaman -->
                                        <?php 
                                        $startPage = max(1, $currentPage - 2);
                                        $endPage = min($totalPages, $currentPage + 2);
                                        ?>
                                        
                                        <?php if ($startPage > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="<?= buildLibraryUrl('multi-opac', $library_slug, ['search_query' => $searchQuery, 'page' => 1]) ?>">1</a>
                                            </li>
                                            <?php if ($startPage > 2): ?>
                                                <li class="page-item disabled"><span class="page-link">…</span></li>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        
                                        <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                                            <li class="page-item <?= ($i == $currentPage) ? 'active' : '' ?>">
                                                <a class="page-link" href="<?= buildLibraryUrl('multi-opac', $library_slug, ['search_query' => $searchQuery, 'page' => $i]) ?>">
                                                    <?= $i ?>
                                                </a>
                                            </li>
                                        <?php endfor; ?>
                                        
                                        <?php if ($endPage < $totalPages): ?>
                                            <?php if ($endPage < $totalPages - 1): ?>
                                                <li class="page-item disabled"><span class="page-link">…</span></li>
                                            <?php endif; ?>
                                            <li class="page-item">
                                                <a class="page-link" href="<?= buildLibraryUrl('multi-opac', $library_slug, ['search_query' => $searchQuery, 'page' => $totalPages]) ?>"><?= $totalPages ?></a>
                                            </li>
                                        <?php endif; ?>
                                        
                                        <!-- Tombol Selanjutnya -->
                                        <?php if ($currentPage < $totalPages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="<?= buildLibraryUrl('multi-opac', $library_slug, ['search_query' => $searchQuery, 'page' => $currentPage + 1]) ?>">
                                                    Selanjutnya <i class="fa-solid fa-chevron-right"></i>
                                                </a>
                                            </li>
                                        <?php else: ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">Selanjutnya <i class="fa-solid fa-chevron-right"></i></span>
                                            </li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>
                            <?php endif; ?>
                            
                        <?php else: ?>
                            <div class="card-modern p-4 text-center">
                                <p class="text-muted mb-0"><i class="fa-solid fa-circle-info me-2"></i> Tidak ditemukan koleksi yang cocok dengan pencarian Anda.</p>
                            </div>
                        <?php endif; ?>
                    </section>
                <?php endif; ?>

                <!-- KONDISI B: HALAMAN DEPAN PERPUSTAKAAN (Tampil Jika TIDAK Sedang Mencari) -->
                <?php if (!$isSearching): ?>
                    
                    <!-- SEKSI KOLEKSI POPULER & PEMBACA TERBANYAK -->
                    <div class="row g-4 mb-5">
                        <!-- Popular Collection -->
                        <div class="col-lg-6">
                            <section class="h-100">
                                <div class="section-header mb-3">
                                    <h3 class="section-title h4"><i class="fa-solid fa-star text-warning me-2"></i>Koleksi Populer</h3>
                                    <small class="text-muted"><?= htmlspecialchars($library_name) ?></small>
                                </div>
                                
                                <?php if (!empty($popular) && count($popular) > 0): ?>
                                    <div class="d-flex flex-column gap-2">
                                        <?php foreach ($popular as $index => $b): ?>
                                            <div class="card-modern p-2 d-flex align-items-center">
                                                <span class="rank-number"><?= $index + 1 ?></span>
                                                <div class="overflow-hidden">
                                                    <h6 class="card-title text-truncate mb-0 text-dark"><?= htmlspecialchars($b['title'] ?? 'Tanpa Judul') ?></h6>
                                                    <small class="text-muted"><i class="fa-regular fa-eye me-1"></i> <?= $b['loan_count'] ?? 0 ?> x dipinjam</small>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="card-modern p-4 text-center">
                                        <p class="text-muted mb-0"><i class="fa-solid fa-circle-info me-2"></i> Belum ada data koleksi populer.</p>
                                    </div>
                                <?php endif; ?>
                            </section>
                        </div>

                        <!-- Top Readers -->
                        <div class="col-lg-6">
                            <section class="h-100">
                                <div class="section-header mb-3">
                                    <h3 class="section-title h4"><i class="fa-solid fa-trophy text-warning me-2"></i>Pembaca Terbanyak</h3>
                                    <small class="text-muted"><?= htmlspecialchars($library_name) ?></small>
                                </div>
                                
                                <?php if (!empty($topReaders) && count($topReaders) > 0): ?>
                                    <div class="d-flex flex-column gap-2">
                                        <?php foreach ($topReaders as $i => $m): ?>
                                            <div class="card-modern p-2 d-flex align-items-center">
                                                <span class="rank-number"><?= $i + 1 ?></span>
                                                <div class="overflow-hidden">
                                                    <h6 class="card-title text-truncate mb-0 text-dark"><?= htmlspecialchars($m['member_name'] ?? 'Anggota') ?></h6>
                                                    <small class="text-muted"><i class="fa-solid fa-book-open me-1"></i> <?= $m['loan_count'] ?? 0 ?> buku dipinjam</small>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="card-modern p-4 text-center">
                                        <p class="text-muted mb-0"><i class="fa-solid fa-circle-info me-2"></i> Belum ada data pembaca terbanyak.</p>
                                    </div>
                                <?php endif; ?>
                            </section>
                        </div>
                    </div>

                    <!-- SEKSI STATISTIK -->
                    <section class="row g-3 mb-5">
                        <div class="col-md-4">
                            <div class="stat-card d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="text-muted small fw-semibold">Total Koleksi</span>
                                    <h3 class="fw-bold mb-0 text-dark"><?= count($biblios ?? []) ?>+</h3>
                                    <small class="text-muted"><?= htmlspecialchars($library_name) ?></small>
                                </div>
                                <div class="stat-icon"><i class="fa-solid fa-book"></i></div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="text-muted small fw-semibold">Informasi & Berita</span>
                                    <h3 class="fw-bold mb-0 text-dark"><?= count($contents ?? []) ?>+</h3>
                                    <small class="text-muted"><?= htmlspecialchars($library_name) ?></small>
                                </div>
                                <div class="stat-icon"><i class="fa-regular fa-newspaper"></i></div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="stat-card d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="text-muted small fw-semibold">Pustakawan</span>
                                    <h3 class="fw-bold mb-0 text-dark"><?= count($librarians ?? []) ?>+</h3>
                                    <small class="text-muted"><?= htmlspecialchars($library_name) ?></small>
                                </div>
                                <div class="stat-icon"><i class="fa-solid fa-user-tie"></i></div>
                            </div>
                        </div>
                    </section>

                    <!-- SEKSI BERITA & INFORMASI -->
                    <section class="mb-5">
                        <div class="section-header d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <h3 class="section-title h4 mb-0"><i class="fa-solid fa-newspaper text-primary me-2"></i>Berita & Informasi</h3>
                                <small class="text-muted">Kabar terbaru dari <?= htmlspecialchars($library_name) ?></small>
                            </div>
                        </div>

                        <?php if (!empty($contents)): ?>
                            <div class="row g-3">
                                <?php 
                                $hasNews = false;
                                foreach ($contents as $news): 
                                    $isNews = isset($news['is_news']) && $news['is_news'] == 1;
                                    $isMatchingLib = !empty($news['library_id']) ? ($news['library_id'] == $library_id) : true;

                                    if ($isNews && $isMatchingLib): 
                                        $hasNews = true;
                                ?>
                                        <div class="col-md-6 col-lg-4">
                                            <div class="card border-0 shadow-sm h-100 rounded-3 overflow-hidden d-flex flex-column justify-content-between">
                                                <div class="card-body p-3">
                                                    <div class="d-flex justify-content-between align-items-center text-muted small mb-2">
                                                        <span>
                                                            <i class="fa-regular fa-calendar-alt me-1"></i>
                                                            <?= date('d M Y', strtotime($news['publish_date'] ?? $news['input_date'])) ?>
                                                        </span>
                                                        <?php if (!empty($showBadge) && !empty($news['library_id'])): ?>
                                                            <span class="badge bg-light text-secondary border"><?= htmlspecialchars(getLibraryNameById($news['library_id'])) ?></span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <h6 class="card-title fw-bold text-dark mb-2 text-truncate-2">
                                                        <?= htmlspecialchars($news['content_title'] ?? 'Tanpa Judul') ?>
                                                    </h6>
                                                    <p class="card-text text-muted small mb-0">
                                                        <?php 
                                                            $cleanText = strip_tags($news['content_desc'] ?? ''); 
                                                            echo htmlspecialchars(mb_strimwidth($cleanText, 0, 120, '...'));
                                                        ?>
                                                    </p>
                                                </div>
                                                <div class="card-footer bg-transparent border-0 p-3 pt-0">
                                                    <a href="index.php?p=multi-opac&lib=<?= htmlspecialchars($library_slug) ?>&action=news_detail&id=<?= $news['content_id'] ?>" class="btn btn-sm btn-link p-0 text-decoration-none fw-semibold">
                                                        Baca Selengkapnya <i class="fa-solid fa-arrow-right ms-1"></i>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                <?php endforeach; ?>

                                <?php if (!$hasNews): ?>
                                    <div class="col-12">
                                        <div class="card-modern p-4 text-center">
                                            <p class="text-muted mb-0"><i class="fa-solid fa-circle-info me-2"></i> Belum ada berita atau informasi terbaru untuk perpustakaan ini.</p>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <div class="card-modern p-4 text-center">
                                <p class="text-muted mb-0"><i class="fa-solid fa-circle-info me-2"></i> Belum ada berita atau informasi terbaru.</p>
                            </div>
                        <?php endif; ?>
                    </section>

                    <!-- SEKSI KOLEKSI TERBARU -->
                    <section class="mb-5">
                        <div class="section-header mb-3">
                            <h3 class="section-title h4"><i class="fa-solid fa-book-bookmark me-2"></i>Koleksi Terbaru</h3>
                            <small class="text-muted"><?= htmlspecialchars($library_name) ?></small>
                        </div>
                        
                        <?php if (!empty($biblios) && count($biblios) > 0): ?>
                            <div class="row g-4">
                                <?php foreach ($biblios as $b): ?>
                                    <div class="col-sm-6 col-md-4 col-lg-3">
                                        <div class="card-modern h-100 d-flex flex-column justify-content-between">
                                            <div>
                                                <!-- Cover Buku -->
                                                <div class="book-cover text-center p-2">
                                                    <?php 
                                                    $cover_dir = 'images/docs/'; 
                                                    $default_cover = 'plugins/multi_opac_path/assets/images/default_book.png';

                                                    if (!empty($b['image']) && file_exists($cover_dir . $b['image'])) {
                                                        $cover_url = $cover_dir . $b['image'];
                                                    } else {
                                                        $cover_url = $default_cover;
                                                    }
                                                    ?>
                                                    <img src="<?= $cover_url ?>" 
                                                         alt="<?= htmlspecialchars($b['title'] ?? 'Cover Buku') ?>" 
                                                         class="img-fluid rounded shadow-sm" 
                                                         style="height: 200px; object-fit: contain;"
                                                         onerror="this.onerror=null; this.src='<?= $default_cover ?>';">
                                                </div>

                                                <!-- Detail Buku -->
                                                <div class="p-3">
                                                    <h6 class="card-title text-truncate-2 fw-semibold mb-2 text-dark" title="<?= htmlspecialchars($b['title'] ?? 'Tanpa Judul') ?>">
                                                        <?= htmlspecialchars($b['title'] ?? 'Tanpa Judul') ?>
                                                    </h6>
                                                </div>
                                            </div>

                                            <!-- Tombol Aksi -->
                                            <div class="p-3 pt-0">
                                                <a href="<?= buildLibraryUrl('detail', $library_slug ?? $slug ?? null, ['id' => $b['biblio_id']]) ?>" class="btn btn-sm btn-outline-primary w-100 rounded-pill">
                                                    Lihat Detail
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="card-modern p-4 text-center">
                                <p class="text-muted mb-0"><i class="fa-solid fa-circle-info me-2"></i> Belum ada koleksi terbaru di perpustakaan ini.</p>
                            </div>
                        <?php endif; ?>
                    </section>

                <?php endif; ?> <!-- Tutup !$isSearching -->

            </div> <!-- Tutup col-lg-* -->
        </div> <!-- Tutup row utama -->

    <?php endif; ?> <!-- Tutup conditional p=member / custom / default -->

</main>
<!-- FOOTER -->
<footer class="landing-footer text-center">
    <div class="container">
        <p class="mb-0"><?= htmlspecialchars($themeData['footer_text']) ?></p>
    </div>
</footer>

<script src="<?= SWB ?>template/default/assets/js/jquery.min.js"></script>
<script src="<?= SWB ?>template/default/assets/js/bootstrap.bundle.min.js"></script>

</body>
</html>
<?php require_once __DIR__ . '/_modal_advanced.tpl'; ?>