<?php
/**
 * Handler untuk OPAC Multi
 * Path: plugins/multi_opac_path/pages/opac_handler.php
 * Version: 1.3.3 (Fixed Member Register Date Session for PHP 8.3 & Complete Tenant Context)
 */

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

// ============================================================
// LOAD HELPERS
// ============================================================
if (!function_exists('getAllLibraries')) {
    require_once __DIR__ . '/../src/helpers.php';
}

// ============================================================
// INISIALISASI SESSION (SLUG-AGNOSTIC)
// ============================================================
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['multi_opac'])) {
    $_SESSION['multi_opac'] = [
        'library_id'        => null,
        'library_slug'      => null,
        'search_library'    => null,
        'filter'            => [],
        'last_library_slug' => null
    ];
}

// ============================================================
// HELPER INTERNAL: PREPARE TEMPLATE VARIABLES
// ============================================================
/**
 * Memastikan seluruh variabel template aman dan terinisialisasi untuk PHP 8.3+
 */
function prepareTemplateVariables($library_id = null) {
    // 1. $topicCounts
    if (function_exists('getTopTopicsByLibrary')) {
        try {
            $GLOBALS['topicCounts'] = getTopTopicsByLibrary($library_id, 10);
        } catch (Throwable $e) {
            $GLOBALS['topicCounts'] = [];
        }
    } else {
        $GLOBALS['topicCounts'] = [];
    }

    // 2. $filterOptions
    if (function_exists('getFilterOptions')) {
        try {
            $GLOBALS['filterOptions'] = getFilterOptions($library_id);
        } catch (Throwable $e) {
            $GLOBALS['filterOptions'] = [];
        }
    } else {
        $GLOBALS['filterOptions'] = [];
    }

    // 3. $popularBiblios
    if (function_exists('getPopularCollections')) {
        try {
            $GLOBALS['popularBiblios'] = getPopularCollections($library_id, 5);
        } catch (Throwable $e) {
            $GLOBALS['popularBiblios'] = [];
        }
    } else {
        $GLOBALS['popularBiblios'] = [];
    }

    // 4. $topReaders
    if (function_exists('getTopReaders')) {
        try {
            $GLOBALS['topReaders'] = getTopReaders($library_id, 5);
        } catch (Throwable $e) {
            $GLOBALS['topReaders'] = [];
        }
    } else {
        $GLOBALS['topReaders'] = [];
    }

    // 5. $themeSettings
    if (function_exists('getTheme')) {
        try {
            $GLOBALS['themeSettings'] = getTheme($library_id);
        } catch (Throwable $e) {
            $GLOBALS['themeSettings'] = null;
        }
    } else {
        $GLOBALS['themeSettings'] = null;
    }

    $GLOBALS['current_library_id'] = $library_id;
}

// ============================================================
// CACHE PER LIBRARY
// ============================================================
function getSearchCache($keyword, $library_id, $page) {
    $cacheKey = 'search_' . md5($keyword . '_' . ($library_id ?? 'global') . '_' . $page);
    
    if (isset($_SESSION[$cacheKey]) && isset($_SESSION[$cacheKey . '_time'])) {
        $cacheTime = $_SESSION[$cacheKey . '_time'];
        if (time() - $cacheTime < 300) { // 5 menit
            return $_SESSION[$cacheKey];
        }
        unset($_SESSION[$cacheKey]);
        unset($_SESSION[$cacheKey . '_time']);
    }
    return null;
}

function setSearchCache($keyword, $library_id, $page, $results) {
    $cacheKey = 'search_' . md5($keyword . '_' . ($library_id ?? 'global') . '_' . $page);
    $_SESSION[$cacheKey] = $results;
    $_SESSION[$cacheKey . '_time'] = time();
}

// ============================================================
// DYNAMIC TIMEOUT
// ============================================================
function getLibraryDataCount($library_id) {
    global $dbs;
    if (empty($library_id)) return 0;
    
    $query = $dbs->query("SELECT COUNT(*) FROM biblio WHERE library_id = " . intval($library_id));
    $row = $query ? $query->fetch_row() : [0];
    return $row[0] ?? 0;
}

