<?php
/**
 * Navbar Plugin Multi OPAC - KHUSUS LIBRARY PAGE
 * Path: plugins/multi_opac_path/template/_navbar_library.inc.php
 * Version: 1.7.0 - Dengan dukungan hook member_menu
 */

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

// ============================================================
// 0. PASTIKAN SESSION SLIMS TERBACA
// ============================================================
if (session_status() == PHP_SESSION_NONE) {
    session_save_path(__DIR__ . '/../../../files/session');
    session_start();
}

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

// ============================================================
// 2. AMBIL DATA KONTEN & TEMA PERPUSTAKAAN UNIT
// ============================================================
$lib_slug     = $GLOBALS['nav_lib_slug'] ?? $_SESSION['multi_opac']['library_slug'] ?? ($_GET['lib'] ?? 'pusat');
$library_name = $GLOBALS['nav_library_name'] ?? 'Perpustakaan';
$theme        = $GLOBALS['nav_theme'] ?? $themeData ?? [];

// Ambil Warna & Logo dari Tema
$primaryColor = $theme['primary_color'] ?? '#0d6efd';
$logo         = $theme['logo'] ?? '';

// KONSISTENSI BRAND
$brandTitle   = !empty($theme['header_text']) ? $theme['header_text'] : $library_name;

// Halaman aktif saat ini
$current_p = $_GET['p'] ?? 'multi-opac';
$current_sec = $_GET['sec'] ?? '';

// Deteksi Status Pencarian & Keyword
$isSearching = $GLOBALS['is_searching'] ?? (!empty($_GET['search_query']) || !empty($_GET['keywords']));
$searchQuery = $_GET['search_query'] ?? $_GET['keywords'] ?? '';

// Cek Status Login Member
$isMemberLoggedIn = isset($_SESSION['mid']) && !empty($_SESSION['mid']);
$memberName       = $_SESSION['m_name'] ?? 'Anggota';
$memberId         = $_SESSION['mid'] ?? $_SESSION['m_id'] ?? '';

// ============================================================
// 3. KONFIGURASI
// ============================================================
$config = getMultiOpacConfig();

// Helper Fallback URL
if (!function_exists('buildLibraryUrl')) {
    function buildLibraryUrl($p, $slug, $sec = '') {
        $url = ($slug === 'pusat' || empty($slug)) ? 'index.php?p=' . urlencode($p) : 'index.php?p=' . urlencode($p) . '&lib=' . urlencode($slug);
        if (!empty($sec)) {
            $url .= '&sec=' . urlencode($sec);
        }
        return $url;
    }
}
?>

<!-- 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;
}

/* Custom Dropdown Style */
.navbar-custom-library .dropdown-menu {
    border: none;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    border-radius: 12px;
    padding: 0.5rem;
    margin-top: 8px;
}

.navbar-custom-library .dropdown-item {
    border-radius: 6px;
    padding: 0.5rem 1rem;
    font-weight: 500;
    transition: all 0.15s ease;
}

.navbar-custom-library .dropdown-item:hover {
    background-color: rgba(13, 110, 253, 0.08);
    color: #0d6efd;
}

/* Member dropdown */
.navbar-custom-library .member-dropdown .dropdown-toggle {
    background: rgba(255, 255, 255, 0.12);
    border: none;
    border-radius: 20px;
    padding: 5px 14px;
    color: white !important;
}

.navbar-custom-library .member-dropdown .dropdown-toggle .member-name {
    display: inline-block;
    max-width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    vertical-align: middle;
}

