<?php
/**
 * Halaman Detail Buku Multi OPAC
 * Path: plugins/multi_opac_path/pages/detail.php
 * Version: 1.4.1 (Multi-Library Member Type & Multi-Location Reserve Permission Check + Remove Basket Handler)
 */

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

// ============================================================
// LOAD HELPERS & UTILITIES
// ============================================================
require_once __DIR__ . '/../src/helpers.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$db = \SLiMS\DB::getInstance();

// ============================================================
// STATUS LOGIN MEMBER
// ============================================================
$loggedMemberID = $_SESSION['mid'] ?? ($_SESSION['m_id'] ?? null);
$isLoggedIn = !empty($loggedMemberID);

// Cek Pengaturan Global SLiMS OPAC Reservation
$opacReservationEnabled = true;
if (isset($sysconf['opac_reservation'])) {
    $opacReservationEnabled = (bool)$sysconf['opac_reservation'];
}

// ============================================================
// HELPER FUNCTION: VALiDASI HAK RESERVASI PERPUSER MEMBER PER LIBRARY_ID
// ============================================================
/**
 * Mengecek apakah member memiliki member_type yang aktif pada perpustakaan (library_id) tertentu
 * dan apakah tipe anggota tersebut mengizinkan reservasi.
 */
function checkMemberLibraryReservePermission($db, $memberId, $libraryId) {
    if (!$memberId || !$libraryId) {
        return [
            'allowed' => false,
            'limit' => 0,
            'reason' => 'Invalid member or library information.'
        ];
    }

    try {
        // Kueri memeriksa tabel member_member_type berdasarkan member_id & library_id koleksi
        $stmt = $db->prepare("
            SELECT 
                mmt.member_type_id,
                mmt.is_active,
                mt.member_type_name,
                mt.enable_reserve,
                mt.reserve_limit
            FROM member_member_type mmt
            INNER JOIN mst_member_type mt ON mmt.member_type_id = mt.member_type_id
            WHERE mmt.member_id = ? 
              AND mmt.library_id = ? 
              AND (mmt.is_active = 1 OR mmt.is_active IS NULL)
            LIMIT 1
        ");
        $stmt->execute([$memberId, $libraryId]);
        $rule = $stmt->fetch(PDO::FETCH_ASSOC);

        // Jika tidak ditemukan relasi member_member_type untuk library_id ini
        if (!$rule) {
            return [
                'allowed' => false,
                'limit' => 0,
                'reason' => 'Reservations for library collections are not permitted at this library.'
            ];
        }

        // Jika enable_reserve = 0 atau reserve_limit <= 0
        $enableReserve = (int)($rule['enable_reserve'] ?? 0);
        $reserveLimit = (int)($rule['reserve_limit'] ?? 0);

        if ($enableReserve !== 1 || $reserveLimit <= 0) {
            return [
                'allowed' => false,
                'limit' => 0,
                'reason' => 'Reservations for library collections are not permitted for your membership type at this library.'
            ];
        }

        return [
            'allowed' => true,
            'limit' => $reserveLimit,
            'type_name' => $rule['member_type_name'],
            'reason' => ''
        ];

    } catch (\Throwable $e) {
        return [
            'allowed' => false,
            'limit' => 0,
            'reason' => 'Error checking membership permissions: ' . $e->getMessage()
        ];
    }
}

// ============================================================
// HANDLER AJAX: ADD TO BASKET / RESERVASI
// ============================================================
if (isset($_POST['action']) && $_POST['action'] === 'add_to_reserve') {
    header('Content-Type: application/json');

    // 1. Cek Login
    if (!$isLoggedIn || !$loggedMemberID) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'Please login to your member account first.'
        ]);
        exit;
    }

    // 2. Cek Sakelar Reservasi Global OPAC
    if (!$opacReservationEnabled) {
        echo json_encode([
            'status' => 'error', 
            'message' => 'OPAC reservation feature is currently disabled globally.'
        ]);
        exit;
    }

    $b_id = isset($_POST['biblio_id']) ? (int)$_POST['biblio_id'] : 0;
    $i_code = isset($_POST['item_code']) ? trim($_POST['item_code']) : '';

    if (!$b_id || empty($i_code)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid book or item code requested.']);
        exit;
    }

    try {
        // 3. Ambil library_id dari koleksi/buku (biblio)
        $qLib = $db->prepare("SELECT library_id FROM biblio WHERE biblio_id = ?");
        $qLib->execute([$b_id]);
        $resLib = $qLib->fetch(PDO::FETCH_ASSOC);
        $bookLibraryId = $resLib['library_id'] ?? 1;

        // 4. VALiDASI HAK KEANGGOTAAN MEMBER DI LIBRARY_ID TERSEBUT
        $perm = checkMemberLibraryReservePermission($db, $loggedMemberID, $bookLibraryId);
        if (!$perm['allowed']) {
            echo json_encode([
                'status' => 'error', 
                'message' => $perm['reason']
            ]);
            exit;
        }

        $reserveLimit = $perm['limit'];

        // 5. Cek apakah member SUDAH PERNAH MERESERVASI DENGAN BIBLIO_ID (JUDUL BUKU) YANG SAMA
        $chkBiblio = $db->prepare("SELECT reserve_id, item_code FROM reserve WHERE member_id = ? AND biblio_id = ?");
        $chkBiblio->execute([$loggedMemberID, $b_id]);
        $existingBiblioRes = $chkBiblio->fetch(PDO::FETCH_ASSOC);

        if ($existingBiblioRes) {
            echo json_encode([
                'status' => 'warning', 
                'message' => 'You have already reserved an item from this title. Only one item per title is allowed for reservation.'
            ]);
            exit;
        }

        // 6. Cek total reservasi member saat ini vs Reserve Limit pada perpustakaan ini
        $chkTotal = $db->prepare("SELECT COUNT(*) FROM reserve WHERE member_id = ? AND library_id = ?");
        $chkTotal->execute([$loggedMemberID, $bookLibraryId]);
        $currentReserveCount = (int)$chkTotal->fetchColumn();

        if ($currentReserveCount >= $reserveLimit) {
            echo json_encode([
                'status' => 'error', 
                'message' => 'You have reached your maximum limit of ' . $reserveLimit . ' reserved title(s) for this library.'
            ]);
            exit;
        }

        // 7. Simpan ke database `reserve`
        $insRes = $db->prepare("
            INSERT INTO reserve (member_id, biblio_id, item_code, reserve_date, library_id) 
            VALUES (?, ?, ?, NOW(), ?)
        ");
        $insRes->execute([$loggedMemberID, $b_id, $i_code, $bookLibraryId]);

        // 8. Simpan Sinkronisasi ke Session Native SLiMS
        if (!isset($_SESSION['basket'])) $_SESSION['basket'] = [];
        if (!isset($_SESSION['reserve'])) $_SESSION['reserve'] = [];
        if (!isset($_SESSION['member_basket'])) $_SESSION['member_basket'] = [];

        $_SESSION['basket'][$i_code] = $i_code;
        $_SESSION['reserve'][$b_id] = $i_code;
        $_SESSION['member_basket'][$loggedMemberID][$i_code] = $b_id;

        echo json_encode([
            'status' => 'success', 
            'message' => 'Item successfully added to your Title Basket reservation!'
        ]);
        exit;

    } catch (\Throwable $e) {
        echo json_encode(['status' => 'error', 'message' => 'System error occurred: ' . $e->getMessage()]);
        exit;
    }
}