function getSearchTimeout($library_id) {
    $count = getLibraryDataCount($library_id);
    
    if ($count > 1000000) {
        return 10; // 10 detik untuk > 1 juta
    } elseif ($count > 500000) {
        return 8;  // 8 detik untuk > 500 ribu
    } elseif ($count > 100000) {
        return 6;  // 6 detik untuk > 100 ribu
    } else {
        return 5;  // 5 detik default
    }
}

function searchWithTimeout($searchQuery, $library_id, $limit, $offset, $filters, $timeout = 5) {
    set_time_limit($timeout);
    
    try {
        $startTime = microtime(true);
        $results = searchBibliosByLibrary($searchQuery, $library_id, $limit, $offset, $filters);
        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        
        if ($executionTime > 3) {
            error_log("⚠️ [Multi OPAC] Search slow: " . $executionTime . "s for keyword: " . $searchQuery . " (library_id: " . ($library_id ?? 'global') . ")");
        }
        
        return $results;
    } catch (Exception $e) {
        error_log("❌ [Multi OPAC] Search timeout: " . $e->getMessage());
        return [];
    }
}

// ============================================================
// 0.1 HANDLE BASKET AJAX ACTIONS
// ============================================================
if (isset($_POST['action']) && $_POST['action'] === 'remove_single_basket') {
    header('Content-Type: application/json');
    
    // Cek login
    if (empty($_SESSION['mid']) && empty($_SESSION['m_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Please login first.']);
        exit;
    }
    
    $member_id = $_SESSION['mid'] ?? $_SESSION['m_id'];
    $reserve_id = isset($_POST['reserve_id']) ? (int)$_POST['reserve_id'] : 0;
    
    if (!$reserve_id) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid reserve ID.']);
        exit;
    }
    
    try {
        $db = \SLiMS\DB::getInstance();
        $del = $db->prepare("DELETE FROM reserve WHERE reserve_id = ? AND member_id = ?");
        $del->execute([$reserve_id, $member_id]);
        
        if ($del->rowCount() > 0) {
            echo json_encode(['status' => 'success', 'message' => 'Item removed from basket.']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Item not found or already removed.']);
        }
    } catch (\Throwable $e) {
        echo json_encode(['status' => 'error', 'message' => 'System error: ' . $e->getMessage()]);
    }
    exit;
}
// ============================================================
// OFFSET LIMIT VALIDATOR
// ============================================================
function validateOffset($offset, $searchQuery, $lib_slug) {
    $maxOffset = 5000;
    if ($offset > $maxOffset) {
        $redirect = 'index.php?p=multi-opac' . (!empty($lib_slug) ? '&lib=' . urlencode($lib_slug) : '') . '&search_query=' . urlencode($searchQuery) . '&page=1';
        header('Location: ' . $redirect);
        exit;
    }
    return $offset;
}

// ============================================================
// 1. INSIALISASI KONTEKS TENANT & PENSIAPAN NAV_THEME (SENTRAL)
// ============================================================
$requested_p = $_GET['p'] ?? '';
$lib_slug   = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? $_SESSION['multi_opac']['library_slug'] ?? null;

$isLibraryContext = !empty($lib_slug) && $lib_slug !== 'pusat';

if ($isLibraryContext) {
    $library = getLibraryBySlug($lib_slug);
    if ($library) {
        $current_library_id                           = $library['library_id'];
        $_SESSION['multi_opac']['library_id']         = $library['library_id'];
        $_SESSION['multi_opac']['library_slug']       = $lib_slug;
        $_SESSION['multi_opac']['last_library_slug']  = $lib_slug;
        $GLOBALS['current_library']                   = $library;

        // Ambil Data Tema dari DB
        $themeFromDb = getTheme($current_library_id);
        $themeData = [
            'primary_color'   => $themeFromDb['primary_color'] ?? '#0d6efd',
            'secondary_color' => $themeFromDb['secondary_color'] ?? '#212529',
            'header_text'     => $themeFromDb['header_text'] ?? ($library['library_name'] ?? 'Perpustakaan'),
            'footer_text'     => $themeFromDb['footer_text'] ?? '',
            'logo'            => $themeFromDb['logo'] ?? ''
        ];

        // SET VARIABLE GLOBALS NAVBAR DI AWAL
        $GLOBALS['nav_lib_slug']     = $lib_slug;
        $GLOBALS['nav_library_name'] = $library['library_name'] ?? 'Perpustakaan';
        $GLOBALS['nav_theme']        = $themeData;
    }
}

