<?php
/**
 * Advanced Search Modal untuk Multi OPAC
 * Path: plugins/multi_opac_path/template/_modal_advanced.tpl
 * Version: 1.1.0
 * 
 * KONSEP: Advanced Search dengan filter perpustakaan (AJAX)
 * - CSRF Token untuk keamanan
 * - Filter lokasi berdasarkan perpustakaan (AJAX)
 * - Tahun range (2 input)
 * - Validasi minimal 1 kriteria
 * - CSS terpisah di modaladv.css
 */

// ============================================================
// AMBIL DAFTAR PERPUSTAKAAN
// ============================================================
$libraries = getAllLibraries();

// ============================================================
// AMBIL PARAMETER LIB (PAKAI SESSION ARRAY)
// ============================================================
$selectedLibSlug = $_GET['lib'] ?? 
                   $_SESSION['multi_opac']['library_slug'] ?? 
                   $_SESSION['multi_opac']['last_library_slug'] ?? 
                   null;

// Ambil data library jika ada slug
$selectedLibId = null;
if ($selectedLibSlug) {
    foreach ($libraries as $lib) {
        if (($lib['url_slug'] ?? '') === $selectedLibSlug || (string)$lib['library_id'] === (string)$selectedLibSlug) {
            $selectedLibId = $lib['library_id'];
            break;
        }
    }
}

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

// ============================================================
// AMBIL TEMA UNTUK STYLING (CSS VARS)
// ============================================================
$themeId = $selectedLibId ?: 1;
$themeFromDb = getTheme($themeId);

if ($themeFromDb) {
    $primaryColor = $themeFromDb['primary_color'] ?? '#0d6efd';
    $secondaryColor = $themeFromDb['secondary_color'] ?? '#212529';
} else {
    $primaryColor = '#0d6efd';
    $secondaryColor = '#212529';
}
?>

<!-- ============================================================
STYLE: CSS VARIABLES (hanya variabel, sisanya di file CSS)
============================================================ -->
<style>
    :root {
        --primary-color: <?= $primaryColor ?>;
        --secondary-color: <?= $secondaryColor ?>;
        --primary-dark: color-mix(in srgb, var(--primary-color) 85%, black);
    }
</style>

<!-- Link ke CSS Modal (terpisah) -->
<link rel="stylesheet" href="<?= SWB ?>plugins/multi_opac_path/assets/css/modaladv.css">