// ============================================================
// HANDLER AJAX: REMOVE FROM BASKET
// ============================================================
if (isset($_POST['action']) && $_POST['action'] === 'remove_from_basket') {
    header('Content-Type: application/json');
    
    if (!$isLoggedIn || !$loggedMemberID) {
        echo json_encode(['status' => 'error', 'message' => 'Please login first.']);
        exit;
    }
    
    $reserve_id = isset($_POST['reserve_id']) ? (int)$_POST['reserve_id'] : 0;
    $biblio_id = isset($_POST['biblio_id']) ? (int)$_POST['biblio_id'] : 0;
    
    if (!$reserve_id || !$biblio_id) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request.']);
        exit;
    }
    
    try {
        // Hapus dari tabel reserve
        $del = $db->prepare("DELETE FROM reserve WHERE reserve_id = ? AND member_id = ?");
        $del->execute([$reserve_id, $loggedMemberID]);
        
        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;
}

// ============================================================
// AMBIL PARAMETER DETAIL BUKU
// ============================================================
$biblio_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$lib_slug  = isset($_GET['lib']) && is_string($_GET['lib']) ? trim($_GET['lib']) : '';

if (!$biblio_id) {
    $fallbackUrl = function_exists('buildLibraryUrl') ? buildLibraryUrl('multi-opac') : 'index.php?p=multi-opac';
    header('Location: ' . $fallbackUrl);
    exit;
}