// ============================================================
// 2. LOGOUT MEMBER HANDLER
// ============================================================
if (($requested_p === 'member' || $requested_p === 'member-login') && isset($_GET['logout'])) {
    unset(
        $_SESSION['mid'], $_SESSION['m_id'], $_SESSION['m_name'], 
        $_SESSION['m_email'], $_SESSION['m_type'], $_SESSION['m_member_type'],
        $_SESSION['m_image'], $_SESSION['m_login'], $_SESSION['m_logged_in'],
        $_SESSION['m_membership_pending'], $_SESSION['m_is_expired'], 
        $_SESSION['m_expire_date'], $_SESSION['m_register_date'], $_SESSION['m_mark_biblio']
    );

    $redirect_url = 'index.php?p=member-login' . ($lib_slug ? '&lib=' . urlencode($lib_slug) : '');
    header('Location: ' . $redirect_url);
    exit;
}

// ============================================================
// 3. HANDLE LIBRARIAN PAGE
// ============================================================
if ($requested_p === 'librarian') {
    ob_start();
    if (file_exists(__DIR__ . '/librarian.php')) {
        include __DIR__ . '/librarian.php';
    } else {
        echo '<div class="alert alert-danger">File librarian.php tidak ditemukan.</div>';
    }
    $page_content = ob_get_clean();

    $GLOBALS['custom_page_title']   = 'Pustakawan & Staf - ' . ($GLOBALS['nav_library_name'] ?? 'Perpustakaan');
    $GLOBALS['custom_page_content'] = $page_content;

    prepareTemplateVariables($current_library_id ?? null);
    extract($GLOBALS);

    $templateFile = __DIR__ . '/../template/library_page.tpl';
    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    } else {
        _showError('Template library_page.tpl tidak ditemukan', $templateFile);
    }
}