<!-- ============================================================
MODAL ADVANCED SEARCH
============================================================ -->
<div class="modal fade adv-modal" id="adv-modal-plugin" tabindex="-1" role="dialog" aria-labelledby="advModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <form class="modal-content" action="index.php" method="get" id="advSearchForm">
            <!-- HEADER -->
            <div class="modal-header">
                <h5 class="modal-title" id="advModalLabel">
                    <i class="fa-solid fa-sliders me-2"></i> <?= __('Advanced Search') ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            
            <!-- BODY -->
            <div class="modal-body">
                
                <!-- ============================================================
                SECTION 1: PERPUSTAKAAN & TAHUN
                ============================================================ -->
                <div class="section-label">
                    <i class="fa-solid fa-filter me-1"></i> <?= __('Filter Pencarian') ?>
                </div>
                
                <div class="row">
                    <!-- Dropdown Perpustakaan -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-library">
                                <i class="fa-solid fa-building-columns me-1"></i> <?= __('Perpustakaan') ?>
                            </label>
                            <select id="adv-library" name="lib" class="form-select" data-selected="<?= htmlspecialchars($selectedLibSlug) ?>">
                                <option value=""><?= __('Semua Perpustakaan') ?></option>
                                <?php foreach ($libraries as $lib): ?>
                                    <?php 
                                    // SKIP library_id = 1 (Pusat)
                                    if ($lib['library_id'] == 1) continue; 
                                    $slug = $lib['url_slug'] ?? $lib['library_id']; 
                                    ?>
                                    <option value="<?= htmlspecialchars($slug) ?>" 
                                        <?= ($selectedLibSlug == $slug) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($lib['library_name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <!-- Tahun Terbit (Range) -->
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-publishyear">
                                <i class="fa-regular fa-calendar me-1"></i> <?= __('Tahun Terbit') ?>
                            </label>
                            <div class="d-flex gap-2 align-items-center">
                                <input type="number" name="year_from" id="adv-year-from" class="form-control" 
                                       placeholder="<?= __('Dari') ?>" min="1900" max="<?= date('Y') ?>">
                                <span class="text-muted">-</span>
                                <input type="number" name="year_to" id="adv-year-to" class="form-control" 
                                       placeholder="<?= __('Sampai') ?>" min="1900" max="<?= date('Y') ?>">
                            </div>
                        </div>
                    </div>
                </div>
                
                <hr class="section-divider">
                
                <!-- ============================================================
                SECTION 2: FIELD SEARCH
                ============================================================ -->
                <div class="section-label">
                    <i class="fa-solid fa-search me-1"></i> <?= __('Kriteria Pencarian') ?>
                    <span class="text-danger">*</span>
                </div>
                
                <!-- Row 1: Title & Author -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-titles">
                                <i class="fa-solid fa-book me-1"></i> <?= __('Judul') ?>
                            </label>
                            <input type="text" name="title" class="form-control" id="adv-titles"
                                   placeholder="<?= __('Masukkan judul buku') ?>">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-author">
                                <i class="fa-regular fa-user me-1"></i> <?= __('Pengarang') ?>
                            </label>
                            <input type="text" name="author" class="form-control" id="adv-author"
                                   placeholder="<?= __('Masukkan nama pengarang') ?>">
                        </div>
                    </div>
                </div>
                
                <!-- Row 2: Subject & ISBN -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-subject">
                                <i class="fa-solid fa-tags me-1"></i> <?= __('Subjek') ?>
                            </label>
                            <input type="text" name="subject" class="form-control" id="adv-subject"
                                   placeholder="<?= __('Masukkan subjek') ?>">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-isbn">
                                <i class="fa-solid fa-barcode me-1"></i> <?= __('ISBN/ISSN') ?>
                            </label>
                            <input type="text" name="isbn" class="form-control" id="adv-isbn"
                                   placeholder="<?= __('Masukkan ISBN/ISSN') ?>">
                        </div>
                    </div>
                </div>
                
                <!-- Row 3: Location & GMD -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-location">
                                <i class="fa-solid fa-location-dot me-1"></i> <?= __('Lokasi') ?>
                            </label>
                            <select id="adv-location" name="location" class="form-select">
                                <option value=""><?= __('Semua Lokasi') ?></option>
                                <!-- Locations akan diisi via AJAX -->
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-gmd">
                                <i class="fa-solid fa-file me-1"></i> <?= __('Format (GMD)') ?>
                            </label>
                            <select id="adv-gmd" name="gmd" class="form-select">
                                <option value=""><?= __('Semua Format') ?></option>
                                <?= commonList('gmd') ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Row 4: Collection Type -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="adv-coll-type">
                                <i class="fa-solid fa-layer-group me-1"></i> <?= __('Tipe Koleksi') ?>
                            </label>
                            <select name="colltype" class="form-select" id="adv-coll-type">
                                <option value=""><?= __('Semua Tipe') ?></option>
                                <?= commonList('collection') ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <div class="text-muted small mt-2">
                                <i class="fa-regular fa-circle-info me-1"></i> 
                                <?= __('Gunakan minimal satu kriteria untuk mencari') ?>
                                <span class="text-danger">*</span>
                            </div>
                        </div>
                    </div>
                </div>
                
            </div>
            
            <!-- FOOTER -->
            <div class="modal-footer">
                <?php if (function_exists('renderCSRFToken')): ?>
                    <?= renderCSRFToken() ?>
                <?php endif; ?>
                <input type="hidden" name="p" value="multi-opac">
                <input type="hidden" name="search" value="search">
                <button type="submit" class="btn btn-primary" id="advSearchSubmit">
                    <i class="fa-solid fa-magnifying-glass me-1"></i> <?= __('Cari Koleksi') ?>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- ============================================================
SCRIPT
============================================================ -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    'use strict';
    
    // ============================================================
    // ELEMENTS
    // ============================================================
    var modalElement = document.getElementById('adv-modal-plugin');
    var form = document.getElementById('advSearchForm');
    var librarySelect = document.getElementById('adv-library');
    var locationSelect = document.getElementById('adv-location');
    var submitBtn = document.getElementById('advSearchSubmit');
    
    // ============================================================
    // INIT: LOAD LOCATIONS (jika ada library yang sudah dipilih)
    // ============================================================
    function loadLocations(librarySlug) {
        if (!librarySlug) {
            locationSelect.innerHTML = '<option value=""><?= __('Semua Lokasi') ?></option>';
            return;
        }
        
        // Show loading
        locationSelect.innerHTML = '<option value=""><?= __('Memuat lokasi...') ?></option>';
        locationSelect.disabled = true;
        
        // Fetch locations via AJAX (SLiMS 9.8 style)
        var url = '<?= SWB ?>plugins/multi_opac_path/pages/get_locations.php?library_id=' + encodeURIComponent(librarySlug) + '&_=' + Date.now();
        
        fetch(url, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            locationSelect.innerHTML = '<option value=""><?= __('Semua Lokasi') ?></option>';
            if (data.status === 'success' && data.data) {
                data.data.forEach(function(loc) {
                    var option = document.createElement('option');
                    option.value = loc.location_id || loc.location_name;
                    option.textContent = loc.location_name;
                    locationSelect.appendChild(option);
                });
            }
            locationSelect.disabled = false;
        })
        .catch(function() {
            locationSelect.innerHTML = '<option value=""><?= __('Semua Lokasi') ?></option>';
            locationSelect.disabled = false;
        });
    }
    
    // ============================================================
    // EVENT: LIBRARY CHANGE → LOAD LOCATIONS
    // ============================================================
    if (librarySelect) {
        librarySelect.addEventListener('change', function() {
            var selectedValue = this.value;
            if (selectedValue) {
                loadLocations(selectedValue);
            } else {
                locationSelect.innerHTML = '<option value=""><?= __('Semua Lokasi') ?></option>';
            }
        });
        
        // Trigger initial load jika ada selected
        var initialLib = librarySelect.getAttribute('data-selected') || librarySelect.value;
        if (initialLib) {
            loadLocations(initialLib);
        }
    }
    
    // ============================================================
    // MODAL: INISIALISASI & FOCUS
    // ============================================================
    if (modalElement) {
        // Trigger modal
        var advBtn = document.querySelector('[data-bs-target="#adv-modal-plugin"]');
        if (advBtn) {
            advBtn.addEventListener('click', function(e) {
                e.preventDefault();
                var modal = new bootstrap.Modal(modalElement);
                modal.show();
            });
        }
        
        // Auto focus ke field pertama
        modalElement.addEventListener('shown.bs.modal', function() {
            var firstInput = this.querySelector('input:not([type="hidden"]):not([type="submit"]), select');
            if (firstInput && !firstInput.disabled) {
                setTimeout(function() {
                    firstInput.focus();
                }, 300);
            }
        });
    }
    
    // ============================================================
    // VALIDASI: MINIMAL 1 KRITERIA
    // ============================================================
    if (form) {
        form.addEventListener('submit', function(e) {
            var fields = ['title', 'author', 'subject', 'isbn'];
            var filled = false;
            
            fields.forEach(function(field) {
                var input = form.querySelector('[name="' + field + '"]');
                if (input && input.value.trim() !== '') {
                    filled = true;
                }
            });
            
            // Cek tahun range
            var yearFrom = document.getElementById('adv-year-from');
            var yearTo = document.getElementById('adv-year-to');
            if (yearFrom && yearFrom.value.trim() !== '') {
                filled = true;
            }
            if (yearTo && yearTo.value.trim() !== '') {
                filled = true;
            }
            
            if (!filled) {
                e.preventDefault();
                alert('<?= __('Mohon isi minimal satu kriteria pencarian (Judul, Pengarang, Subjek, ISBN, atau Tahun)') ?>');
            }
        });
    }
    
    // ============================================================
    // ENTER KEY UNTUK SUBMIT
    // ============================================================
    if (form) {
        form.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                var target = e.target;
                if (target.tagName !== 'TEXTAREA' && target.type !== 'submit') {
                    e.preventDefault();
                    form.submit();
                }
            }
        });
    }
});
</script>