<?php
/**
 * Halaman Title Basket untuk Member
 * Path: plugins/multi_opac_path/pages/member_basket.php
 * Version: 1.1.3 (Fixed jQuery loading order)
 */

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

// ============================================================
// AMBIL PARAMETER lib
// ============================================================
$lib_slug = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? '';

// ============================================================
// FUNGSI SHOW BASKET
// ============================================================
function showBasketFromReserve($num_recs_show = 20)
{
    global $dbs, $_SESSION, $sysconf;

    $sql = "SELECT 
                r.reserve_id,
                r.biblio_id,
                r.item_code,
                r.reserve_date,
                r.library_id,
                b.title,
                b.isbn_issn,
                b.publish_year,
                l.library_code,
                l.library_name
            FROM reserve r
            LEFT JOIN biblio b ON r.biblio_id = b.biblio_id
            LEFT JOIN mst_library l ON r.library_id = l.library_id
            WHERE r.member_id = '" . $dbs->escape_string($_SESSION['mid']) . "'
            ORDER BY r.reserve_date DESC
            LIMIT " . intval($num_recs_show);

    $query = $dbs->query($sql);
    $reserveItems = [];
    while ($row = $query->fetch_assoc()) {
        $reserveItems[] = $row;
    }

    $lib_slug = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? '';

    $_result = '<div class="memberBasketInfo">' . count($reserveItems) . ' ' . __('title(s) on basket') . '</div>' . "\n";

    if (count($reserveItems) > 0) {
        $_result .= '<table class="memberBasketList table table-striped" cellpadding="5" cellspacing="0">';
        $_result .= '<thead>';
        $_result .= '<tr class="dataListHeader" style="font-weight: bold;">';
        $_result .= '<th width="40">' . __('Remove') . '</th>';
        $_result .= '<th>' . __('Title') . '</th>';
        $_result .= '<th>' . __('Library') . '</th>';
        $_result .= '<th>' . __('Reserve Date') . '</th>';
        $_result .= '<th width="100">' . __('Action') . '</th>';
        $_result .= '</tr>';
        $_result .= '</thead>';
        $_result .= '<tbody>';

        foreach ($reserveItems as $item) {
            $_result .= '<tr id="basket-row-' . $item['reserve_id'] . '">';
            $_result .= '<td><input type="checkbox" name="basket[]" class="basketItem" value="' . $item['reserve_id'] . '" /></td>';
            $_result .= '<td><a target="_blank" href="' . buildLibraryUrl('detail', $lib_slug, ['id' => $item['biblio_id']]) . '">' . htmlspecialchars($item['title'] ?? 'Tanpa Judul') . '</a></td>';
            $_result .= '<td><span class="badge bg-info text-dark">' . htmlspecialchars($item['library_code'] ?? '') . '</span><br><small>' . htmlspecialchars($item['library_name'] ?? '') . '</small></td>';
            $_result .= '<td>' . date('d-m-Y H:i', strtotime($item['reserve_date'])) . '</td>';
            $_result .= '<td>';
            $_result .= '<button type="button" class="btn btn-sm btn-danger remove-single" data-reserve-id="' . $item['reserve_id'] . '" data-biblio-id="' . $item['biblio_id'] . '">';
            $_result .= '<i class="fa fa-trash"></i>';
            $_result .= '</button>';
            $_result .= '</td>';
            $_result .= '</tr>';
        }

        $_result .= '</tbody>';
        $_result .= '</table>';

        $lib_slug_enc = urlencode($lib_slug);
        $_result .= '<div class="memberBasketAction my-3">';
        $_result .= '<form name="memberBasketListForm" id="memberBasketListForm" action="index.php?p=member&sec=title_basket&lib=' . $lib_slug_enc . '" method="post">';
        $_result .= '<a href="index.php?p=member&sec=title_basket&lib=' . $lib_slug_enc . '" class="btn btn-sm btn-primary basket reserve"><i class="fa fa-save"></i>&nbsp;&nbsp;' . __('Reserve title(s) on Basket') . '</a> ';
        $_result .= '<a href="index.php?p=member&sec=title_basket&lib=' . $lib_slug_enc . '" class="btn btn-sm btn-secondary basket clearAll" postdata="clear_biblio=1"><i class="fa fa-eraser"></i>&nbsp;&nbsp;' . __('Clear Basket') . '</a> ';
        $_result .= '<a href="index.php?p=member&sec=title_basket&lib=' . $lib_slug_enc . '" class="btn btn-sm btn-secondary basket clearOne"><i class="fa fa-trash"></i>&nbsp;&nbsp;' . __('Remove selected title(s) from Basket') . '</a> ';
        $_result .= '</form>';
        $_result .= '</div>';

    } else {
        $_result .= '<div class="text-center py-5 text-muted">';
        $_result .= '<i class="fa-solid fa-shopping-basket fa-3x mb-3 opacity-25"></i>';
        $_result .= '<h5>' . __('Belum ada title di basket Anda') . '</h5>';
        $_result .= '<p class="small">' . __('Tambahkan title dari halaman detail buku') . '</p>';
        $_result .= '</div>';
    }

    return $_result;
}

