<?php
/**
 * Template Landing Page Multi OPAC
 * Path: plugins/multi_opac_path/template/landing_page.tpl
 * Version: 1.3.0 (Slug-Agnostic / No Pusat Fallback / Unified Multi-Tenant)
 * 
 * KONSEP: Landing Page menampilkan SEMUA koleksi dari semua perpustakaan
 */

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

// ============================================================
// 1. AMBIL PARAMETER UNIT & CONTEXT (SLUG-AGNOSTIC)
// ============================================================
$selectedLibSlug = $_GET['lib'] ?? null;
$selectedLibId   = null;

$libraries = getAllLibraries();

if ($selectedLibSlug) {
    foreach ($libraries as $lib) {
        if (($lib['url_slug'] ?? '') === $selectedLibSlug || (string)$lib['library_id'] === (string)$selectedLibSlug) {
            $selectedLibId   = $lib['library_id'];
            $selectedLibSlug = $lib['url_slug'];
            break;
        }
    }
}

// Catatan: Jika $selectedLibSlug NULL, konteks MURNI Portal Induk Utama (Lintas Unit)

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

// Deteksi status pencarian
$isSearching = !empty($searchQuery) || !empty($selectedAuthor) || !empty($selectedTopic) || !empty($selectedGmd) || isset($_GET['callnumber']);

// ============================================================
// 3. TEMA SYSTEM (GLOBAL VS UNIT TENANT)
// ============================================================
$themeFromDb = $selectedLibId ? getTheme($selectedLibId) : null;

if ($themeFromDb) {
    $themeData = [
        'primary_color'   => $themeFromDb['primary_color'] ?? '#0d6efd',
        'secondary_color' => $themeFromDb['secondary_color'] ?? '#212529',
        'header_text'     => $themeFromDb['header_text'] ?? '📚 OPAC ' . getLibraryNameById($selectedLibId),
        'footer_text'     => $themeFromDb['footer_text'] ?? '© ' . date('Y') . ' SLiMS Multi OPAC',
        'logo'            => $themeFromDb['logo'] ?? ''
    ];
} else {
    // Default Portal Induk Theme
    $themeData = [
        'primary_color'   => '#0d6efd',
        'secondary_color' => '#212529',
        'header_text'     => '📚 Portal Multi Perpustakaan',
        'footer_text'     => '© ' . date('Y') . ' SLiMS Multi OPAC Portal',
        'logo'            => ''
    ];
}

// ============================================================
// 4. DATA KOLEKSI & KONTEN
// ============================================================
$biblios    = getBibliosByLibrary($selectedLibId, 12);
$popular    = getPopularCollections($selectedLibId, 6);
$topReaders = getTopReaders($selectedLibId, 5);

// Definisi Kategori/Topik Default
$topics = [
    ['id' => '000', 'name' => 'Karya Umum', 'icon' => '0-chemical.png'],
    ['id' => '100', 'name' => 'Filsafat', 'icon' => '1-memory.png'],
    ['id' => '200', 'name' => 'Agama', 'icon' => '2-mosque.png'],
    ['id' => '300', 'name' => 'Ilmu Sosial', 'icon' => '3-diploma.png'],
    ['id' => '400', 'name' => 'Bahasa', 'icon' => '4-translation.png'],
    ['id' => '500', 'name' => 'MIPA', 'icon' => '5-math.png'],
    ['id' => '600', 'name' => 'Teknologi', 'icon' => '6-blackboard.png'],
    ['id' => '700', 'name' => 'Seni & Olahraga', 'icon' => '7-quill.png'],
    ['id' => '800', 'name' => 'Sastra', 'icon' => '8-books.png'],
    ['id' => '900', 'name' => 'Sejarah & Geografi', 'icon' => '9-return-to-the-past.png'],
];

// ============================================================
// 5. PENCARIAN & FACETS GENERATOR
// ============================================================
$searchResults = [];
if (!empty($searchQuery)) {
    $searchResults = searchBibliosByLibrary($searchQuery, $selectedLibId, 24);
} elseif (isset($GLOBALS['search_results']) && !empty($GLOBALS['search_results'])) {
    $searchResults = $GLOBALS['search_results'];
}

