<script>
document.addEventListener('DOMContentLoaded', function() {
    // NEW: Global variables for bulk selection
    let selectedItems = new Set();
    let currentTransactionItems = [];
    let bulkActionsVisible = false;
    
    // Tab switching functionality
    window.switchTab = function(tab) {
        // Update active tab button
        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('active');
        });
        document.getElementById('tab-' + tab).classList.add('active');
        
        // Update current tab input
        document.getElementById('current-tab').value = tab;
        
        // Show/hide status filter based on tab
        const statusFilter = document.getElementById('status-filter');
        if (tab === 'completed') {
            statusFilter.style.display = 'none';
            document.getElementById('status').value = ''; // Clear status filter for completed tab
        } else {
            statusFilter.style.display = 'block';
        }
        
        // Submit form to refresh data
        document.getElementById('filter-form').submit();
    };
    
    // Reset filters function
    window.resetFilters = function() {
        const currentTab = document.getElementById('current-tab').value;
        // ENHANCED: Preserve show_reservation parameter when resetting filters
        const urlParams = new URLSearchParams(window.location.search);
        const showReservation = urlParams.get('show_reservation');
        
        let resetUrl = `persetujuan_formulir_admin.php?tab=${currentTab}`;
        if (showReservation) {
            resetUrl += `&show_reservation=${encodeURIComponent(showReservation)}`;
        }
        
        window.location.href = resetUrl;
    };
    
    // Show notification function
    function showNotification(message, type = 'success') {
        const notificationContainer = document.getElementById('notification-container');
        const notification = document.getElementById('notification');
        const notificationMessage = document.getElementById('notification-message');
        
        // Set message and style based on type
        notificationMessage.textContent = message;
        
        if (type === 'success') {
            notification.className = 'bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded shadow-md';
        } else if (type === 'error') {
            notification.className = 'bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded shadow-md';
        } else if (type === 'warning') {
            notification.className = 'bg-yellow-100 border border-yellow-400 text-yellow-700 px-4 py-3 rounded shadow-md';
        }
        
        // Show notification
        notificationContainer.style.display = 'block';
        
        // Hide after 3 seconds
        setTimeout(function() {
            notificationContainer.style.display = 'none';
        }, 3000);
    }
    
    // Handle URL params for notifications
    const urlParams = new URLSearchParams(window.location.search);
    const notification = urlParams.get('notification');
    const notificationType = urlParams.get('type');
    
    if (notification) {
        showNotification(notification, notificationType || 'success');
        
        // Remove notification params from URL
        const newUrl = window.location.pathname + window.location.search.replace(/[?&]notification=([^&]*)(&type=([^&]*))?/, '');
        window.history.replaceState({}, document.title, newUrl);
    }
    
    // View transaction details
    const viewDetailButtons = document.querySelectorAll('.view-details');
    const detailsModal = document.getElementById('details-modal');
    const closeModalButtons = document.querySelectorAll('.close-modal');
    
    viewDetailButtons.forEach(button => {
        button.addEventListener('click', function() {
            const transactionId = this.getAttribute('data-transaction-id');
            loadTransactionDetails(transactionId);
        });
    });
    
    closeModalButtons.forEach(button => {
        button.addEventListener('click', function() {
            detailsModal.classList.add('hidden');
            // Reset bulk selection when closing modal
            resetBulkSelection();
        });
    });
    
    // NEW: Bulk selection functions
    function resetBulkSelection() {
        selectedItems.clear();
        currentTransactionItems = [];
        updateBulkActionsVisibility();
        updateSelectedCount();
        
        // Uncheck all checkboxes
        document.querySelectorAll('.item-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
    }
    
    function updateBulkActionsVisibility() {
        const bulkActionsSection = document.getElementById('bulk-actions-section');
        const hasSelectableItems = currentTransactionItems.some(item => item.bulk_selection && item.bulk_selection.is_selectable);
        
        if (hasSelectableItems && selectedItems.size > 0) {
            bulkActionsSection.classList.remove('hidden');
            bulkActionsVisible = true;
        } else {
            bulkActionsSection.classList.add('hidden');
            bulkActionsVisible = false;
        }
    }
    
    function updateSelectedCount() {
        const selectedCountElement = document.getElementById('selected-count');
        if (selectedCountElement) {
            selectedCountElement.textContent = `${selectedItems.size} item dipilih`;
        }
    }
    
    function selectAllAvailableItems() {
        selectedItems.clear();
        
        // Select only available items (status 'Tersedia' and not processed)
        currentTransactionItems.forEach(item => {
            if (item.bulk_selection && item.bulk_selection.is_selectable) {
                selectedItems.add(item.id);
                const checkbox = document.querySelector(`input[data-item-id="${item.id}"]`);
                if (checkbox) {
                    checkbox.checked = true;
                }
            }
        });
        
        updateBulkActionsVisibility();
        updateSelectedCount();
    }
    
    function clearSelection() {
        selectedItems.clear();
        document.querySelectorAll('.item-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
        updateBulkActionsVisibility();
        updateSelectedCount();
    }
    
    // NEW: Bulk action event listeners
    document.addEventListener('click', function(e) {
        if (e.target.id === 'select-all-available') {
            selectAllAvailableItems();
        } else if (e.target.id === 'clear-selection') {
            clearSelection();
        } else if (e.target.id === 'bulk-approve') {
            showBulkActionModal('approve');
        } else if (e.target.id === 'bulk-reject') {
            showBulkActionModal('reject');
        } else if (e.target.id === 'bulk-onprocess') {
            showBulkActionModal('onprocess');
        }
    });
    
    // NEW: Handle item checkbox changes
    document.addEventListener('change', function(e) {
        if (e.target.classList.contains('item-checkbox')) {
            const itemId = parseInt(e.target.getAttribute('data-item-id'));
            
            if (e.target.checked) {
                selectedItems.add(itemId);
            } else {
                selectedItems.delete(itemId);
            }
            
            updateBulkActionsVisibility();
            updateSelectedCount();
        }
    });
    
    // UPDATED: Calculate duration from transaction and return dates
    function calculateDuration(tanggal_transaksi, tanggal_pengembalian) {
        const startDate = new Date(tanggal_transaksi);
        const endDate = new Date(tanggal_pengembalian);
        const diffTime = Math.abs(endDate - startDate);
        const diffHours = diffTime / (1000 * 60 * 60);
        
        if (diffHours < 24) {
            return Math.round(diffHours * 10) / 10 + ' jam';
        } else {
            const days = Math.round(diffHours / 24 * 10) / 10;
            return days + ' hari';
        }
    }
    
    // ENHANCED: Function to check if item is currently overdue
    function isCurrentlyOverdue(tanggal_pengembalian, dikembalikan) {
        if (dikembalikan) return false;
        
        const dueDate = new Date(tanggal_pengembalian);
        const toleranceTime = new Date(dueDate.getTime() + (15 * 60 * 1000)); // Add 15 minutes
        const currentTime = new Date();
        
        return currentTime > toleranceTime;
    }
    
    // ENHANCED: Format overdue duration for display
    function formatOverdueDuration(hours) {
        if (hours < 24) {
            return `${Math.round(hours)} jam`;
        } else {
            const days = Math.floor(hours / 24);
            const remainingHours = Math.round(hours % 24);
            return `${days} hari ${remainingHours > 0 ? remainingHours + ' jam' : ''}`;
        }
    }
    
    // Load transaction details
    function loadTransactionDetails(transactionId) {
        // Reset bulk selection when loading new transaction
        resetBulkSelection();
        
        // Show loading state
        const loadingHtml = `
            <div class="flex items-center justify-center py-8">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
                <span class="ml-2 text-gray-600">Memuat detail transaksi...</span>
            </div>
        `;
        document.getElementById('transaction-details').innerHTML = loadingHtml;
        document.getElementById('transaction-items').innerHTML = '';
        
        // Fetch transaction details
        fetch(`get_transaction_details_admin.php?id=${transactionId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // Store current transaction items for bulk selection
                    currentTransactionItems = data.items || [];
                    
                    // Show reservation number in modal header
                    document.getElementById('reservation-number-display').textContent = data.transaction.reservation_number || 'No Reservation Number';
                    
                    // UPDATED: Calculate duration for display
                    const durationText = calculateDuration(data.transaction.tanggal_transaksi, data.transaction.tanggal_pengembalian);
                    
                    // ENHANCED: Add overdue warning if applicable
                    const hasOverdueItems = data.metadata.currently_overdue > 0;
                    const overdueWarning = hasOverdueItems ? 
                        `<div class="col-span-2 p-3 bg-red-50 border border-red-200 rounded-lg">
                            <div class="flex items-center">
                                <i class="fas fa-exclamation-triangle text-red-500 mr-2"></i>
                                <span class="text-red-700 font-medium">
                                    Peringatan: ${data.metadata.currently_overdue} item sedang terlambat dikembalikan!
                                </span>
                            </div>
                        </div>` : '';
                    
                    // NEW: Add bulk selection info if applicable
                    const bulkSelectionInfo = data.summary.bulk_selection.has_bulk_actions_available ? 
                        `<div class="col-span-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                            <div class="flex items-center">
                                <i class="fas fa-tasks text-blue-500 mr-2"></i>
                                <span class="text-blue-700 font-medium">
                                    ${data.summary.bulk_selection.total_selectable} item tersedia untuk aksi massal
                                    ${data.summary.bulk_selection.unavailable_for_approval > 0 ? 
                                        `(${data.summary.bulk_selection.unavailable_for_approval} item tidak tersedia)` : ''}
                                </span>
                            </div>
                        </div>` : '';
                    
                    // Populate transaction details
                    document.getElementById('transaction-details').innerHTML = `
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            ${overdueWarning}
                            ${bulkSelectionInfo}
                            <div>
                                <p class="text-sm text-gray-500">ID Transaksi</p>
                                <p class="font-medium">${data.transaction.id}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">No. Reservasi</p>
                                <p class="font-medium">${data.transaction.reservation_number || '-'}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Peminjam</p>
                                <p class="font-medium">${data.transaction.borrower_name} (${data.transaction.lokasi_posisi})</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Tanggal Transaksi</p>
                                <p class="font-medium">${new Date(data.transaction.tanggal_transaksi).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Tanggal Pengembalian</p>
                                <p class="font-medium">${new Date(data.transaction.tanggal_pengembalian).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Durasi Peminjaman</p>
                                <p class="font-medium">${durationText}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Status</p>
                                <p class="font-medium">${data.transaction.status}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Status Peminjaman</p>
                                <p class="font-medium">${data.transaction.status_peminjaman}</p>
                            </div>
                            ${data.transaction.keterangan ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Keterangan</p>
                                <p class="font-medium">${data.transaction.keterangan}</p>
                            </div>
                            ` : ''}
                            ${data.transaction.catatan_tolak ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Catatan Tolak</p>
                                <p class="font-medium text-red-600">${data.transaction.catatan_tolak}</p>
                            </div>
                            ` : ''}
                            ${data.transaction.catatan_proses ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Catatan Proses</p>
                                <p class="font-medium text-blue-600">${data.transaction.catatan_proses}</p>
                            </div>
                            ` : ''}
                            ${data.transaction.catatan_pengembalian ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Catatan Pengembalian</p>
                                <p class="font-medium text-green-600">${data.transaction.catatan_pengembalian}</p>
                            </div>
                            ` : ''}
                        </div>
                    `;
                    
                    // Populate transaction items
                    let itemsHtml = '';
                    
                    if (data.items && data.items.length > 0) {
                        data.items.forEach(item => {
                            let statusBadge = '';
                            let actionButtons = '';
                            let statusWaktoBadge = '';
                            let overdueIndicator = '';
                            let checkboxHtml = '';
                            
                            // ENHANCED: Check if item is currently overdue
                            const currentlyOverdue = isCurrentlyOverdue(data.transaction.tanggal_pengembalian, item.dikembalikan);
                            if (currentlyOverdue) {
                                overdueIndicator = `
                                    <div class="mb-2 p-2 bg-red-50 border border-red-200 rounded">
                                        <div class="flex items-center text-red-700">
                                            <i class="fas fa-clock text-red-500 mr-2 animate-pulse"></i>
                                            <span class="text-sm font-medium">Item ini sedang terlambat dikembalikan!</span>
                                        </div>
                                    </div>
                                `;
                            }
                            
                            // NEW: Add checkbox for bulk selection (only for selectable items)
                            if (item.bulk_selection && item.bulk_selection.is_selectable) {
                                checkboxHtml = `
                                    <div class="checkbox-container mr-3">
                                        <input type="checkbox" class="item-checkbox" 
                                               data-item-id="${item.id}" 
                                               title="Pilih item untuk aksi massal">
                                    </div>
                                `;
                            } else if (item.quantity_approved === null) {
                                // Show disabled checkbox with tooltip for non-selectable items
                                checkboxHtml = `
                                    <div class="checkbox-container mr-3" title="${item.bulk_selection ? item.bulk_selection.selection_reason : 'Item tidak dapat dipilih'}">
                                        <input type="checkbox" class="item-checkbox" disabled>
                                    </div>
                                `;
                            }
                            
                            // Determine status badge
                            if (item.quantity_approved === null) {
                                statusBadge = '<span class="px-2 py-1 rounded-full text-xs font-semibold bg-yellow-100 text-yellow-800">Menunggu Persetujuan</span>';
                                
                                // For items waiting approval, show approve/reject/onprocess buttons
                                actionButtons = `
                                    <button type="button" class="px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 action-button mr-1"
                                            data-action="approve" data-item-id="${item.id}" data-transaction-id="${data.transaction.id}">
                                        <i class="fas fa-check mr-1"></i> Disetujui
                                    </button>
                                    <button type="button" class="px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 action-button mr-1"
                                            data-action="reject" data-item-id="${item.id}" data-transaction-id="${data.transaction.id}">
                                        <i class="fas fa-times mr-1"></i> Ditolak
                                    </button>
                                    <button type="button" class="px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 action-button"
                                            data-action="onprocess" data-item-id="${item.id}" data-transaction-id="${data.transaction.id}">
                                        <i class="fas fa-clock mr-1"></i> OnProcessing
                                    </button>
                                `;
                            } else if (item.quantity_approved > 0) {
                                if (item.dikembalikan) {
                                    statusBadge = `<span class="px-2 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800">Dikembalikan (${item.kondisi_kembali})</span>`;
                                    
                                    // Add status waktu badge for returned items
                                    if (item.status_waktu === 'tepat') {
                                        statusWaktoBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-green-100 text-green-800">Tepat Waktu</span>';
                                    } else if (item.status_waktu === 'overdue') {
                                        statusWaktoBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-red-100 text-red-800">Terlambat</span>';
                                    }
                                } else {
                                    statusBadge = '<span class="px-2 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-800">Disetujui</span>';
                                    
                                    // Check if item is overdue but not yet returned
                                    if (item.status_waktu === 'overdue' || currentlyOverdue) {
                                        statusWaktoBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-red-100 text-red-800 animate-pulse">⚠️ Terlambat</span>';
                                    }
                                    
                                    // For approved but not returned items, show return button
                                    const returnButtonClass = currentlyOverdue ? 
                                        'px-3 py-1 bg-red-500 text-white rounded hover:bg-red-600 action-button animate-pulse' :
                                        'px-3 py-1 bg-green-500 text-white rounded hover:bg-green-600 action-button';
                                    
                                    actionButtons = `
                                        <button type="button" class="${returnButtonClass}"
                                                data-action="return" data-item-id="${item.id}" data-transaction-id="${data.transaction.id}">
                                            <i class="fas fa-undo mr-1"></i> ${currentlyOverdue ? 'Kembalikan (Terlambat!)' : 'Dikembalikan'}
                                        </button>
                                    `;
                                }
                            } else if (item.quantity_approved === 0) {
                                statusBadge = '<span class="px-2 py-1 rounded-full text-xs font-semibold bg-red-100 text-red-800">Ditolak</span>';
                            }
                            
                            // Add item status badge
                            let itemStatusBadge = '';
                            switch (item.item_status) {
                                case 'Tersedia':
                                    itemStatusBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-green-100 text-green-800">Tersedia</span>';
                                    break;
                                case 'Dipinjam':
                                    itemStatusBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-blue-100 text-blue-800">Dipinjam</span>';
                                    break;
                                case 'Rusak':
                                    itemStatusBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-red-100 text-red-800">Rusak</span>';
                                    break;
                                case 'Expired':
                                    itemStatusBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-gray-100 text-gray-800">Expired</span>';
                                    break;
                                case 'Renew':
                                    itemStatusBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-purple-100 text-purple-800">Diperbaharui</span>';
                                    break;
                                case 'Hilang':
                                    itemStatusBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-orange-100 text-orange-800">Hilang</span>';
                                    break;
                                default:
                                    itemStatusBadge = '<span class="px-2 py-1 ml-2 rounded-full text-xs font-semibold bg-gray-100 text-gray-800">Unknown</span>';
                            }
                            
                            // Set lokasi_tujuan based on borrower location if not specified
                            const lokasi_tujuan = item.lokasi_tujuan || data.transaction.lokasi_posisi;
                            
                            // ENHANCED: Container class for overdue items and selection state
                            let containerClass = currentlyOverdue ? 'bg-red-50 border-2 border-red-200' : 'bg-gray-50';
                            if (item.bulk_selection && !item.bulk_selection.is_selectable && item.quantity_approved === null) {
                                containerClass += ' item-disabled';
                            }
                            
                            itemsHtml += `
                                <div class="${containerClass} p-4 rounded-lg">
                                    ${overdueIndicator}
                                    <div class="flex items-start mb-2">
                                        ${checkboxHtml}
                                        <div class="flex-1">
                                            <div class="flex flex-wrap justify-between items-start mb-2">
                                                <div class="w-full md:w-auto mb-2 md:mb-0">
                                                    <h5 class="font-semibold">${item.keterangan || 'Item #' + item.id}</h5>
                                                    <p class="text-sm text-gray-600">
                                                        Kode: ${item.kode_barang}
                                                        ${itemStatusBadge}
                                                    </p>
                                                    <p class="text-sm text-gray-600">
                                                        ${item.color_code ? `Color: ${item.color_code} (${item.color_description})` : ''}
                                                        ${item.component_name ? ` - Component: ${item.component_name}` : ''}
                                                    </p>
                                                    ${item.nama_buyer ? `<p class="text-xs text-gray-500">Buyer: ${item.nama_buyer}</p>` : ''}
                                                    ${item.bulk_selection && !item.bulk_selection.is_selectable && item.quantity_approved === null ? 
                                                        `<p class="text-xs text-orange-600 mt-1"><i class="fas fa-info-circle mr-1"></i>${item.bulk_selection.selection_reason}</p>` : ''}
                                                </div>
                                                <div>
                                                    ${statusBadge}
                                                    ${statusWaktoBadge}
                                                </div>
                                            </div>
                                            
                                            <div class="grid grid-cols-1 md:grid-cols-3 gap-2 mb-3">
                                                <div>
                                                    <p class="text-xs text-gray-500">Lokasi Asal</p>
                                                    <p class="text-sm">${item.lokasi_asal || 'Color Room'}</p>
                                                </div>
                                                <div>
                                                    <p class="text-xs text-gray-500">Lokasi Tujuan</p>
                                                    <p class="text-sm">${lokasi_tujuan}</p>
                                                </div>
                                                <div>
                                                    <p class="text-xs text-gray-500">Jumlah</p>
                                                    <p class="text-sm">${item.quantity_requested}</p>
                                                </div>
                                            </div>
                                            
                                            ${item.catatan ? `
                                            <div class="mb-3">
                                                <p class="text-xs text-gray-500">Catatan</p>
                                                <p class="text-sm">${item.catatan}</p>
                                            </div>
                                            ` : ''}
                                            
                                            ${item.tanggal_kembali ? `
                                            <div class="mb-3">
                                                <p class="text-xs text-gray-500">Tanggal Kembali</p>
                                                <p class="text-sm">${new Date(item.tanggal_kembali).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</p>
                                            </div>
                                            ` : ''}
                                            
                                            <div class="flex flex-wrap justify-end space-x-2">
                                                ${actionButtons}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                    } else {
                        itemsHtml = '<p class="text-gray-500">Tidak ada item dalam transaksi ini.</p>';
                    }
                    
                    document.getElementById('transaction-items').innerHTML = itemsHtml;
                    
                    // Add event listeners to action buttons
                    const actionButtons = document.querySelectorAll('.action-button');
                    actionButtons.forEach(button => {
                        button.addEventListener('click', function() {
                            const action = this.getAttribute('data-action');
                            const itemId = this.getAttribute('data-item-id');
                            const transactionId = this.getAttribute('data-transaction-id');
                            
                            showActionModal(action, itemId, transactionId);
                        });
                    });
                    
                    // Update bulk actions visibility
                    updateBulkActionsVisibility();
                    
                    // Show the modal
                    detailsModal.classList.remove('hidden');
                    
                    // ENHANCED: Show notification if transaction has overdue items
                    if (hasOverdueItems) {
                        showNotification(`Perhatian: Transaksi ini memiliki ${data.metadata.currently_overdue} item yang terlambat dikembalikan!`, 'warning');
                    }
                    
                    // NEW: Show notification about bulk selection if available
                    if (data.summary.bulk_selection.has_bulk_actions_available) {
                        showNotification(`${data.summary.bulk_selection.total_selectable} item tersedia untuk aksi massal`, 'info');
                    }
                } else {
                    showNotification('Gagal memuat detail transaksi', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Terjadi kesalahan saat memuat detail', 'error');
            });
    }
    
    // Action modal handling
    const actionModal = document.getElementById('action-modal');
    const closeActionModalButtons = document.querySelectorAll('.close-action-modal');
    const actionForm = document.getElementById('action-form');
    
    closeActionModalButtons.forEach(button => {
        button.addEventListener('click', function() {
            actionModal.classList.add('hidden');
        });
    });
    
    function showActionModal(action, itemId, transactionId) {
        const actionItemId = document.getElementById('action-item-id');
        const actionTransactionId = document.getElementById('action-transaction-id');
        const actionType = document.getElementById('action-type');
        const actionModalTitle = document.getElementById('action-modal-title');
        const noteContainer = document.getElementById('note-container');
        const conditionContainer = document.getElementById('condition-container');
        const submitButton = document.getElementById('submit-action');
        
        actionItemId.value = itemId;
        actionTransactionId.value = transactionId;
        actionType.value = action;
        
        // Reset form
        actionForm.reset();
        
        // Configure modal based on action
        switch (action) {
            case 'approve':
                actionModalTitle.textContent = 'Menyetujui Peminjaman';
                noteContainer.classList.add('hidden');
                conditionContainer.classList.add('hidden');
                submitButton.textContent = 'Setujui';
                submitButton.className = 'px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600';
                break;
                
            case 'reject':
                actionModalTitle.textContent = 'Menolak Peminjaman';
                noteContainer.classList.remove('hidden');
                conditionContainer.classList.add('hidden');
                submitButton.textContent = 'Tolak';
                submitButton.className = 'px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600';
                break;
                
            case 'onprocess':
                actionModalTitle.textContent = 'Memproses Peminjaman';
                noteContainer.classList.add('hidden');
                conditionContainer.classList.add('hidden');
                submitButton.textContent = 'Proses';
                submitButton.className = 'px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600';
                break;
                
            case 'return':
                actionModalTitle.textContent = 'Mengembalikan Item';
                noteContainer.classList.remove('hidden');
                conditionContainer.classList.remove('hidden');
                submitButton.textContent = 'Kembalikan';
                submitButton.className = 'px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600';
                break;
        }
        
        // Show the modal
        actionModal.classList.remove('hidden');
    }
    
    // NEW: Bulk action modal handling
    const bulkActionModal = document.getElementById('bulk-action-modal');
    const closeBulkActionModalButtons = document.querySelectorAll('.close-bulk-action-modal');
    const bulkActionForm = document.getElementById('bulk-action-form');
    
    closeBulkActionModalButtons.forEach(button => {
        button.addEventListener('click', function() {
            bulkActionModal.classList.add('hidden');
        });
    });
    
    function showBulkActionModal(operation) {
        if (selectedItems.size === 0) {
            showNotification('Pilih minimal satu item terlebih dahulu', 'warning');
            return;
        }
        
        const bulkActionModalTitle = document.getElementById('bulk-action-modal-title');
        const bulkActionMessage = document.getElementById('bulk-action-message');
        const bulkSelectedItems = document.getElementById('bulk-selected-items');
        const bulkNoteContainer = document.getElementById('bulk-note-container');
        const submitBulkAction = document.getElementById('submit-bulk-action');
        
        // Set operation
        document.getElementById('bulk-action-operation').value = operation;
        document.getElementById('bulk-transaction-id').value = currentTransactionItems.length > 0 ? 
            currentTransactionItems[0].transaction_id || '' : '';
        document.getElementById('bulk-item-ids').value = Array.from(selectedItems).join(',');
        
        // Reset form
        bulkActionForm.reset();
        document.getElementById('bulk-action-type').value = 'bulk_action';
        document.getElementById('bulk-action-operation').value = operation;
        document.getElementById('bulk-transaction-id').value = currentTransactionItems.length > 0 ? 
            currentTransactionItems[0].transaction_id || '' : '';
        document.getElementById('bulk-item-ids').value = Array.from(selectedItems).join(',');
        
        // Configure modal based on operation
        let actionText = '';
        let buttonClass = '';
        let showNote = false;
        
        switch (operation) {
            case 'approve':
                actionText = 'Menyetujui';
                buttonClass = 'px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600';
                showNote = false;
                break;
            case 'reject':
                actionText = 'Menolak';
                buttonClass = 'px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600';
                showNote = true;
                break;
            case 'onprocess':
                actionText = 'Memproses';
                buttonClass = 'px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600';
                showNote = false;
                break;
        }
        
        bulkActionModalTitle.textContent = `${actionText} Item Terpilih`;
        bulkActionMessage.textContent = `Anda akan ${actionText.toLowerCase()} ${selectedItems.size} item yang dipilih. Aksi ini tidak dapat dibatalkan.`;
        
        // Show/hide note container
        if (showNote) {
            bulkNoteContainer.classList.remove('hidden');
        } else {
            bulkNoteContainer.classList.add('hidden');
        }
        
        // Set button style
        submitBulkAction.textContent = `${actionText} ${selectedItems.size} Item`;
        submitBulkAction.className = buttonClass;
        
        // Show selected items
        let selectedItemsHtml = '<div class="space-y-2">';
        selectedItems.forEach(itemId => {
            const item = currentTransactionItems.find(i => i.id === itemId);
            if (item) {
                selectedItemsHtml += `
                    <div class="flex items-center p-2 bg-white rounded border">
                        <i class="fas fa-check-circle text-green-500 mr-2"></i>
                        <div class="flex-1">
                            <span class="font-medium">${item.kode_barang}</span>
                            <span class="text-sm text-gray-600 ml-2">${item.keterangan || 'Item #' + item.id}</span>
                        </div>
                    </div>
                `;
            }
        });
        selectedItemsHtml += '</div>';
        
        bulkSelectedItems.innerHTML = selectedItemsHtml;
        
        // Show the modal
        bulkActionModal.classList.remove('hidden');
    }
    
    // Handle form submission for single actions
    actionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(actionForm);
        const itemId = document.getElementById('action-item-id').value;
        const transactionId = document.getElementById('action-transaction-id').value;
        const action = document.getElementById('action-type').value;
        
        // Show loading state on submit button
        const submitButton = document.getElementById('submit-action');
        const originalText = submitButton.textContent;
        submitButton.textContent = 'Memproses...';
        submitButton.disabled = true;
        
        // Send AJAX request
        fetch('persetujuan_formulir_admin.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                // Reset button state
                submitButton.textContent = originalText;
                submitButton.disabled = false;
                
                if (data.status === 'success') {
                    // Hide action modal
                    actionModal.classList.add('hidden');
                    
                    // Show success notification
                    showNotification(data.message, 'success');
                    
                    // Refresh the transaction details in the modal
                    refreshTransactionDetails(transactionId, itemId, action);
                    
                    // If action was return and all items returned, refresh page after delay
                    if (action === 'return') {
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000);
                    }
                } else {
                    showNotification(data.message, 'error');
                }
            })
            .catch(error => {
                // Reset button state
                submitButton.textContent = originalText;
                submitButton.disabled = false;
                
                console.error('Error:', error);
                showNotification('Terjadi kesalahan saat memproses aksi', 'error');
            });
    });
    
    // NEW: Handle form submission for bulk actions
    bulkActionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(bulkActionForm);
        const operation = document.getElementById('bulk-action-operation').value;
        const transactionId = document.getElementById('bulk-transaction-id').value;
        
        // Show loading state on submit button
        const submitButton = document.getElementById('submit-bulk-action');
        const originalText = submitButton.textContent;
        submitButton.textContent = 'Memproses...';
        submitButton.disabled = true;
        
        // Send AJAX request
        fetch('persetujuan_formulir_admin.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                // Reset button state
                submitButton.textContent = originalText;
                submitButton.disabled = false;
                
                if (data.status === 'success') {
                    // Hide bulk action modal
                    bulkActionModal.classList.add('hidden');
                    
                    // Show success notification
                    showNotification(data.message, 'success');
                    
                    // Clear selection
                    clearSelection();
                    
                    // Refresh the transaction details in the modal
                    refreshTransactionDetails(transactionId, null, `bulk_${operation}`);
                    
                } else {
                    showNotification(data.message, 'error');
                    
                    // Show details about failed items if available
                    if (data.failed_items && data.failed_items.length > 0) {
                        console.log('Failed items:', data.failed_items);
                    }
                    if (data.invalid_items && data.invalid_items.length > 0) {
                        console.log('Invalid items:', data.invalid_items);
                    }
                }
            })
            .catch(error => {
                // Reset button state
                submitButton.textContent = originalText;
                submitButton.disabled = false;
                
                console.error('Error:', error);
                showNotification('Terjadi kesalahan saat memproses aksi massal', 'error');
            });
    });
    
    // Function to refresh transaction details without page reload
    function refreshTransactionDetails(transactionId, updatedItemId, lastAction) {
        // Fetch the updated transaction details
        fetch(`get_transaction_details_admin.php?id=${transactionId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // Store updated transaction items
                    currentTransactionItems = data.items || [];
                    
                    // Clear bulk selection since items may have changed
                    resetBulkSelection();
                    
                    // Update reservation number display
                    document.getElementById('reservation-number-display').textContent = data.transaction.reservation_number || 'No Reservation Number';
                    
                    // UPDATED: Calculate duration for display
                    const durationText = calculateDuration(data.transaction.tanggal_transaksi, data.transaction.tanggal_pengembalian);
                    
                    // ENHANCED: Add overdue warning if applicable
                    const hasOverdueItems = data.metadata.currently_overdue > 0;
                    const overdueWarning = hasOverdueItems ? 
                        `<div class="col-span-2 p-3 bg-red-50 border border-red-200 rounded-lg">
                            <div class="flex items-center">
                                <i class="fas fa-exclamation-triangle text-red-500 mr-2"></i>
                                <span class="text-red-700 font-medium">
                                    Peringatan: ${data.metadata.currently_overdue} item sedang terlambat dikembalikan!
                                </span>
                            </div>
                        </div>` : '';
                    
                    // NEW: Add bulk selection info if applicable
                    const bulkSelectionInfo = data.summary.bulk_selection.has_bulk_actions_available ? 
                        `<div class="col-span-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                            <div class="flex items-center">
                                <i class="fas fa-tasks text-blue-500 mr-2"></i>
                                <span class="text-blue-700 font-medium">
                                    ${data.summary.bulk_selection.total_selectable} item tersedia untuk aksi massal
                                    ${data.summary.bulk_selection.unavailable_for_approval > 0 ? 
                                        `(${data.summary.bulk_selection.unavailable_for_approval} item tidak tersedia)` : ''}
                                </span>
                            </div>
                        </div>` : '';
                    
                    // Update transaction details (same as in loadTransactionDetails but simplified)
                    document.getElementById('transaction-details').innerHTML = `
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            ${overdueWarning}
                            ${bulkSelectionInfo}
                            <div>
                                <p class="text-sm text-gray-500">ID Transaksi</p>
                                <p class="font-medium">${data.transaction.id}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">No. Reservasi</p>
                                <p class="font-medium">${data.transaction.reservation_number || '-'}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Peminjam</p>
                                <p class="font-medium">${data.transaction.borrower_name} (${data.transaction.lokasi_posisi})</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Tanggal Transaksi</p>
                                <p class="font-medium">${new Date(data.transaction.tanggal_transaksi).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Tanggal Pengembalian</p>
                                <p class="font-medium">${new Date(data.transaction.tanggal_pengembalian).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Durasi Peminjaman</p>
                                <p class="font-medium">${durationText}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Status</p>
                                <p class="font-medium">${data.transaction.status}</p>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">Status Peminjaman</p>
                                <p class="font-medium">${data.transaction.status_peminjaman}</p>
                            </div>
                            ${data.transaction.keterangan ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Keterangan</p>
                                <p class="font-medium">${data.transaction.keterangan}</p>
                            </div>
                            ` : ''}
                            ${data.transaction.catatan_tolak ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Catatan Tolak</p>
                                <p class="font-medium text-red-600">${data.transaction.catatan_tolak}</p>
                            </div>
                            ` : ''}
                            ${data.transaction.catatan_proses ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Catatan Proses</p>
                                <p class="font-medium text-blue-600">${data.transaction.catatan_proses}</p>
                            </div>
                            ` : ''}
                            ${data.transaction.catatan_pengembalian ? `
                            <div class="col-span-2">
                                <p class="text-sm text-gray-500">Catatan Pengembalian</p>
                                <p class="font-medium text-green-600">${data.transaction.catatan_pengembalian}</p>
                            </div>
                            ` : ''}
                        </div>
                    `;
                    
                    // Re-render transaction items (reuse logic from loadTransactionDetails)
                    // [Previous item rendering logic would go here - abbreviated for length]
                    
                    // Update the status in the transaction list without page reload
                    const transactionRow = document.querySelector(`tr[data-transaction-id="${transactionId}"]`);
                    if (transactionRow) {
                        // Update status cell (6th column for process tab, 7th column for completed tab)
                        const statusIndex = document.getElementById('current-tab').value === 'completed' ? 6 : 5;
                        const statusCell = transactionRow.querySelector(`td:nth-child(${statusIndex+1}) span`);
                        if (statusCell) {
                            statusCell.textContent = data.transaction.status;
                            // Update status class based on new status
                            statusCell.className = "px-2 py-1 rounded-full text-xs font-semibold " + 
                                (data.transaction.status === 'Disetujui' ? 'bg-green-100 text-green-800' : 
                                 data.transaction.status === 'Ditolak' ? 'bg-red-100 text-red-800' : 
                                 data.transaction.status === 'OnProccesing' ? 'bg-blue-100 text-blue-800' : 
                                 'bg-yellow-100 text-yellow-800');
                        }
                        
                        // Update borrowing status cell (7th column for process tab, 8th column for completed tab)
                        const borrowingStatusIndex = document.getElementById('current-tab').value === 'completed' ? 7 : 6;
                        const borrowingStatusCell = transactionRow.querySelector(`td:nth-child(${borrowingStatusIndex+1}) span`);
                        if (borrowingStatusCell) {
                            borrowingStatusCell.textContent = data.transaction.status_peminjaman;
                            // Update borrowing status class based on new status
                            borrowingStatusCell.className = "px-2 py-1 rounded-full text-xs font-semibold " + 
                                (data.transaction.status_peminjaman === 'Dikembalikan' ? 'bg-green-100 text-green-800' : 
                                 data.transaction.status_peminjaman === 'Dipinjam' ? 'bg-blue-100 text-blue-800' : 
                                 'bg-gray-100 text-gray-800');
                        }
                    }
                    
                    // Reload the transaction items properly
                    loadTransactionDetails(transactionId);
                    
                } else {
                    showNotification('Gagal memuat detail transaksi', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('Terjadi kesalahan saat memuat detail', 'error');
            });
    }
});
</script>