// ============================================================
// HANDLER ACTION
// ============================================================

// 1. Clear Basket
if (isset($_POST['clear_biblio'])) {
    $del = $dbs->prepare("DELETE FROM reserve WHERE member_id = ?");
    $del->execute([$_SESSION['mid']]);
    $_SESSION['info']['data'] = __('Basket data cleared!');
    $_SESSION['info']['status'] = 'success';
    header('Location: index.php?p=member&sec=title_basket&lib=' . urlencode($_GET['lib'] ?? ''));
    exit;
}

// 2. Remove selected items
if (isset($_POST['basketRemove']) && isset($_POST['basket']) && count($_POST['basket']) > 0) {
    $ids = implode(',', array_map('intval', $_POST['basket']));
    $del = $dbs->prepare("DELETE FROM reserve WHERE reserve_id IN ($ids) AND member_id = ?");
    $del->execute([$_SESSION['mid']]);
    $_SESSION['info']['data'] = __('Selected basket data removed!');
    $_SESSION['info']['status'] = 'success';
    header('Location: index.php?p=member&sec=title_basket&lib=' . urlencode($_GET['lib'] ?? ''));
    exit;
}

// 2b. Remove single item (AJAX)
if (isset($_POST['action']) && $_POST['action'] === 'remove_single_basket') {
    header('Content-Type: application/json');
    
    $reserve_id = isset($_POST['reserve_id']) ? (int)$_POST['reserve_id'] : 0;
    $member_id = $_SESSION['mid'] ?? null;
    
    if (!$member_id || !$reserve_id) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request.']);
        exit;
    }
    
    try {
        $del = $dbs->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;
}

// 3. Reserve
if (isset($_POST['sendReserve']) && $_POST['sendReserve'] == 1) {
    $query = $dbs->query("SELECT reserve_id, biblio_id, item_code FROM reserve WHERE member_id = '" . $dbs->escape_string($_SESSION['mid']) . "'");
    $items = $query->fetchAll(PDO::FETCH_ASSOC);
    
    $_SESSION['info']['data'] = __('Reservation request sent successfully!');
    $_SESSION['info']['status'] = 'success';
    
    header('Location: index.php?p=member&sec=title_basket&lib=' . urlencode($_GET['lib'] ?? ''));
    exit;
}

// ============================================================
// TAMPILKAN BASKET
// ============================================================

if (isset($_SESSION['info'])) {
    echo '<div class="alert alert-' . $_SESSION['info']['status'] . '">' . $_SESSION['info']['data'] . '</div>';
    unset($_SESSION['info']);
}

// ============================================================
// LOAD DEPENDENCIES SEBELUM KONTEN
// ============================================================
// Pastikan jQuery dimuat SEBELUM script
echo '<script src="' . SWB . 'template/default/assets/js/jquery.min.js"></script>';
echo '<link rel="stylesheet" href="' . SWB . 'js/toastr/toastr.min.css">';
echo '<script src="' . SWB . 'js/toastr/toastr.min.js"></script>';

// Tampilkan konten basket
echo showBasketFromReserve(50);
?>

