<?php
/**
 * Navbar Plugin Multi OPAC (Portal Utama Global)
 * Path: plugins/multi_opac_path/template/_navbar_plugin.inc.php
 * Version: 1.4.0 (Tanpa Login/Logout di navbar global)
 */

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

// ============================================================
// 1. REDIRECT / ROUTE KE NAVBAR LIBRARY JIKA LAGI DI PERPUSTAKAAN UNIT
// ============================================================
$url_lib = $_GET['lib'] ?? null;

// Jika ada library slug aktif di URL, muat navbar khusus library unit
if (!empty($url_lib)) {
    if (file_exists(__DIR__ . '/_navbar_library.inc.php')) {
        include __DIR__ . '/_navbar_library.inc.php';
        return; // Menghentikan eksekusi script agar navbar portal global tidak dirender
    }
}

// ============================================================
// 2. PASTIKAN HELPERS TERLOAD
// ============================================================
if (!function_exists('getAllLibraries')) {
    require_once dirname(__DIR__) . '/src/helpers.php';
}

// Helper Fallback URL
if (!function_exists('buildLibraryUrl')) {
    function buildLibraryUrl($p, $slug = null, $extraParams = []) {
        $url = 'index.php?p=' . urlencode($p);
        if (!empty($slug)) {
            $url .= '&lib=' . urlencode($slug);
        }
        if (!empty($extraParams) && is_array($extraParams)) {
            foreach ($extraParams as $k => $v) {
                $url .= '&' . urlencode($k) . '=' . urlencode($v);
            }
        }
        return $url;
    }
}

// ============================================================
// 3. DATA & TEMA KHUSUS PORTAL UTAMA (GLOBAL = SLUG NULL)
// ============================================================
$lib_slug     = null;
$library_name = $GLOBALS['nav_library_name'] ?? 'SIPERI Multi-OPAC';
$theme        = $GLOBALS['nav_theme'] ?? [];

$primaryColor = $theme['primary_color'] ?? '#0d6efd';
$logo         = $theme['logo'] ?? '';

// Ambil Seluruh Perpustakaan untuk Dropdown Switcher
$libraries = function_exists('getAllLibraries') ? getAllLibraries() : [];
$current_p = $_GET['p'] ?? 'multi-opac';
?>

<!-- Asset Font Awesome 6 Free -->
<link rel="stylesheet" href="plugins/multi_opac_path/assets/css/all.min.css">

<style>
/* ============================================================
NAVBAR STYLE - BRAND KIRI, MENU KANAN
============================================================ */
.navbar-custom-library {
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
    transition: all 0.3s ease;
    padding-top: 0.65rem;
    padding-bottom: 0.65rem;
}

.navbar-custom-library .navbar-brand {
    font-weight: 700;
    letter-spacing: -0.3px;
    font-size: 1.15rem;
    display: flex;
    align-items: center;
    gap: 10px;
    white-space: nowrap;
}

.navbar-custom-library .brand-logo {
    max-height: 38px;
    width: auto;
    object-fit: contain;
    background: rgba(255, 255, 255, 0.15);
    padding: 3px 6px;
    border-radius: 6px;
    flex-shrink: 0;
}