// ============================================================
// 4. HANDLE MEMBER & MEMBER LOGIN AREA (ADOPSI FUNGSI MEMBER)
// ============================================================
if (in_array($requested_p, ['member', 'member-login'])) {

    // --- A. PROCESS FORM LOGIN ---
    if (isset($_POST['logMe']) && !empty($_POST['memberID'])) {
        global $dbs;

        $memberID = trim($_POST['memberID']);
        $password = trim($_POST['password']);
        $memberID_escaped = $dbs->escape_string($memberID);
        
        $sql_text = "SELECT member_id, member_name, member_email, member_type_id, mpasswd, expire_date, register_date, member_image, is_pending 
                     FROM member 
                     WHERE member_id = '{$memberID_escaped}' OR member_email = '{$memberID_escaped}' 
                     LIMIT 1";

        $query = $dbs->query($sql_text);
        $row   = $query ? $query->fetch_assoc() : null;

        if ($row && (password_verify($password, $row['mpasswd']) || $row['mpasswd'] === md5($password))) {
            $today = date('Y-m-d');
            $is_expired = (!empty($row['expire_date']) && $row['expire_date'] !== '0000-00-00' && $row['expire_date'] < $today) ? 1 : 0;

            if ($is_expired) {
                $_SESSION['login_error'] = 'Masa keanggotaan Anda telah berakhir.';
                $redirect_login = 'index.php?p=member-login' . ($lib_slug ? '&lib=' . urlencode($lib_slug) : '');
                header('Location: ' . $redirect_login);
                exit;
            }

            $_SESSION['mid']                  = $row['member_id'];
            $_SESSION['m_id']                 = $row['member_id'];
            $_SESSION['m_name']               = $row['member_name'] ?? '';
            $_SESSION['m_email']              = $row['member_email'] ?? '';
            $_SESSION['m_type']               = $row['member_type_id'] ?? '';
            $_SESSION['m_member_type']        = $row['member_type_id'] ?? '';
            $_SESSION['m_image']              = $row['member_image'] ?? '';
            $_SESSION['m_login']              = 1;
            $_SESSION['m_logged_in']          = true;
            $_SESSION['m_membership_pending'] = (int)($row['is_pending'] ?? 0);
            $_SESSION['m_is_expired']         = $is_expired;
            $_SESSION['m_expire_date']        = $row['expire_date'] ?? '';
            $_SESSION['m_register_date']      = $row['register_date'] ?? date('Y-m-d');
            $_SESSION['m_mark_biblio']        = $_SESSION['m_mark_biblio'] ?? [];
            $_SESSION['m_institution']        = $row['institution'] ?? $_SESSION['m_institution'] ?? '';
            $_SESSION['m_can_reserve']        = $row['can_reserve'] ?? $_SESSION['m_can_reserve'] ?? 1;
            $_SESSION['m_reserve_limit']      = $row['reserve_limit'] ?? $_SESSION['m_reserve_limit'] ?? 5;

            unset($_SESSION['login_error']);
            
            $redirect_target = 'index.php?p=member' . ($lib_slug ? '&lib=' . urlencode($lib_slug) : '');
            header('Location: ' . $redirect_target);
            exit;
        } else {
            $_SESSION['login_error'] = 'ID Anggota atau Kata Sandi salah!';
            $redirect_login = 'index.php?p=member-login' . ($lib_slug ? '&lib=' . urlencode($lib_slug) : '');
            header('Location: ' . $redirect_login);
            exit;
        }
    }

    // --- B. JIKA SUDAH LOGIN DAN MEMBUKA p=member ---
    if (!empty($_SESSION['m_id'])) {
        // Sync Data Session
        $_SESSION['mid']           = $_SESSION['mid'] ?? $_SESSION['m_id'];
        $_SESSION['m_name']        = $_SESSION['m_name'] ?? '';
        $_SESSION['m_login']       = 1;
        $_SESSION['m_logged_in']   = true;

        // ============================================================
        // GUNAKAN MEMBER_CONTENT.TPL (ADOPSI FUNGSI MEMBER)
        // Semua section (loan, bookmark, title_basket, history, my_account)
        // ditangani di member_content.tpl
        // ============================================================
        $GLOBALS['isMemberLoggedIn'] = true;
        $GLOBALS['isMemberPage']     = true;
        $GLOBALS['custom_page_title'] = 'Area Anggota - ' . ($GLOBALS['nav_library_name'] ?? 'Perpustakaan');
        
        // Load konten member dari template
        ob_start();
        include __DIR__ . '/../template/member_content.tpl';
        $GLOBALS['custom_page_content'] = ob_get_clean();

        prepareTemplateVariables($current_library_id ?? null);
        extract($GLOBALS);

        $templateFile = __DIR__ . '/../template/library_page.tpl';
        if (file_exists($templateFile)) {
            include $templateFile;
            exit;
        }
    }
    // --- C. JIKA BELUM LOGIN DAN MEMBUKA p=member-login / p=member ---
    ob_start();
    include __DIR__ . '/member_login.php';
    $page_content = ob_get_clean();

    $GLOBALS['isMemberLoggedIn']   = false;
    $GLOBALS['isMemberPage']       = false;
    $GLOBALS['custom_page_title']   = 'Login Anggota - ' . ($GLOBALS['nav_library_name'] ?? 'Perpustakaan');
    $GLOBALS['custom_page_content'] = $page_content;

    prepareTemplateVariables($current_library_id ?? null);
    extract($GLOBALS);

    $templateFile = __DIR__ . '/../template/library_page.tpl';
    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    }
}
// ============================================================
// AKHIR SECTION 4
// ============================================================

// Jika $requested_p === 'multi-opac' (Beranda), script akan LEWAT dari blok di atas
// dan memuat pencarian katalog secara normal!

// ============================================================
// 0.2 HANDLE CUSTOM PAGES (libinfo, help)
// ============================================================
$custom_pages = ['libinfo', 'help'];

