<?php
/**
 * Filter Sidebar untuk Hasil Pencarian
 * Path: plugins/multi_opac_path/template/_filter_sidebar.tpl
 * Version: 2.0.0
 * 
 * Diadopsi dari SLiMS _result-search.php dengan tambahan filter library
 * - Collapse/Expand
 * - Checkbox filter
 * - See More untuk GMD
 * - CSS terpisah di filtersidebar.css
 */

// ============================================================
// AMBIL NILAI FILTER DARI GET ATAU SESSION
// ============================================================
$filterYearFrom     = $_GET['year_from'] ?? $_SESSION['multi_opac']['filter']['year_from'] ?? '';
$filterYearTo       = $_GET['year_to'] ?? $_SESSION['multi_opac']['filter']['year_to'] ?? '';
$filterAvailability = $_GET['availability'] ?? $_SESSION['multi_opac']['filter']['availability'] ?? '';
$filterAttachment   = $_GET['attachment'] ?? $_SESSION['multi_opac']['filter']['attachment'] ?? '';
$filterCollType     = $_GET['colltype'] ?? $_SESSION['multi_opac']['filter']['colltype'] ?? '';
$filterGmd          = $_GET['gmd'] ?? $_SESSION['multi_opac']['filter']['gmd'] ?? '';
$filterLocation     = $_GET['location'] ?? $_SESSION['multi_opac']['filter']['location'] ?? '';
$filterLanguage     = $_GET['language'] ?? $_SESSION['multi_opac']['filter']['language'] ?? '';