.navbar-custom-library .brand-text {
    display: inline-block;
    max-width: 220px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.navbar-custom-library .nav-link {
    font-weight: 500;
    padding: 0.5rem 0.85rem !important;
    border-radius: 8px;
    transition: all 0.2s ease-in-out;
    opacity: 0.9;
    color: rgba(255, 255, 255, 0.85) !important;
}

.navbar-custom-library .nav-link:hover,
.navbar-custom-library .nav-item.active .nav-link {
    opacity: 1;
    background-color: rgba(255, 255, 255, 0.2);
    font-weight: 600;
    color: #ffffff !important;
}

.navbar-custom-library .dropdown-menu {
    border: none;
    border-radius: 12px;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
    padding: 0.5rem;
    min-width: 260px;
    max-height: 380px;
    overflow-y: auto;
}

.navbar-custom-library .dropdown-item {
    border-radius: 8px;
    padding: 0.5rem 0.85rem;
    font-size: 0.9rem;
    font-weight: 500;
    transition: all 0.2s ease;
}

.navbar-custom-library .dropdown-item:hover {
    background-color: #f1f5f9;
    color: #0d6efd;
    transform: translateX(3px);
}

.navbar-custom-library .dropdown-item.active {
    background-color: #e7f1ff;
    color: #0d6efd;
    font-weight: 600;
}

.navbar-custom-library .dropdown-divider {
    margin: 0.4rem 0;
    border-color: #f1f5f9;
}

/* Library Selector Button Modern */
.lib-select-btn {
    background: rgba(255, 255, 255, 0.15);
    border: 1px solid rgba(255, 255, 255, 0.25);
    backdrop-filter: blur(4px);
}

/* Toggler mobile */
.navbar-custom-library .navbar-toggler {
    border: none;
    box-shadow: none;
    color: white;
}

.navbar-custom-library .navbar-toggler-icon {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255,255,255,0.9%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}

/* Responsive */
@media (max-width: 992px) {
    .navbar-custom-library .navbar-brand .brand-text {
        max-width: 150px;
    }
}

@media (max-width: 768px) {
    .navbar-custom-library .navbar-brand .brand-text {
        max-width: 100px;
        font-size: 0.95rem;
    }
    .navbar-custom-library .brand-logo {
        max-height: 30px;
    }
    .navbar-custom-library .nav-link {
        padding: 0.4rem 0.6rem !important;
        font-size: 0.9rem;
    }
}

@media (max-width: 576px) {
    .navbar-custom-library .navbar-brand .brand-text {
        max-width: 70px;
        font-size: 0.85rem;
    }
    .navbar-custom-library .brand-logo {
        max-height: 25px;
    }
}
</style>

<nav class="navbar navbar-expand-lg navbar-dark navbar-custom-library sticky-top" style="background-color: <?= htmlspecialchars($primaryColor) ?>;">
    <div class="container">
        
        <!-- ============================================================
        BRAND / LOGO - RATA KIRI
        ============================================================ -->
        <a class="navbar-brand" href="<?= buildLibraryUrl('multi-opac') ?>" title="<?= htmlspecialchars($library_name) ?>">
            <?php if (!empty($logo)): ?>
                <img src="<?= htmlspecialchars($logo) ?>" alt="Logo" class="brand-logo">
            <?php else: ?>
                <i class="fa-solid fa-book-open fs-4"></i>
            <?php endif; ?>
            <span class="brand-text"><?= htmlspecialchars($library_name) ?></span>
        </a>
        
        <!-- ============================================================
        TOGGLER MOBILE
        ============================================================ -->
        <button class="navbar-toggler" type="button" 
                data-bs-toggle="collapse" 
                data-bs-target="#navbarLibrary" 
                aria-controls="navbarLibrary" 
                aria-expanded="false" 
                aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        
        <!-- ============================================================
        MENU NAVIGASI - RATA KIRI (me-auto) & SWITCHER RATA KANAN (ms-auto)
        ============================================================ -->
        <div class="collapse navbar-collapse" id="navbarLibrary">
            
            <!-- MENU UTAMA - RATA KIRI -->
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li class="nav-item <?= ($current_p == 'multi-opac') ? 'active' : '' ?>">
                    <a class="nav-link" href="<?= buildLibraryUrl('multi-opac') ?>">Beranda</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="<?= buildLibraryUrl('multi-opac') ?>">Informasi</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="<?= buildLibraryUrl('multi-opac') ?>">Bantuan</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="<?= buildLibraryUrl('multi-opac') ?>">Pustakawan</a>
                </li>
            </ul>
            
            <!-- MENU KANAN - SWITCHER PERPUSTAKAAN -->
            <ul class="navbar-nav ms-auto mb-2 mb-lg-0 align-items-lg-center">
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle lib-select-btn px-3 rounded-pill text-white d-flex align-items-center" 
                       href="#" id="libraryPageDropdown" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <i class="fa-solid fa-building-columns me-2"></i>
                        <span class="text-truncate" style="max-width: 180px;">Pilih Perpustakaan</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end mt-2 animate slideIn" aria-labelledby="libraryPageDropdown">
                        <li>
                            <a class="dropdown-item fw-semibold text-primary active" href="<?= buildLibraryUrl('multi-opac') ?>">
                                <i class="fa-solid fa-globe me-2"></i> Semua Perpustakaan
                            </a>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <?php if (count($libraries) > 0): ?>
                            <?php foreach ($libraries as $lib): ?>
                                <?php $slug = $lib['url_slug'] ?? $lib['library_id']; ?>
                                <li>
                                    <a class="dropdown-item d-flex align-items-center justify-content-between" 
                                       href="<?= buildLibraryUrl('multi-opac', $slug) ?>"
                                       title="<?= htmlspecialchars($lib['library_name']) ?>">
                                        <span class="text-truncate me-2" style="max-width: 200px;">
                                            <i class="fa-solid fa-building text-muted me-2"></i>
                                            <?= htmlspecialchars($lib['library_name']) ?>
                                        </span>
                                    </a>
                                </li>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <li><span class="dropdown-item text-muted">Tidak ada perpustakaan</span></li>
                        <?php endif; ?>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<script>
// ============================================================
// MANUAL DROPDOWN & HAMBURGER FALLBACK HANDLER
// ============================================================
document.addEventListener('DOMContentLoaded', function() {
    // 1. Dropdown toggles
    var dropdownToggles = document.querySelectorAll('.navbar-custom-library .dropdown-toggle[data-bs-toggle="dropdown"]');
    dropdownToggles.forEach(function(toggle) {
        toggle.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var menu = this.nextElementSibling;
            if (menu && menu.classList.contains('dropdown-menu')) {
                var isOpen = menu.classList.contains('show');
                closeAllDropdowns();
                if (!isOpen) {
                    menu.classList.add('show');
                    this.setAttribute('aria-expanded', 'true');
                }
            }
        });
    });

    document.addEventListener('click', function(e) {
        closeAllDropdowns();
    });

    function closeAllDropdowns() {
        document.querySelectorAll('.navbar-custom-library .dropdown-menu.show').forEach(function(menu) {
            menu.classList.remove('show');
            var toggle = menu.parentElement.querySelector('.dropdown-toggle');
            if (toggle) toggle.setAttribute('aria-expanded', 'false');
        });
    }

    // 2. Toggler mobile
    var toggler = document.querySelector('.navbar-custom-library .navbar-toggler');
    var collapse = document.querySelector('#navbarLibrary');
    if (toggler && collapse) {
        toggler.addEventListener('click', function(e) {
            e.preventDefault();
            collapse.classList.toggle('show');
            this.setAttribute('aria-expanded', collapse.classList.contains('show'));
        });
    }
});
</script>