if (in_array($requested_p, $custom_pages)) {
    global $dbs;

    $lib_slug = $_GET['lib'] ?? null;
    $library  = $lib_slug ? getLibraryBySlug($lib_slug) : null;
    $current_library_id = $library['library_id'] ?? null;

    if ($library) {
        $_SESSION['multi_opac']['library_id']         = $library['library_id'];
        $_SESSION['multi_opac']['library_slug']       = $lib_slug;
        $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
        $GLOBALS['current_library']                   = $library;

        $lib_id       = intval($library['library_id']);
        $content_path = $lib_id . '-' . $requested_p;

        $query_str = "SELECT content_title, content_desc FROM content 
                      WHERE content_path = '{$dbs->escape_string($content_path)}' 
                         OR (library_id = {$lib_id} AND content_path LIKE '%{$requested_p}') 
                      LIMIT 1";
    } else {
        unset($_SESSION['multi_opac']['library_id']);
        unset($_SESSION['multi_opac']['library_slug']);
        $GLOBALS['current_library'] = null;

        $content_path = '0-' . $requested_p;

        $query_str = "SELECT content_title, content_desc FROM content 
                      WHERE content_path = '{$dbs->escape_string($content_path)}' 
                         OR content_path = '{$dbs->escape_string($requested_p)}' 
                         OR (library_id IS NULL AND content_path LIKE '%{$requested_p}') 
                         OR (library_id = 0 AND content_path LIKE '%{$requested_p}') 
                      LIMIT 1";
    }

    $query = $dbs->query($query_str);

    $page_title   = '';
    $page_content = '';

    if ($query && $query->num_rows > 0) {
        $data         = $query->fetch_assoc();
        $page_title   = $data['content_title'];
        $page_content = $data['content_desc'];
    }

    if (empty(trim($page_content))) {
        $titles = [
            'libinfo'   => 'Informasi Perpustakaan',
            'help'      => 'Bantuan & Layanan'
        ];
        
        $scope_label  = $library ? 'unit ini' : 'portal utama';
        $page_title   = $titles[$requested_p] ?? 'Informasi';
        $page_content = '<div class="alert alert-info rounded-3 mb-0">' .
                        '<i class="fa-solid fa-info-circle me-2"></i> Belum ada informasi khusus yang diisi untuk ' . $scope_label . '.' .
                        '</div>';
    }

    $GLOBALS['custom_page_title']   = $page_title;
    $GLOBALS['custom_page_content'] = $page_content;

    prepareTemplateVariables($current_library_id);
    extract($GLOBALS);

    $templateFile = __DIR__ . '/../template/library_page.tpl';
    if (file_exists($templateFile)) {
        include $templateFile;
        exit;
    } else {
        _showError('Template library_page.tpl tidak ditemukan', $templateFile);
    }
}

// ============================================================
// 0.3 HANDLE ACTION=DETAIL & NEWS_DETAIL
// ============================================================
if (isset($_GET['action']) && $_GET['action'] == 'detail' && isset($_GET['id'])) {
    $biblio_id = intval($_GET['id']);
    $lib_slug = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? null;
    
    if (!empty($lib_slug)) {
        $library = getLibraryBySlug($lib_slug);
        if ($library) {
            $_SESSION['multi_opac']['library_id']         = $library['library_id'];
            $_SESSION['multi_opac']['library_slug']       = $lib_slug;
            $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
            $GLOBALS['current_library']                   = $library;
        }
    }
    
    if ($biblio_id) {
        $redirectUrl = 'index.php?p=detail' . (!empty($lib_slug) ? '&lib=' . urlencode($lib_slug) : '') . '&id=' . $biblio_id;
        header('Location: ' . $redirectUrl);
        exit;
    } else {
        header('Location: index.php?p=multi-opac');
        exit;
    }
}

if ((isset($_GET['action']) && $_GET['action'] == 'news_detail') || (isset($_GET['p']) && $_GET['p'] == 'news_detail')) {
    $content_id = intval($_GET['id'] ?? 0);
    $lib_slug   = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? null;
    $current_library_id = null;

    if (!empty($lib_slug)) {
        $library = getLibraryBySlug($lib_slug);
        if ($library) {
            $current_library_id                          = $library['library_id'];
            $_SESSION['multi_opac']['library_id']         = $library['library_id'];
            $_SESSION['multi_opac']['library_slug']       = $lib_slug;
            $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
            $GLOBALS['current_library']                   = $library;
        }
    }

    if ($content_id > 0) {
        global $dbs;
        $query_str = "SELECT * FROM content WHERE content_id = {$content_id} LIMIT 1";
        $query     = $dbs->query($query_str);

        if ($query && $query->num_rows > 0) {
            $data = $query->fetch_assoc();
            $publishDate = !empty($data['publish_date']) ? $data['publish_date'] : $data['input_date'];
            $formattedDate = date('d M Y', strtotime($publishDate));

            $homeUrl = 'index.php?p=multi-opac' . (!empty($lib_slug) ? '&lib=' . urlencode($lib_slug) : '');

            $page_content = '
            <div class="news-detail-wrapper">
                <nav aria-label="breadcrumb" class="mb-3">
                  <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="' . $homeUrl . '">Beranda</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Detail Berita</li>
                  </ol>
                </nav>
                
                <h2 class="fw-bold mb-3 text-dark">' . htmlspecialchars($data['content_title']) . '</h2>
                <div class="text-muted small mb-4 pb-2 border-bottom">
                    <i class="fa-regular fa-calendar-alt me-1"></i> Dipublikasikan pada: ' . $formattedDate . '
                </div>
                
                <div class="news-body text-dark" style="line-height: 1.8; font-size: 1.05rem;">
                    ' . $data['content_desc'] . '
                </div>
                
                <div class="mt-5 pt-3 border-top">
                    <a href="' . $homeUrl . '" class="btn btn-outline-primary rounded-pill">
                        <i class="fa-solid fa-arrow-left me-1"></i> Kembali ke Beranda Perpustakaan
                    </a>
                </div>
            </div>';

            $GLOBALS['custom_page_title']   = $data['content_title'];
            $GLOBALS['custom_page_content'] = $page_content;

            prepareTemplateVariables($current_library_id);
            extract($GLOBALS);

            $templateFile = __DIR__ . '/../template/library_page.tpl';
            if (file_exists($templateFile)) {
                include $templateFile;
                exit;
            } else {
                _showError('Template library_page.tpl tidak ditemukan', $templateFile);
            }
        }
    }

    header('Location: index.php?p=multi-opac' . (!empty($lib_slug) ? '&lib=' . urlencode($lib_slug) : ''));
    exit;
}