// ============================================================
// AMBIL DATA BUKU
// ============================================================
try {
    $stmt = $db->prepare("
        SELECT 
            b.biblio_id, 
            b.title, 
            b.isbn_issn, 
            b.publish_year,
            b.edition,
            b.collation,
            b.series_title,
            b.call_number,
            b.notes,
            b.image,
            b.input_date,
            b.library_id,
            mp.publisher_name as publisher,
            mpl.place_name as publish_place,
            mg.gmd_name as gmd,
            GROUP_CONCAT(DISTINCT ma.author_name SEPARATOR ' - ') AS author,
            GROUP_CONCAT(DISTINCT mt.topic SEPARATOR ', ') AS subject
        FROM biblio b
        LEFT JOIN mst_publisher mp ON b.publisher_id = mp.publisher_id
        LEFT JOIN mst_place mpl ON b.publish_place_id = mpl.place_id
        LEFT JOIN mst_gmd mg ON b.gmd_id = mg.gmd_id
        LEFT JOIN biblio_author ba ON ba.biblio_id = b.biblio_id
        LEFT JOIN mst_author ma ON ba.author_id = ma.author_id
        LEFT JOIN biblio_topic bt ON bt.biblio_id = b.biblio_id
        LEFT JOIN mst_topic mt ON bt.topic_id = mt.topic_id
        WHERE b.biblio_id = ?
        GROUP BY b.biblio_id
    ");
    $stmt->execute([$biblio_id]);
    $biblio = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (\Throwable $e) {
    $biblio = false;
}

if (!$biblio) {
    echo "<!DOCTYPE html><html><head><title>Error</title></head><body>
          <div class='container mt-5'><div class='alert alert-danger'>Buku tidak ditemukan atau terjadi kesalahan database.</div></div>
          </body></html>";
    exit;
}

// EVALUASI NAMA PERPUSTAKAAN PEMILIK BUKU
$bookLibraryId = $biblio['library_id'] ?? 1;
$itemLibraryName = 'Perpustakaan';

if ($bookLibraryId && function_exists('getLibraryNameById')) {
    $fetchedName = getLibraryNameById($bookLibraryId);
    if (!empty($fetchedName)) {
        $itemLibraryName = $fetchedName;
    }
}

// VALiDASI HAK MEMBER UNTUK KOLEKSI DARI LIBRARY_ID INI
$memberPermission = [
    'allowed' => false,
    'limit' => 0,
    'reason' => 'Please login to your member account first.'
];

if ($isLoggedIn) {
    $memberPermission = checkMemberLibraryReservePermission($db, $loggedMemberID, $bookLibraryId);
}

// HITUNG AVAILABILITY
try {
    $qItem = $db->prepare("SELECT COUNT(*) FROM item WHERE biblio_id = ?");
    $qItem->execute([$biblio_id]);
    $totalItem = (int)$qItem->fetchColumn();

    $qLoan = $db->prepare("
        SELECT COUNT(*) FROM loan AS l 
        INNER JOIN item AS i ON l.item_code = i.item_code 
        WHERE l.is_lent = 1 AND l.is_return = 0 AND i.biblio_id = ?
    ");
    $qLoan->execute([$biblio_id]);
    $totalLoan = (int)$qLoan->fetchColumn();

    $availabilityCount = max(0, $totalItem - $totalLoan);
} catch (\Throwable $e) {
    $availabilityCount = 0;
}

// COVER GAMBAR
$defaultCover = 'plugins/multi_opac_path/assets/images/default_book.png';
$coverUrl = $defaultCover;

if (!empty($biblio['image']) && is_string($biblio['image'])) {
    $img = trim($biblio['image']);
    if (filter_var($img, FILTER_VALIDATE_URL)) {
        $coverUrl = $img;
    } else {
        $cleanImg = preg_replace('/^(images\/docs\/|images\/)/i', '', $img);
        $docPathPhysical = SB . 'images/docs/' . $cleanImg;
        $imgPathPhysical = SB . 'images/' . $cleanImg;
        
        if (file_exists($docPathPhysical)) {
            $coverUrl = SWB . 'images/docs/' . $cleanImg;
        } elseif (file_exists($imgPathPhysical)) {
            $coverUrl = SWB . 'images/' . $cleanImg;
        } else {
            $coverUrl = $defaultCover;
        }
    }
}

// AMBIL EKSEMPLAR
$items = [];
try {
    $stmt = $db->prepare("
        SELECT 
            i.item_id, 
            i.item_code,
            i.call_number, 
            ml.location_name AS location,
            mis.item_status_name AS status
        FROM item i
        LEFT JOIN mst_location ml ON i.location_id = ml.location_id
        LEFT JOIN mst_item_status mis ON i.item_status_id = mis.item_status_id
        WHERE i.biblio_id = ?
        ORDER BY i.call_number ASC
    ");
    $stmt->execute([$biblio_id]);
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (\Throwable $e) {
    $items = [];
}

// CEK DATA RESERVASI MEMBER UNTUK BIBLIO ID INI
$reservedItemCodes = [];
$hasReservedThisBiblio = false;

if ($isLoggedIn && $loggedMemberID) {
    try {
        $qResBib = $db->prepare("SELECT item_code FROM reserve WHERE member_id = ? AND biblio_id = ?");
        $qResBib->execute([$loggedMemberID, $biblio_id]);
        $resRows = $qResBib->fetchAll(PDO::FETCH_COLUMN);
        if (!empty($resRows)) {
            $reservedItemCodes = $resRows;
            $hasReservedThisBiblio = true;
        }
    } catch (\Throwable $e) {}
}

// KONTEKS NAVIGASI
$isLibraryContext = !empty($lib_slug);
$library_id = null;
$library_name = '';

if ($isLibraryContext) {
    $lib = function_exists('getLibraryBySlug') ? getLibraryBySlug($lib_slug) : null;
    if ($lib) {
        $library_id = $lib['library_id'];
        $library_name = $lib['library_name'];
    } else {
        $library_id = $bookLibraryId;
        $library_name = $itemLibraryName;
    }
    $backUrl = function_exists('buildLibraryUrl') ? buildLibraryUrl('multi-opac', $lib_slug) : 'index.php?p=multi-opac&lib=' . urlencode($lib_slug);
} else {
    $backUrl = 'index.php?p=multi-opac';
    $library_id = $bookLibraryId;
    $library_name = $itemLibraryName;
}

$themeFromDb = ($library_id && function_exists('getTheme')) ? getTheme($library_id) : null;
$themeData = [
    'primary_color'   => $themeFromDb['primary_color'] ?? '#0d6efd',
    'secondary_color' => $themeFromDb['secondary_color'] ?? '#212529',
    'header_text'     => $themeFromDb['header_text'] ?? ($library_name ?: 'Global Search'),
    'footer_text'     => $themeFromDb['footer_text'] ?? '© ' . date('Y') . ' SLiMS Multi OPAC',
    'logo'            => $themeFromDb['logo'] ?? ''
];

$config = function_exists('getMultiOpacConfig') ? getMultiOpacConfig() : [];
$showBadge = $config['show_library_badge'] ?? 1;

$isBookmarked = isset($_SESSION['bookmark'][$biblio_id]);
$bookmarkClass = $isBookmarked ? 'bg-success text-white' : 'text-secondary';
$bookmarkText = $isBookmarked ? 'Bookmarked' : 'Bookmark';
$citeUrl = SWB . 'index.php?p=cite&id=' . $biblio_id . '&keywords=' . urlencode($_GET['keywords'] ?? '');
$marcUrl = SWB . 'index.php?p=show_detail&id=' . $biblio_id . '&MARC=true';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($biblio['title'] ?? 'Detail Buku') ?> | <?= htmlspecialchars($isLibraryContext ? $library_name : 'Pencarian Global') ?></title>
    
    <link rel="stylesheet" href="plugins/multi_opac_path/assets/css/all.min.css">
    <link href="<?= SWB ?>template/default/assets/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="<?= SWB ?>js/toastr/toastr.min.css">
    <link rel="stylesheet" href="plugins/multi_opac_path/assets/css/bookdetails.css">

    <style>
        :root {
            --primary-color: <?= htmlspecialchars($themeData['primary_color']) ?>;
            --secondary-color: <?= htmlspecialchars($themeData['secondary_color']) ?>;
        }
        .availability-box {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 12px;
            background: #f8f9fa;
        }
        .btn-custom-basket {
            white-space: nowrap;
        }
    </style>
</head>
<body>

<?php
if ($isLibraryContext) {
    $GLOBALS['nav_lib_slug'] = $lib_slug;
    $GLOBALS['nav_library_name'] = $library_name;
    $GLOBALS['nav_theme'] = $themeData;
    $navLibFile = __DIR__ . '/../template/_navbar_library.inc.php';
    if (file_exists($navLibFile)) include_once $navLibFile;
} else {
    $navPluginFile = __DIR__ . '/../template/_navbar_plugin.inc.php';
    if (file_exists($navPluginFile)) include_once $navPluginFile;
}
?>

<header class="detail-header">
    <div class="container">
        <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
            <a href="<?= htmlspecialchars($backUrl) ?>" class="back-link">
                <i class="fa-solid fa-arrow-left me-1"></i> 
                <?= $isLibraryContext ? 'Kembali ke ' . htmlspecialchars($library_name) : 'Kembali ke Beranda' ?>
            </a>
            <div class="d-flex align-items-center gap-2">
                <?php if ($isLibraryContext && !empty($themeData['logo'])): ?>
                    <img src="<?= htmlspecialchars($themeData['logo']) ?>" alt="Logo" style="max-height: 30px;">
                <?php endif; ?>
                <?php if ($isLibraryContext && !empty($library_name)): ?>
                    <span class="badge-library"><?= htmlspecialchars($library_name) ?></span>
                <?php else: ?>
                    <span class="badge bg-primary text-white px-3 py-2 rounded-pill"><i class="fa-solid fa-globe me-1"></i> Pencarian Global</span>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="row align-items-center">
            <div class="col-lg-7">
                <h1 class="h3 fw-bold mb-0">
                    <i class="fa-solid fa-book-open me-2"></i> Detail Buku
                </h1>
            </div>
            <div class="col-lg-5 mt-3 mt-lg-0">
                <form action="index.php" method="get" class="search-wrapper">
                    <input type="hidden" name="p" value="multi-opac">
                    <?php if ($isLibraryContext): ?>
                        <input type="hidden" name="lib" value="<?= htmlspecialchars($lib_slug) ?>">
                    <?php endif; ?>
                    <div class="d-flex gap-2 w-100">
                        <input type="text" name="keywords" class="form-control" 
                               placeholder="Cari judul buku, pengarang, atau subjek..." 
                               value="<?= htmlspecialchars((string)($_GET['keywords'] ?? '')) ?>">
                        <button type="submit" class="btn btn-theme bg-white text-primary border-0 rounded-pill px-4 fw-semibold">
                            <i class="fa-solid fa-magnifying-glass"></i> Cari
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</header>

<main class="container my-4">
    <div class="row g-4">
        
        <!-- SIDEBAR KIRI -->
        <div class="col-lg-4">
            <div class="detail-card text-center">
                <img src="<?= htmlspecialchars($coverUrl) ?>" alt="Cover <?= htmlspecialchars($biblio['title'] ?? '') ?>" class="book-cover-large mb-3">
                
                <h5 class="fw-bold mt-2"><?= htmlspecialchars($biblio['title'] ?? 'Tanpa Judul') ?></h5>
                <?php if (!empty($biblio['author'])): ?>
                    <p class="text-muted small"><?= htmlspecialchars($biblio['author']) ?></p>
                <?php endif; ?>

                <!-- TOMBOL BOOKMARK -->
                <div class="d-flex justify-content-center gap-2 my-3">
                    <button type="button" id="btn-custom-bookmark" data-id="<?= $biblio_id ?>" class="btn btn-sm border <?= $bookmarkClass ?> font-weight-bolder px-3 py-2">
                        <i class="fa-solid fa-bookmark me-1"></i>
                        <span id="label-bookmark"><?= $bookmarkText ?></span>
                    </button>
                </div>

                <!-- BOX AVAILABILITY -->
                <div class="availability-box mb-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <span class="text-muted small fw-semibold">Ketersediaan Stok:</span>
                        <span class="fs-5 fw-bold <?= $availabilityCount > 0 ? 'text-success' : 'text-danger' ?>">
                            <?= $availabilityCount ?> Eksemplar
                        </span>
                    </div>
                </div>

                <!-- TOMBOL MARC & CITE -->
                <div class="d-grid gap-2">
                    <a class="btn btn-outline-secondary btn-sm" href="<?= $marcUrl ?>" target="_blank">
                        <i class="fa-solid fa-file-code me-1"></i> MARC Download
                    </a>
                    <a class="btn btn-outline-secondary btn-sm" href="<?= $citeUrl ?>" target="_blank">
                        <i class="fa-solid fa-quote-right me-1"></i> Cite (Sitasi)
                    </a>
                </div>

                <hr>
                
                <div class="text-start small">
                    <div class="d-flex justify-content-between py-1">
                        <span class="text-muted">GMD</span>
                        <span><?= htmlspecialchars($biblio['gmd'] ?? '-') ?></span>
                    </div>
                    <div class="d-flex justify-content-between py-1">
                        <span class="text-muted">Call Number</span>
                        <span class="fw-semibold"><?= htmlspecialchars($biblio['call_number'] ?? '-') ?></span>
                    </div>
                    <div class="d-flex justify-content-between py-1">
                        <span class="text-muted">Penerbit</span>
                        <span><?= htmlspecialchars($biblio['publisher'] ?? '-') ?></span>
                    </div>
                    <div class="d-flex justify-content-between py-1">
                        <span class="text-muted">Tahun</span>
                        <span><?= htmlspecialchars($biblio['publish_year'] ?? '-') ?></span>
                    </div>
                    <div class="d-flex justify-content-between py-1">
                        <span class="text-muted">ISBN</span>
                        <span><?= htmlspecialchars($biblio['isbn_issn'] ?? '-') ?></span>
                    </div>
                    <?php if ($showBadge && !empty($itemLibraryName)): ?>
                        <div class="d-flex justify-content-between py-1">
                            <span class="text-muted">Lokasi Koleksi</span>
                            <span class="fw-semibold text-primary"><?= htmlspecialchars($itemLibraryName) ?></span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- MAIN CONTENT KANAN -->
        <div class="col-lg-8">
            <div class="detail-card">
                <h5 class="fw-bold mb-3">
                    <i class="fa-solid fa-circle-info me-2 text-primary"></i>
                    Informasi Detail
                </h5>
                
                <div class="row g-3">
                    <div class="col-12">
                        <div class="label"><i class="fa-solid fa-book me-1"></i> Judul Utama</div>
                        <div class="value value-title"><?= htmlspecialchars($biblio['title'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-user-pen me-1"></i> Pengarang</div>
                        <div class="value"><?= htmlspecialchars($biblio['author'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-tags me-1"></i> Subjek / Topik</div>
                        <div class="value"><?= htmlspecialchars($biblio['subject'] ?? '-') ?></div>
                    </div>

                    <hr class="my-2 opacity-25">

                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-building me-1"></i> Penerbit</div>
                        <div class="value"><?= htmlspecialchars($biblio['publisher'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-city me-1"></i> Kota Terbit</div>
                        <div class="value"><?= htmlspecialchars($biblio['publish_place'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-calendar-days me-1"></i> Tahun Terbit</div>
                        <div class="value"><?= htmlspecialchars($biblio['publish_year'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-layer-group me-1"></i> Edisi</div>
                        <div class="value"><?= htmlspecialchars($biblio['edition'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-barcode me-1"></i> ISBN / ISSN</div>
                        <div class="value"><?= htmlspecialchars($biblio['isbn_issn'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-bookmark me-1"></i> Nomor Panggil</div>
                        <div class="value"><?= htmlspecialchars($biblio['call_number'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-file-lines me-1"></i> Deskripsi Fisik</div>
                        <div class="value"><?= htmlspecialchars($biblio['collation'] ?? '-') ?></div>
                    </div>
                    <div class="col-md-6">
                        <div class="label"><i class="fa-solid fa-list-ol me-1"></i> Judul Seri</div>
                        <div class="value"><?= htmlspecialchars($biblio['series_title'] ?? '-') ?></div>
                    </div>

                    <?php if (!empty($biblio['notes'])): ?>
                        <div class="col-12">
                            <div class="label"><i class="fa-solid fa-note-sticky me-1"></i> Catatan / Abstrak</div>
                            <div class="value bg-light p-2 rounded border-start border-3 border-secondary">
                                <?= nl2br(htmlspecialchars($biblio['notes'])) ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="col-12">
                        <div class="label"><i class="fa-regular fa-calendar-check me-1"></i> Tanggal Reg. Masuk</div>
                        <div class="value text-muted">
                            <?= !empty($biblio['input_date']) ? date('d F Y', strtotime($biblio['input_date'])) : '-' ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- TABEL EKSEMPLAR FISIK & TOMBOL BASKET -->
            <?php if (count($items) > 0): ?>
                <div class="detail-card mt-4">
                    <h5 class="fw-bold mb-3 d-flex justify-content-between align-items-center">
                        <span>
                            <i class="fa-solid fa-boxes me-2 text-primary"></i>
                            Daftar Eksemplar Fisik
                            <span class="badge bg-secondary ms-2"><?= count($items) ?></span>
                        </span>
                    </h5>

                    <!-- PESAN INFORMASI STATUS RESERVASI MEMBER (BAHASA INGGRIS) -->
                    <div class="mb-3">
                        <?php if (!$opacReservationEnabled || !$memberPermission['allowed']): ?>
                            <div class="alert alert-warning py-2 px-3 mb-2 small d-flex align-items-center">
                                <i class="fa-solid fa-circle-exclamation me-2 fs-6"></i>
                                <div><strong>Reservation Notice:</strong> <?= htmlspecialchars($memberPermission['reason']) ?></div>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info py-2 px-3 mb-2 small d-flex align-items-center">
                                <i class="fa-solid fa-circle-info me-2 fs-6"></i>
                                <div><strong>Reservation Info:</strong> As a registered member of <strong><?= htmlspecialchars($itemLibraryName) ?></strong>, you can reserve up to <strong><?= $memberPermission['limit'] ?></strong> title(s). Note that only 1 item per title/book can be added to your basket.</div>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-sm table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>Kode Barcode</th>
                                    <th>No. Panggil</th>
                                    <th>Lokasi</th>
                                    <th>Status Item</th>
                                    <th class="text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($items as $item): 
                                $code = $item['item_code'] ?? '';
                                $isItemReserved = in_array($code, $reservedItemCodes);
                                $isBtnDisabled = false;
                                $btnText = 'Add to Basket';
                                $btnClass = 'btn-primary';

                                // Logika tombol disabled
                                if (!$opacReservationEnabled || !$memberPermission['allowed']) {
                                    $isBtnDisabled = true;
                                    $btnText = 'Reservation Disabled';
                                    $btnClass = 'btn-secondary opacity-50';
                                } elseif ($hasReservedThisBiblio) {
                                    $isBtnDisabled = true;
                                    if ($isItemReserved) {
                                        $btnText = 'Already in Basket';
                                        $btnClass = 'btn-success';
                                    } else {
                                        $btnText = 'Title Already Reserved';
                                        $btnClass = 'btn-secondary opacity-50';
                                    }
                                }
                            ?>
                                <tr>
                                    <td><code><?= htmlspecialchars($code ?: '-') ?></code></td>
                                    <td><code><?= htmlspecialchars($item['call_number'] ?? '-') ?></code></td>
                                    <td><?= htmlspecialchars($item['location'] ?? '-') ?></td>
                                    <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($item['status'] ?? 'Available') ?></span></td>
                                    <td class="text-center">
                                        <button type="button" 
                                                class="btn btn-sm <?= $btnClass ?> btn-custom-basket" 
                                                data-biblio="<?= $biblio_id ?>" 
                                                data-item="<?= htmlspecialchars($code) ?>"
                                                <?= $isBtnDisabled ? 'disabled="disabled"' : '' ?>>
                                            <i class="fa-solid <?= $isItemReserved ? 'fa-check' : 'fa-cart-plus' ?> me-1"></i> <?= $btnText ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<footer class="detail-footer text-center">
    <div class="container">
        <p class="mb-1 text-white fw-semibold"><?= htmlspecialchars($themeData['footer_text']) ?></p>
        <small>Multi OPAC Path v1.4.1 | <?= htmlspecialchars($isLibraryContext ? $library_name : 'Global Search') ?></small>
    </div>
</footer>

<!-- JS DEPENDENCIES -->
<script src="<?= SWB ?>template/default/assets/js/jquery.min.js"></script>
<script src="<?= SWB ?>template/default/assets/js/bootstrap.bundle.min.js"></script>
<script src="<?= SWB ?>js/toastr/toastr.min.js"></script>

<script>
$(document).ready(function() {
    var IS_LOGGED_IN = <?= json_encode($isLoggedIn) ?>;
    var MEMBER_PERM_ALLOWED = <?= json_encode($memberPermission['allowed']) ?>;
    var MEMBER_PERM_REASON = <?= json_encode($memberPermission['reason']) ?>;

    // ============================================================
    // HANDLER TOMBOL ADD TO BASKET
    // ============================================================
    $('.btn-custom-basket').on('click', function(e) {
        e.preventDefault();
        var $btn = $(this);

        if ($btn.is(':disabled')) {
            return false;
        }

        if (!IS_LOGGED_IN) {
            toastr.error('Please login to your member account first.', 'Access Denied');
            return false;
        }

        if (!MEMBER_PERM_ALLOWED) {
            toastr.error(MEMBER_PERM_REASON, 'Reservation Disabled');
            return false;
        }

        var biblioId = $btn.data('biblio');
        var itemCode = $btn.data('item');

        $btn.prop('disabled', true);

        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: { 
                action: 'add_to_reserve',
                biblio_id: biblioId,
                item_code: itemCode 
            },
            dataType: 'json',
            success: function(res) {
                if (res.status === 'success') {
                    toastr.success(res.message, 'Success');
                    $('.btn-custom-basket').prop('disabled', true).addClass('btn-secondary opacity-50').removeClass('btn-primary');
                    $btn.addClass('btn-success').removeClass('btn-secondary opacity-50').html('<i class="fa-solid fa-check me-1"></i> Already in Basket');
                } else if (res.status === 'warning') {
                    toastr.warning(res.message, 'Notice');
                    $btn.prop('disabled', true);
                } else {
                    toastr.error(res.message, 'Failed');
                    $btn.prop('disabled', false);
                }
            },
            error: function() {
                $btn.prop('disabled', false);
                toastr.error('System error occurred while processing reservation.', 'Error');
            }
        });
    });

    // ============================================================
    // HANDLER TOMBOL BOOKMARK
    // ============================================================
    $('#btn-custom-bookmark').on('click', function(e) {
        e.preventDefault();
        var biblioId = $(this).data('id');
        var $btn = $(this);
        var $lbl = $('#label-bookmark');

        $.ajax({
            url: '<?= SWB ?>index.php?p=bookmark',
            type: 'POST',
            data: { id: biblioId },
            dataType: 'json',
            success: function(res) {
                if ($btn.hasClass('bg-success')) {
                    $btn.removeClass('bg-success text-white').addClass('text-secondary');
                    $lbl.text('Bookmark');
                } else {
                    $btn.removeClass('text-secondary').addClass('bg-success text-white');
                    $lbl.text('Bookmarked');
                }
                toastr.success(res.message || 'Status bookmark berhasil diperbarui!');
            },
            error: function() {
                if ($btn.hasClass('bg-success')) {
                    $btn.removeClass('bg-success text-white').addClass('text-secondary');
                    $lbl.text('Bookmark');
                } else {
                    $btn.removeClass('text-secondary').addClass('bg-success text-white');
                    $lbl.text('Bookmarked');
                }
                toastr.info('Bookmark diperbarui.');
            }
        });
    });
});
</script>

</body>
</html>