<!-- ============================================================
SCRIPT: DIJALANKAN SETELAH JQUERY DIMUAT
============================================================ -->
<script>
// Tunggu jQuery dan Toastr benar-benar siap
(function() {
    // Fungsi untuk menunggu jQuery ready
    function waitForJQuery() {
        if (typeof jQuery !== 'undefined') {
            // jQuery sudah tersedia
            jQuery(document).ready(function($) {
                initBasketScripts($);
            });
        } else {
            // jQuery belum tersedia, tunggu 100ms
            setTimeout(waitForJQuery, 100);
        }
    }
    
    // Mulai menunggu jQuery
    waitForJQuery();
    
    // Inisialisasi script basket
    function initBasketScripts($) {
// ============================================================
// HANDLER HAPUS SATU ITEM (DENGAN URL YANG BENAR)
// ============================================================
$('.remove-single').on('click', function() {
    var $btn = $(this);
    var reserveId = $btn.data('reserve-id');
    var biblioId = $btn.data('biblio-id');
    
    if (!confirm('Hapus title ini dari basket?')) return;
    
    // ============================================================
    // URL YANG BENAR: Kirim ke opac_handler via member page
    // ============================================================
    <?php $lib_slug_js = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? ''; ?>
    var url = 'index.php?p=member&sec=title_basket&lib=<?= urlencode($lib_slug_js) ?>';
    
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');
    
    $.ajax({
        url: url,
        type: 'POST',
        data: {
            action: 'remove_single_basket',
            reserve_id: reserveId,
            biblio_id: biblioId
        },
        dataType: 'json',
        success: function(res) {
            if (res.status === 'success') {
                $('#basket-row-' + reserveId).fadeOut(300, function() {
                    $(this).remove();
                    var counter = $('.memberBasketInfo');
                    var text = counter.text();
                    var total = parseInt(text) || 0;
                    var newTotal = total - 1;
                    counter.text(newTotal + ' title(s) on basket');
                    if (newTotal === 0) {
                        location.reload();
                    }
                });
                toastr.success(res.message);
            } else {
                toastr.error(res.message);
                $btn.prop('disabled', false).html('<i class="fa fa-trash"></i>');
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            console.log('Response:', xhr.responseText);
            toastr.error('Gagal menghapus item. Silakan coba lagi.');
            $btn.prop('disabled', false).html('<i class="fa fa-trash"></i>');
        }
    });
});
        // ============================================================
        // CLEAR ALL
        // ============================================================
        $('.clearAll').click(function(evt) {
            evt.preventDefault();
            var anchor = $(this);
            var aHREF = anchor.attr('href');
            var postData = anchor.attr('postdata');
            if (confirm('Clear your title(s) basket?')) {
                $.ajax({
                    type: 'POST',
                    url: aHREF,
                    cache: false,
                    data: postData,
                    async: false,
                    success: function() {
                        alert('Basket data cleared!');
                        window.location.href = aHREF;
                    }
                });
            }
        });

        // ============================================================
        // REMOVE SELECTED
        // ============================================================
        $('.clearOne').click(function(evt) {
            evt.preventDefault();
            var basketForm = $('#memberBasketListForm');
            var basketData = basketForm.serialize() + '&basketRemove=1';
            var basketAction = basketForm.attr('action');
            if (confirm('Remove selected title(s) from basket?')) {
                $.ajax({
                    type: 'POST',
                    url: basketAction,
                    cache: false,
                    data: basketData,
                    async: false,
                    success: function() {
                        alert('Selected basket data removed!');
                        window.location.href = basketAction;
                    }
                });
            }
        });

        // ============================================================
        // RESERVE
        // ============================================================
        $('.reserve').click(function(evt) {
            evt.preventDefault();
            var anchor = $(this);
            var aHREF = anchor.attr('href');
            $('#info').html('<div class="alert alert-info"><?= __('Please wait. your reservation is being sent') ?>...</div>');
            $.ajax({
                type: 'POST',
                url: aHREF,
                cache: false,
                data: 'sendReserve=1',
                async: false,
                success: function() {
                    toastr.success('<?= __('Reservation request sent') ?>');
                    setTimeout(function() {
                        window.location.href = aHREF;
                    }, 3000);
                }
            });
        });
    }
})();
</script>