// ============================================================
// 1. HANDLE CALLNUMBER / TOPIC (FIXED AUTOMATIC ROUTING)
// ============================================================
if (isset($_GET['callnumber'])) {
    $callnumberVal = trim($_GET['callnumber']);
    $lib_slug      = $_GET['lib'] ?? '';
    
    // Mapping callnumber digit tunggal ke DDC prefix jika numerik
    $ddcPrefixes = [
        '0' => '000', '1' => '100', '2' => '200', '3' => '300', '4' => '400',
        '5' => '500', '6' => '600', '7' => '700', '8' => '800', '9' => '900'
    ];
    
    $prefix = $ddcPrefixes[$callnumberVal] ?? $callnumberVal;
    
    if (!empty($prefix)) {
        $redirectUrl = 'index.php?p=multi-opac&search_query=' . urlencode($prefix);
        if (!empty($lib_slug)) {
            $redirectUrl .= '&lib=' . urlencode($lib_slug);
        }
        header('Location: ' . $redirectUrl);
        exit;
    }
}

// ============================================================
// 2. HANDLE DETAIL BUKU (p=detail)
// ============================================================
if (isset($_GET['p']) && $_GET['p'] == 'detail' && isset($_GET['id'])) {
    $biblio_id = intval($_GET['id']);
    $lib_slug  = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? null;
    
    if (!empty($lib_slug)) {
        $library = getLibraryBySlug($lib_slug);
        if ($library) {
            $_SESSION['multi_opac']['library_id']        = $library['library_id'];
            $_SESSION['multi_opac']['library_slug']      = $lib_slug;
            $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
            $GLOBALS['current_library']                  = $library;
        }
    }
    
    if ($biblio_id) {
        require_once __DIR__ . '/detail.php';
        exit;
    } else {
        $backUrl = 'index.php?p=multi-opac' . (!empty($lib_slug) ? '&lib=' . urlencode($lib_slug) : '');
        header('Location: ' . $backUrl);
        exit;
    }
}

// ============================================================
// 3. HANDLE RESET FILTER & FILTER
// ============================================================
if (isset($_GET['reset_filter'])) {
    $_SESSION['multi_opac']['filter'] = [];
    $redirectUrl = 'index.php?p=multi-opac';
    if (!empty($_GET['lib'])) {
        $redirectUrl .= '&lib=' . urlencode($_GET['lib']);
    }
    header('Location: ' . $redirectUrl);
    exit;
}

if (isset($_GET['filter']) && is_array($_GET['filter'])) {
    $_SESSION['multi_opac']['filter'] = array_merge(
        $_SESSION['multi_opac']['filter'] ?? [],
        $_GET['filter']
    );
    $_SESSION['multi_opac']['filter'] = array_filter($_SESSION['multi_opac']['filter']);
}