$filterLib = $_GET['lib'] ?? $_SESSION['multi_opac']['library_slug'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? '';
$searchQuery = $_GET['search_query'] ?? $_GET['keywords'] ?? '';

$libraries = getAllLibraries();
$config    = getMultiOpacConfig();
$showBadge = $config['show_library_badge'] ?? 1;

$selectedLibId = null;
if ($filterLib) {
    $lib = getLibraryBySlug($filterLib);
    if ($lib) {
        $selectedLibId = $lib['library_id'];
    }
}

$filterOptions = getFilterOptions($selectedLibId);

$baseUrl = 'index.php?p=multi-opac';
if (!empty($searchQuery)) {
    $baseUrl .= '&search_query=' . urlencode($searchQuery);
}
if (!empty($filterLib)) {
    $baseUrl .= '&lib=' . urlencode($filterLib);
}

$currentLibraryName = $selectedLibId ? getLibraryNameById($selectedLibId) : 'Semua Perpustakaan';

// Daftar GMD (untuk See More)
$allGmds = [
    'Text', 'Art Original', 'Chart', 'Computer Software', 'Diorama', 'Filmstrip',
    'Flash Card', 'Game', 'Globe', 'Kit', 'Map', 'Microform', 'Manuscript',
    'Model', 'Motion Picture', 'Microscope Slide', 'Music', 'Picture', 'Realia',
    'Slide', 'Sound Recording', 'Technical Drawing', 'Transparency',
    'Video Recording', 'Equipment', 'Computer File', 'Cartographic Material',
    'CD-ROM', 'Multimedia', 'Electronic Resource', 'Digital Versatile Disc'
];

// Daftar Collection Type
$collTypes = ['Fiction', 'Reference', 'Textbook'];
?>
<!-- Link ke CSS Filter Sidebar -->
<link rel="stylesheet" href="<?= SWB ?>plugins/multi_opac_path/assets/css/filtersidebar.css">

<div class="filter-sidebar">
    <!-- HEADER -->
    <div class="filter-header">
        <h4><i class="fa-solid fa-sliders me-2 text-primary"></i> <?= __('Filter Koleksi') ?></h4>
        <span class="badge"><?= htmlspecialchars($currentLibraryName) ?></span>
    </div>
    
    <!-- FORM FILTER -->
    <form action="index.php" method="get" id="filterForm">
        <input type="hidden" name="p" value="multi-opac">
        <input type="hidden" name="search_query" value="<?= htmlspecialchars($searchQuery) ?>">
        <?php if (!empty($filterLib)): ?>
            <input type="hidden" name="lib" value="<?= htmlspecialchars($filterLib) ?>">
        <?php endif; ?>
        
        <ul class="list-group list-group-flush">
            
            <!-- ============================================================
            PUBLICATION YEAR
            ============================================================ -->
            <li class="list-group-item bg-transparent pl-0 border-top-0">
                <div class="d-flex justify-content-between align-items-center cursor-pointer" data-toggle="collapse" data-target="#collapse-year">
                    <strong class="text-sm"><?= __('Publication Year') ?></strong>
                    <i class="dropdown-toggle"></i>
                </div>
                <div class="collapse show text-sm" id="collapse-year">
                    <div class="mt-2">
                        <div class="d-flex gap-2 align-items-center">
                            <input type="number" name="year_from" class="form-control form-control-sm" placeholder="Dari" value="<?= htmlspecialchars($filterYearFrom) ?>" min="1900" max="<?= date('Y') ?>">
                            <span class="text-muted">-</span>
                            <input type="number" name="year_to" class="form-control form-control-sm" placeholder="Sampai" value="<?= htmlspecialchars($filterYearTo) ?>" min="1900" max="<?= date('Y') ?>">
                        </div>
                    </div>
                </div>
            </li>
            
            <!-- ============================================================
            AVAILABILITY
            ============================================================ -->
            <li class="list-group-item bg-transparent pl-0">
                <div class="d-flex justify-content-between align-items-center cursor-pointer" data-toggle="collapse" data-target="#collapse-availability">
                    <strong class="text-sm"><?= __('Availability') ?></strong>
                    <i class="dropdown-toggle"></i>
                </div>
                <div class="collapse show text-sm" id="collapse-availability">
                    <div class="mt-2">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="availability" id="avail-all" value="">
                            <label class="form-check-label" for="avail-all"><?= __('All') ?></label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="availability" id="avail-on-shelf" value="1" <?= $filterAvailability == '1' ? 'checked' : '' ?>>
                            <label class="form-check-label" for="avail-on-shelf"><?= __('On Shelf') ?></label>
                        </div>
                    </div>
                </div>
            </li>
            
            <!-- ============================================================
            ATTACHMENT
            ============================================================ -->
            <li class="list-group-item bg-transparent pl-0">
                <div class="d-flex justify-content-between align-items-center cursor-pointer" data-toggle="collapse" data-target="#collapse-attachment">
                    <strong class="text-sm"><?= __('Attachment') ?></strong>
                    <i class="dropdown-toggle"></i>
                </div>
                <div class="collapse show text-sm" id="collapse-attachment">
                    <div class="mt-2">
                        <?php $attachments = ['pdf' => 'PDF', 'audio' => 'Audio', 'video' => 'Video']; ?>
                        <?php foreach ($attachments as $val => $label): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="attachment[]" id="att-<?= $val ?>" value="<?= $val ?>" <?= ($filterAttachment == $val) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="att-<?= $val ?>"><?= $label ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </li>
            
            <!-- ============================================================
            COLLECTION TYPE
            ============================================================ -->
            <li class="list-group-item bg-transparent pl-0">
                <div class="d-flex justify-content-between align-items-center cursor-pointer" data-toggle="collapse" data-target="#collapse-colltype">
                    <strong class="text-sm"><?= __('Collection Type') ?></strong>
                    <i class="dropdown-toggle"></i>
                </div>
                <div class="collapse show text-sm" id="collapse-colltype">
                    <div class="mt-2">
                        <?php foreach ($collTypes as $ct): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="colltype[]" id="coll-<?= $ct ?>" value="<?= $ct ?>" <?= ($filterCollType == $ct) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="coll-<?= $ct ?>"><?= $ct ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </li>
            
            <!-- ============================================================
            GMD (FORMAT) - DENGAN SEE MORE
            ============================================================ -->
            <li class="list-group-item bg-transparent pl-0">
                <div class="d-flex justify-content-between align-items-center cursor-pointer" data-toggle="collapse" data-target="#collapse-gmd">
                    <strong class="text-sm"><?= __('General Material Designation') ?></strong>
                    <i class="dropdown-toggle"></i>
                </div>
                <div class="collapse show text-sm" id="collapse-gmd">
                    <div class="mt-2">
                        <?php 
                        $showCount = 5; // Tampilkan 5 dulu
                        $totalGmds = count($allGmds);
                        ?>
                        <?php foreach ($allGmds as $index => $gmd): ?>
                            <?php if ($index < $showCount): ?>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="gmd[]" id="gmd-<?= $index ?>" value="<?= htmlspecialchars($gmd) ?>" <?= ($filterGmd == $gmd) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="gmd-<?= $index ?>"><?= $gmd ?></label>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; ?>
                        
                        <!-- SEE MORE -->
                        <?php if ($totalGmds > $showCount): ?>
                            <div class="collapse" id="seeMore-gmd">
                                <?php for ($i = $showCount; $i < $totalGmds; $i++): ?>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="gmd[]" id="gmd-<?= $i ?>" value="<?= htmlspecialchars($allGmds[$i]) ?>">
                                        <label class="form-check-label" for="gmd-<?= $i ?>"><?= $allGmds[$i] ?></label>
                                    </div>
                                <?php endfor; ?>
                            </div>
                            <a class="d-block mt-2" data-toggle="collapse" href="#seeMore-gmd"><?= __('See More') ?></a>
                        <?php endif; ?>
                    </div>
                </div>
            </li>
            
            <!-- ============================================================
            LOCATION
            ============================================================ -->
            <li class="list-group-item bg-transparent pl-0">
                <div class="d-flex justify-content-between align-items-center cursor-pointer" data-toggle="collapse" data-target="#collapse-location">
                    <strong class="text-sm"><?= __('Location') ?></strong>
                    <i class="dropdown-toggle"></i>
                </div>
                <div class="collapse show text-sm" id="collapse-location">
                    <div class="mt-2">
                        <?php 
                        $locationsList = !empty($filterOptions['locations']) ? $filterOptions['locations'] : [];
                        if (empty($locationsList)) {
                            // Fallback
                            $locationsList = ['Sirkulasi FT', 'FEB R Sirkulasi', 'Lantai 2 UPA Perpustakaan Pusat'];
                        }
                        ?>
                        <?php foreach ($locationsList as $loc): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="location[]" id="loc-<?= md5($loc) ?>" value="<?= htmlspecialchars($loc) ?>" <?= ($filterLocation == $loc) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="loc-<?= md5($loc) ?>"><?= htmlspecialchars($loc) ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </li>
            
            <!-- ============================================================
            LANGUAGE
            ============================================================ -->
            <li class="list-group-item bg-transparent pl-0">
                <div class="d-flex justify-content-between align-items-center cursor-pointer" data-toggle="collapse" data-target="#collapse-language">
                    <strong class="text-sm"><?= __('Language') ?></strong>
                    <i class="dropdown-toggle"></i>
                </div>
                <div class="collapse show text-sm" id="collapse-language">
                    <div class="mt-2">
                        <?php 
                        $langs = ['en' => 'English', 'id' => 'Indonesia'];
                        ?>
                        <?php foreach ($langs as $code => $name): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="language[]" id="lang-<?= $code ?>" value="<?= $code ?>" <?= ($filterLanguage == $code) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="lang-<?= $code ?>"><?= $name ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </li>
            
        </ul>
        
        <!-- TOMBOL -->
        <hr class="divider">
        <button type="submit" class="btn-apply"><i class="fa-solid fa-filter me-1"></i> <?= __('Terapkan Filter') ?></button>
        <a href="<?= $baseUrl ?>&reset_filter=1" class="btn-reset mt-2"><i class="fa-solid fa-undo me-1"></i> <?= __('Reset Filter') ?></a>
        <div class="filter-count"><i class="fa-regular fa-clock me-1"></i> <?= __('Filter akan mempersempit hasil pencarian') ?></div>
    </form>
</div>

<!-- SCRIPT -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Toggle collapse menggunakan Bootstrap 5
    var collapseElements = document.querySelectorAll('.collapse');
    collapseElements.forEach(function(el) {
        // Inisialisasi Bootstrap Collapse
        new bootstrap.Collapse(el, {
            toggle: false
        });
    });
    
    // Click handler untuk toggle
    var toggles = document.querySelectorAll('[data-toggle="collapse"]');
    toggles.forEach(function(toggle) {
        toggle.addEventListener('click', function(e) {
            var targetId = this.getAttribute('data-target');
            var targetEl = document.querySelector(targetId);
            if (targetEl) {
                var bsCollapse = bootstrap.Collapse.getInstance(targetEl);
                if (bsCollapse) {
                    bsCollapse.toggle();
                } else {
                    new bootstrap.Collapse(targetEl, { toggle: true });
                }
            }
        });
    });
    
    // Validasi tahun
    var yearFrom = document.querySelector('input[name="year_from"]');
    var yearTo = document.querySelector('input[name="year_to"]');
    if (yearFrom && yearTo) {
        yearFrom.addEventListener('change', function() {
            if (this.value && yearTo.value && parseInt(this.value) > parseInt(yearTo.value)) {
                yearTo.value = this.value;
            }
        });
        yearTo.addEventListener('change', function() {
            if (this.value && yearFrom.value && parseInt(this.value) < parseInt(yearFrom.value)) {
                yearFrom.value = this.value;
            }
        });
    }
});
</script>