$facets = ['authors' => [], 'topics' => [], 'gmd' => []];
if (!empty($searchResults)) {
    $authCounts  = [];
    $topicCounts = [];
    $gmdCounts   = [];

    foreach ($searchResults as $res) {
        if (!empty($res['author'])) {
            $authCounts[$res['author']] = ($authCounts[$res['author']] ?? 0) + 1;
        }
        if (!empty($res['topic'])) {
            $topicCounts[$res['topic']] = ($topicCounts[$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];
    }
}

// Konfigurasi Tambahan
$config    = getMultiOpacConfig();
$showBadge = $config['show_library_badge'] ?? 1;

?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($themeData['header_text']) ?></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 Plugin -->
    <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 PLUGIN
============================================================ -->
<?php
$GLOBALS['nav_lib_slug']     = $selectedLibSlug;
$GLOBALS['nav_library_name'] = $selectedLibId ? getLibraryNameById($selectedLibId) : 'Multi-OPAC Portal';
$GLOBALS['nav_theme']        = $themeData;

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">
                        <span class="text-warning">SIPERI</span> Multi Perpustakaan
                    </h1>
                </div>
                <p class="lead text-white-50">
                    <?= $selectedLibId 
                        ? 'Koleksi Perpustakaan: ' . htmlspecialchars(getLibraryNameById($selectedLibId))
                        : 'Jelajahi dan temukan koleksi buku dari seluruh perpustakaan dalam satu portal.' ?>
                </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">
                    <?php if ($selectedLibSlug): ?>
                        <input type="hidden" name="lib" value="<?= htmlspecialchars($selectedLibSlug) ?>">
                    <?php endif; ?>
                    <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
============================================================ -->
<main class="container my-4">
    <div class="row <?= $isSearching ? '' : 'justify-content-center' ?>">
        
        <?php if ($isSearching): ?>
        <!-- SIDEBAR FILTER / FACETS -->
        <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<?= !empty($selectedLibSlug) ? '&lib='.htmlspecialchars($selectedLibSlug) : '' ?>&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>

                <!-- 1. 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<?= !empty($selectedLibSlug) ? '&lib='.htmlspecialchars($selectedLibSlug) : '' ?>&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; ?>

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

                <!-- 3. 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<?= !empty($selectedLibSlug) ? '&lib='.htmlspecialchars($selectedLibSlug) : '' ?>&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; ?>

<!-- AREA UTAMA CONTENT -->
<div class="<?= $isSearching ? 'col-lg-9' : 'col-lg-12' ?>">
    
    <!-- ============================================================
    TOPIC ICONS GRID - HANYA TAMPIL SAAT TIDAK MENCARI
    ============================================================ -->
    <?php if (!$isSearching): ?>
        <section class="mb-4">
            <ul class="topic-grid">
                <?php foreach ($topics as $topic): ?>
                    <li>
                        <a href="<?= buildLibraryUrl('multi-opac', $selectedLibSlug, ['callnumber' => $topic['id'], 'search' => 'search']) ?>">
                            <img src="<?= SWB ?>template/default/assets/images/<?= $topic['icon'] ?>" alt="<?= htmlspecialchars($topic['name']) ?>" loading="lazy" onerror="this.src='<?= SWB ?>plugins/multi_opac_path/assets/images/default_book.png'">
                            <span><?= htmlspecialchars($topic['name']) ?></span>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </section>
    <?php endif; ?>

            <!-- CONDITION A: MODE 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) ?>"
                            <?php if ($selectedLibSlug && $selectedLibId): ?>
                                <span class="badge bg-info text-dark fs-6 font-normal ms-2">
                                    <?= htmlspecialchars(getLibraryNameById($selectedLibId)) ?>
                                </span>
                            <?php endif; ?>
                        </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 col-lg-3">
                                    <div class="card-modern h-100 d-flex flex-column justify-content-between border rounded shadow-sm p-2">
                                        <div>
                                            <div class="book-cover text-center mb-2">
                                                <?php 
                                                $cover_dir = 'images/docs/'; 
                                                $default_cover = 'plugins/multi_opac_path/assets/images/default_book.png';
                                                $cover_url = (!empty($b['image']) && file_exists($cover_dir . $b['image'])) 
                                                    ? $cover_dir . $b['image'] 
                                                    : $default_cover;
                                                ?>
                                                <img src="<?= $cover_url ?>" alt="<?= htmlspecialchars($b['title']) ?>" class="img-fluid rounded" style="max-height: 180px; object-fit: cover;">
                                            </div>
                                            <div class="p-2">
                                                <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 ($showBadge && !empty($b['library_id'])): ?>
                                                    <span class="badge bg-secondary mb-2"><?= htmlspecialchars(getLibraryNameById($b['library_id'])) ?></span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="p-2 pt-0">
                                            <a href="<?= buildLibraryUrl('detail', $selectedLibSlug, ['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> Tidak ditemukan koleksi yang cocok dengan pencarian Anda.</p>
                        </div>
                    <?php endif; ?>
                </section>

            <!-- CONDITION B: MODE DEFAULT LANDING PAGE (PORTAL/UNIT HOME) -->
            <?php else: ?>

                <!-- DIREKTORI UNIT PERPUSTAKAAN (Tampil Hanya jika Akses Portal Induk) -->
                <?php if (!$selectedLibId && !empty($libraries)): ?>
                <section class="mb-5">
                    <div class="section-header mb-3">
                        <h3 class="section-title h4 mb-0"><i class="fa-solid fa-building-columns text-primary me-2"></i>Jelajahi Perpustakaan Unit</h3>
                        <p class="text-muted small mb-0">Pilih unit perpustakaan untuk masuk ke katalog khusus unit terkait.</p>
                    </div>
                    <div class="row g-3">
                        <?php foreach ($libraries as $lib): ?>
                            <?php $slug = $lib['url_slug'] ?? $lib['library_id']; ?>
                            <div class="col-md-4 col-sm-6">
                                <div class="card border-0 shadow-sm h-100 p-3 rounded-3 d-flex flex-row align-items-center gap-3 bg-white hover-shadow transition">
                                    <div class="lib-icon bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 48px; height: 48px; flex-shrink:0;">
                                        <i class="fa-solid fa-book-bookmark fs-5"></i>
                                    </div>
                                    <div>
                                        <h6 class="fw-bold mb-1 text-dark"><?= htmlspecialchars($lib['library_name']) ?></h6>
                                        <a href="index.php?p=multi-opac&lib=<?= urlencode($slug) ?>" class="btn btn-link btn-sm p-0 text-decoration-none fw-semibold">
                                            Kunjungi OPAC <i class="fa-solid fa-arrow-right ms-1"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>
                <?php endif; ?>

                <!-- KOLEKSI TERBARU -->
                <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-clock-rotate-left text-primary me-2"></i>Koleksi Terbaru</h3>
                    </div>
                    <?php if (!empty($biblios)): ?>
                        <div class="row g-4">
                            <?php foreach ($biblios as $b): ?>
                                <div class="col-6 col-md-3 col-lg-2">
                                    <div class="card-modern h-100 d-flex flex-column justify-content-between border rounded p-2 text-center">
                                        <div>
                                            <?php 
                                            $cover_dir = 'images/docs/'; 
                                            $default_cover = 'plugins/multi_opac_path/assets/images/default_book.png';
                                            $cover_url = (!empty($b['image']) && file_exists($cover_dir . $b['image'])) 
                                                ? $cover_dir . $b['image'] 
                                                : $default_cover;
                                            ?>
                                            <img src="<?= $cover_url ?>" alt="<?= htmlspecialchars($b['title']) ?>" class="img-fluid rounded mb-2" style="max-height: 150px; object-fit: cover;">
                                            <h6 class="card-title text-truncate-2 small fw-bold text-dark mb-1" title="<?= htmlspecialchars($b['title']) ?>">
                                                <?= htmlspecialchars($b['title']) ?>
                                            </h6>
                                            <?php if ($showBadge && !empty($b['library_id'])): ?>
                                                <span class="badge bg-light text-dark border mb-2" style="font-size: 0.65rem;"><?= htmlspecialchars(getLibraryNameById($b['library_id'])) ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <a href="<?= buildLibraryUrl('detail', $selectedLibSlug, ['id' => $b['biblio_id']]) ?>" class="btn btn-xs btn-outline-primary w-100 rounded-pill mt-2 py-1" style="font-size: 0.75rem;">
                                            Detail
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="text-muted">Belum ada data koleksi terbaru.</p>
                    <?php endif; ?>
                </section>

                <!-- KOLEKSI POPULER -->
                <?php if (!empty($popular)): ?>
                <section class="mb-5">
                    <div class="section-header mb-3">
                        <h3 class="section-title h4 mb-0"><i class="fa-solid fa-fire text-danger me-2"></i>Koleksi Populer</h3>
                    </div>
                    <div class="row g-4">
                        <?php foreach ($popular as $b): ?>
                            <div class="col-6 col-md-3 col-lg-2">
                                <div class="card-modern h-100 d-flex flex-column justify-content-between border rounded p-2 text-center">
                                    <div>
                                        <?php 
                                        $cover_dir = 'images/docs/'; 
                                        $default_cover = 'plugins/multi_opac_path/assets/images/default_book.png';
                                        $cover_url = (!empty($b['image']) && file_exists($cover_dir . $b['image'])) 
                                            ? $cover_dir . $b['image'] 
                                            : $default_cover;
                                        ?>
                                        <img src="<?= $cover_url ?>" alt="<?= htmlspecialchars($b['title']) ?>" class="img-fluid rounded mb-2" style="max-height: 150px; object-fit: cover;">
                                        <h6 class="card-title text-truncate-2 small fw-bold text-dark mb-1" title="<?= htmlspecialchars($b['title']) ?>">
                                            <?= htmlspecialchars($b['title']) ?>
                                        </h6>
                                    </div>
                                    <a href="<?= buildLibraryUrl('detail', $selectedLibSlug, ['id' => $b['biblio_id']]) ?>" class="btn btn-xs btn-outline-danger w-100 rounded-pill mt-2 py-1" style="font-size: 0.75rem;">
                                        Detail
                                    </a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>
                <?php endif; ?>

            <?php endif; ?>

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

<!-- FOOTER -->
<footer class="landing-footer text-center py-4 bg-dark text-white-50 mt-5">
    <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'; ?>