// ============================================================
// 4. HANDLE SEARCH QUERY & CATEGORY SEARCH
// ============================================================
$searchQuery = trim($_GET['search_query'] ?? $_GET['keywords'] ?? '');
$callnumber  = trim($_GET['callnumber'] ?? '');

if ($searchQuery !== '' || $callnumber !== '' || isset($_GET['search'])) {
    if (strlen($searchQuery) > 100) {
        $searchQuery = substr($searchQuery, 0, 100);
    }
    
    $lib_slug   = $_GET['lib'] ?? '';
    $library_id = null;
    $library    = null;
    $page       = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit      = 20;
    $offset     = ($page - 1) * $limit;
    
    $offset = validateOffset($offset, $searchQuery, $lib_slug);
    
    if (!empty($lib_slug)) {
        $library = getLibraryBySlug($lib_slug);
        if ($library) {
            $library_id = $library['library_id'];
            $_SESSION['multi_opac']['library_id']        = $library_id;
            $_SESSION['multi_opac']['library_slug']      = $lib_slug;
            $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
            $_SESSION['multi_opac']['search_library']    = $library_id;
            $GLOBALS['current_library']                  = $library;
        }
    } else {
        unset($_SESSION['multi_opac']['search_library']);
        $library_id = null;
        $lib_slug   = '';
    }
    
    $filters = $_SESSION['multi_opac']['filter'] ?? [];

    if ($callnumber !== '') {
        $filters['callnumber'] = $callnumber;
    }
    
    $cachedResults = getSearchCache($searchQuery, $library_id, $page);
    
    if ($cachedResults !== null) {
        $searchResults = $cachedResults;
    } else {
        $timeout = getSearchTimeout($library_id);
        $searchResults = searchWithTimeout($searchQuery, $library_id, $limit, $offset, $filters, $timeout);
        
        if (!empty($searchResults)) {
            setSearchCache($searchQuery, $library_id, $page, $searchResults);
        }
    }
    
    $GLOBALS['search_results'] = $searchResults;
    $GLOBALS['search_query']   = $searchQuery;
    $GLOBALS['current_page']   = $page;
    $GLOBALS['is_searching']    = true;
    
    // Persiapkan Variabel & Ekstrak untuk Template
    prepareTemplateVariables($library_id);
    extract($GLOBALS);

    // Pilih Template secara Otomatis berdasarkan Konteks (Global Portal vs Library Page)
    $templateFile = !empty($lib_slug) 
        ? __DIR__ . '/../template/library_page.tpl' 
        : __DIR__ . '/../template/landing_page.tpl';

    if (file_exists($templateFile)) {
        require_once $templateFile;
    } else {
        _showError('Template file tidak ditemukan', $templateFile);
    }
    exit;
}

// ============================================================
// 5. HANDLE ADVANCED SEARCH
// ============================================================
if (isset($_GET['search']) && $_GET['search'] == 'search') {
    $params = [
        'title'       => $_GET['title'] ?? '',
        'author'      => $_GET['author'] ?? '',
        'subject'     => $_GET['subject'] ?? '',
        'isbn'        => $_GET['isbn'] ?? '',
        'publishyear' => $_GET['publishyear'] ?? '',
        'location'    => $_GET['location'] ?? '',
        'gmd'         => $_GET['gmd'] ?? '',
        'colltype'    => $_GET['colltype'] ?? '',
    ];
    
    $lib_slug   = $_GET['lib'] ?? '';
    $library_id = null;
    
    if (!empty($lib_slug)) {
        $library = getLibraryBySlug($lib_slug);
        if ($library) {
            $library_id = $library['library_id'];
            $_SESSION['multi_opac']['library_id']        = $library_id;
            $_SESSION['multi_opac']['library_slug']      = $lib_slug;
            $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
            $_SESSION['multi_opac']['search_library']    = $library_id;
            $GLOBALS['current_library']                  = $library;
        }
    }
    
    $searchResults = advancedSearchBiblios($params, $library_id, 20, 0);
    
    $searchQueryParts = [];
    if (!empty($params['title']))       $searchQueryParts[] = $params['title'];
    if (!empty($params['author']))      $searchQueryParts[] = $params['author'];
    if (!empty($params['subject']))     $searchQueryParts[] = $params['subject'];
    if (!empty($params['isbn']))        $searchQueryParts[] = $params['isbn'];
    if (!empty($params['publishyear'])) $searchQueryParts[] = $params['publishyear'];
    
    $searchQuery = !empty($searchQueryParts) ? implode(' ', $searchQueryParts) : 'Advanced Search';
    
    $GLOBALS['search_results'] = $searchResults;
    $GLOBALS['search_query']   = $searchQuery;
    $GLOBALS['is_searching']    = true;
    
    // Persiapkan Variabel
    prepareTemplateVariables($library_id);
    extract($GLOBALS);

    $templateFile = !empty($lib_slug) 
        ? __DIR__ . '/../template/library_page.tpl' 
        : __DIR__ . '/../template/landing_page.tpl';

    if (file_exists($templateFile)) {
        require_once $templateFile;
    } else {
        _showError('Template file tidak ditemukan', $templateFile);
    }
    exit;
}