/* 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 .member-dropdown .dropdown-toggle .member-name {
        max-width: 60px;
    }
    .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', $lib_slug) ?>" 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($brandTitle) ?></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 KANAN (ms-auto)
        ============================================================ -->
        <div class="collapse navbar-collapse" id="navbarLibrary">
            <ul class="navbar-nav ms-auto mb-2 mb-lg-0 align-items-lg-center">
                
                <!-- 1. BERANDA UNIT -->
                <li class="nav-item <?= ($current_p == 'multi-opac' && !$isSearching) ? 'active' : '' ?>">
                    <a class="nav-link" href="<?= buildLibraryUrl('multi-opac', $lib_slug) ?>">Beranda</a>
                </li>

                <!-- 2. INFORMASI PERPUSTAKAAN UNIT -->
                <li class="nav-item <?= ($current_p == 'libinfo') ? 'active' : '' ?>">
                    <a class="nav-link" href="<?= buildLibraryUrl('libinfo', $lib_slug) ?>">Informasi</a>
                </li>

                <!-- 3. BANTUAN & LAYANAN UNIT -->
                <li class="nav-item <?= ($current_p == 'help') ? 'active' : '' ?>">
                    <a class="nav-link" href="<?= buildLibraryUrl('help', $lib_slug) ?>">Bantuan</a>
                </li>

                <!-- 4. PUSTAKAWAN / STAF UNIT -->
                <li class="nav-item <?= ($current_p == 'librarian') ? 'active' : '' ?>">
                    <a class="nav-link" href="<?= buildLibraryUrl('librarian', $lib_slug) ?>">Pustakawan</a>
                </li>

               <!-- 5. MEMBER AREA (Login / Logout) -->
<?php if ($isMemberLoggedIn): ?>
    <!-- SUDAH LOGIN -->
    <li class="nav-item dropdown member-dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="memberDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            <i class="fa-solid fa-user-circle me-1"></i>
            <span class="member-name"><?= htmlspecialchars($memberName) ?></span>
        </a>
        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="memberDropdown">
            <!-- Menu Default -->
            <li>
                <a class="dropdown-item" href="<?= buildLibraryUrl('member', $lib_slug) ?>">
                    <i class="fa-solid fa-id-card me-2 text-primary"></i> Profil Saya
                </a>
            </li>
            <li>
                <a class="dropdown-item" href="<?= buildLibraryUrl('member', $lib_slug, ['sec' => 'loan']) ?>">
                    <i class="fa-solid fa-book-open me-2 text-success"></i> Peminjaman Aktif
                </a>
            </li>
            <li>
                <a class="dropdown-item" href="<?= buildLibraryUrl('member', $lib_slug, ['sec' => 'bookmark']) ?>">
                    <i class="fa-solid fa-bookmark me-2 text-warning"></i> Bookmark
                </a>
            </li>
            <li>
                <a class="dropdown-item" href="<?= buildLibraryUrl('member', $lib_slug, ['sec' => 'title_basket']) ?>">
                    <i class="fa-solid fa-basket-shopping me-2 text-info"></i> Keranjang Judul
                </a>
            </li>
            <li>
                <a class="dropdown-item" href="<?= buildLibraryUrl('member', $lib_slug, ['sec' => 'history']) ?>">
                    <i class="fa-solid fa-clock-rotate-left me-2 text-secondary"></i> Riwayat Peminjaman
                </a>
            </li>

            <!-- ============================================================
            HOOK: TAMPILKAN MENU DARI PLUGIN LAIN (BEBAS PUSTAKA, DLL)
            ============================================================ -->
            <?php
            // Panggil hook member_menu dari semua plugin
            $extraMenus = [];
            try {
                \SLiMS\Plugins::getInstance()->execute('member_menu', ['menu' => &$extraMenus]);
            } catch (Exception $e) {
                // Hook tidak tersedia, abaikan
            }
            
            if (!empty($extraMenus) && is_array($extraMenus)):
                echo '<li><hr class="dropdown-divider"></li>';
                foreach ($extraMenus as $menuItem):
                    if (isset($menuItem['title']) && isset($menuItem['url'])):
                        $icon = $menuItem['icon'] ?? 'fa-file';
                        $title = $menuItem['title'];
                        $url = $menuItem['url'];
                        $class = $menuItem['class'] ?? '';
                    ?>
                        <li>
                            <a class="dropdown-item <?= htmlspecialchars($class) ?>" href="<?= htmlspecialchars($url) ?>">
                                <i class="fa-solid <?= htmlspecialchars($icon) ?> me-2 text-danger"></i> <?= htmlspecialchars($title) ?>
                            </a>
                        </li>
                    <?php
                    endif;
                endforeach;
            endif;
            ?>
            <!-- ============================================================ -->
            
            <li><hr class="dropdown-divider"></li>
            <li>
                <a class="dropdown-item text-danger" href="<?= buildLibraryUrl('member', $lib_slug, ['logout' => 1]) ?>">
                    <i class="fa-solid fa-right-from-bracket me-2"></i> Keluar (Logout)
                </a>
            </li>
        </ul>
    </li>
<?php else: ?>
    <!-- BELUM LOGIN -->
    <li class="nav-item <?= ($current_p == 'member-login') ? 'active' : '' ?>">
        <a class="nav-link" href="<?= buildLibraryUrl('member-login', $lib_slug) ?>">
            <i class="fa-solid fa-right-to-bracket me-1"></i> Login
        </a>
    </li>
<?php endif; ?>
                
                <!-- 6. GLOBAL SEARCH (Kembali ke Portal Utama) -->
                <li class="nav-item">
                    <a class="nav-link btn btn-outline-light px-3 py-1 ms-lg-1" href="index.php?p=multi-opac" title="Kembali ke pencarian seluruh perpustakaan">
                        <i class="fa-solid fa-globe me-1"></i> Global
                    </a>
                </li>

            </ul>
        </div>
    </div>
</nav>

<script>
// ============================================================
// MANUAL HANDLER UNTUK HAMBURGER & DROPDOWN MENU (FALLBACK)
// ============================================================
document.addEventListener('DOMContentLoaded', function() {
    // 1. Toggler Navbar 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');
            var isOpen = collapse.classList.contains('show');
            this.setAttribute('aria-expanded', isOpen);
        });
    }

    // 2. Dropdown Member Toggle Fallback
    var memberDropdownBtn = document.querySelector('#memberDropdown');
    if (memberDropdownBtn) {
        memberDropdownBtn.addEventListener('click', function(e) {
            e.preventDefault();
            var parent = this.parentElement;
            var menu = parent.querySelector('.dropdown-menu');
            if (menu) {
                menu.classList.toggle('show');
            }
        });

        document.addEventListener('click', function(e) {
            if (!memberDropdownBtn.contains(e.target)) {
                var menu = memberDropdownBtn.parentElement.querySelector('.dropdown-menu');
                if (menu && menu.classList.contains('show')) {
                    menu.classList.remove('show');
                }
            }
        });
    }
});
</script>