// ============================================================
// 6. HANDLE LIBRARY PAGE (TANPA KEYWORD -> TAMPILKAN BERANDA UNIT)
// ============================================================
$lib_slug = $_GET['lib'] ?? '';

if (!empty($lib_slug)) {
    $library = getLibraryBySlug($lib_slug);
    
    if ($library) {
        $library_id = $library['library_id'];
        $_SESSION['multi_opac']['library_id']        = $library_id;
        $_SESSION['multi_opac']['library_slug']      = $lib_slug;
        $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
        
        $GLOBALS['current_library'] = $library;
        
        // Persiapkan Variabel
        prepareTemplateVariables($library_id);
        extract($GLOBALS);

        $templateFile = __DIR__ . '/../template/library_page.tpl';
        if (file_exists($templateFile)) {
            include $templateFile;
            exit;
        } else {
            _showError('Template library_page.tpl tidak ditemukan', $templateFile);
        }
    } else {
        $_SESSION['multi_opac']['error'] = 'Perpustakaan "' . htmlspecialchars($lib_slug) . '" tidak ditemukan.';
        header('Location: index.php?p=multi-opac');
        exit;
    }
}

// ============================================================
// 7. LANDING PAGE (DEFAULT / PORTAL UTAMA GLOBAL)
// ============================================================
if (empty($_GET['lib'])) {
    $_SESSION['multi_opac']['library_id']        = null;
    $_SESSION['multi_opac']['library_slug']      = null;
    $_SESSION['multi_opac']['last_library_slug'] = null;
    unset($_SESSION['multi_opac']['search_library']);
    unset($GLOBALS['current_library']);
}

// Persiapkan Variabel Global
prepareTemplateVariables(null);
extract($GLOBALS);

$templateFile = __DIR__ . '/../template/landing_page.tpl';
if (file_exists($templateFile)) {
    require_once $templateFile;
} else {
    _showError('Template landing_page.tpl tidak ditemukan', $templateFile);
}
exit;

// ============================================================
// FUNGSI ERROR HANDLING
// ============================================================
function _showError($message, $path = '')
{
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>Error - Multi OPAC</title>
        <style>
            body { font-family: Arial, sans-serif; background: #f8f9fa; padding: 40px; display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; }
            .error-container { background: white; border-radius: 16px; padding: 40px; max-width: 600px; width: 100%; box-shadow: 0 4px 24px rgba(0,0,0,0.1); text-align: center; }
            .error-icon { font-size: 4rem; color: #dc3545; margin-bottom: 16px; }
            .error-container h2 { color: #212529; margin-bottom: 12px; }
            .error-message { color: #6c757d; margin-bottom: 16px; }
            .error-path { background: #f1f3f5; padding: 12px; border-radius: 8px; font-size: 0.85rem; color: #495057; word-break: break-all; margin-bottom: 20px; }
            .btn-back { display: inline-block; padding: 10px 30px; background: #0d6efd; color: white; text-decoration: none; border-radius: 8px; font-weight: 600; }
        </style>
    </head>
    <body>
        <div class="error-container">
            <div class="error-icon">⚠️</div>
            <h2>Error: <?= htmlspecialchars($message) ?></h2>
            <?php if ($path): ?>
                <div class="error-path"><strong>Path:</strong> <?= htmlspecialchars($path) ?></div>
            <?php endif; ?>
            <a href="index.php?p=multi-opac" class="btn-back"><i class="fa-solid fa-arrow-left me-1"></i> Kembali ke OPAC</a>
        </div>
    </body>
    </html>
    <?php
    exit;
}