<script>
document.addEventListener('DOMContentLoaded', function() {
    // NEW: Bulk action variables
    let selectedItems = new Set();
    let currentTransactionId = null;
    let availableItems = [];
    let allAvailableItemIds = []; // FIXED: Store all available item IDs
    
    // 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_it.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';
        } else if (type === 'partial') {
            notification.className = 'bg-orange-100 border border-orange-400 text-orange-700 px-4 py-3 rounded shadow-md';
        }
        
        // Show notification
        notificationContainer.style.display = 'block';
        
        // Hide after 4 seconds for bulk operations
        setTimeout(function() {
            notificationContainer.style.display = 'none';
        }, 4000);
    }
    
    // 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();
        });
    });
    
    // FIXED: Bulk selection functions
    function resetBulkSelection() {
        selectedItems.clear();
        availableItems = [];
        allAvailableItemIds = []; // FIXED: Reset all available IDs
        updateBulkActionBar();
        updateSelectAllCheckbox();
        
        // Reset all item checkboxes
        document.querySelectorAll('.item-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
        
        // Remove checked styling from item rows
        document.querySelectorAll('.item-row.checked').forEach(row => {
            row.classList.remove('checked');
        });
    }
    
    function updateBulkActionBar() {
        const bulkBar = document.getElementById('bulk-action-bar');
        const selectedCount = document.getElementById('selected-count');
        
        if (selectedItems.size > 0) {
            bulkBar.classList.add('show');
            selectedCount.textContent = `${selectedItems.size} item dipilih`;
        } else {
            bulkBar.classList.remove('show');
            selectedCount.textContent = '0 item dipilih';
        }
    }
    
    function updateSelectAllCheckbox() {
        const selectAllCheckbox = document.getElementById('select-all-items');
        if (!selectAllCheckbox) return;
        
        const availableCount = allAvailableItemIds.length; // FIXED: Use allAvailableItemIds
        if (availableCount === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
            return;
        }
        
        const selectedAvailableCount = allAvailableItemIds.filter(itemId => selectedItems.has(itemId)).length;
        
        if (selectedAvailableCount === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
        } else if (selectedAvailableCount === availableCount) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = true;
        }
    }
    
    // FIXED: Handle select all checkbox
    document.addEventListener('change', function(e) {
        if (e.target && e.target.id === 'select-all-items') {
            const isChecked = e.target.checked;
            
            // Clear previous selection
            selectedItems.clear();
            
            // FIXED: Use allAvailableItemIds for select all
            allAvailableItemIds.forEach(itemId => {
                const checkbox = document.querySelector(`.item-checkbox[data-item-id="${itemId}"]`);
                const row = checkbox?.closest('.item-row');
                
                if (checkbox && !checkbox.disabled) {
                    checkbox.checked = isChecked;
                    
                    if (isChecked) {
                        selectedItems.add(itemId);
                        row?.classList.add('checked');
                    } else {
                        row?.classList.remove('checked');
                    }
                }
            });
            
            updateBulkActionBar();
            updateSelectAllCheckbox();
        }
    });
    
    // FIXED: Handle individual item checkbox changes
    document.addEventListener('change', function(e) {
        if (e.target && e.target.classList.contains('item-checkbox') && e.target.id !== 'select-all-items') {
            const itemId = parseInt(e.target.getAttribute('data-item-id'));
            const row = e.target.closest('.item-row');
            
            if (e.target.checked) {
                selectedItems.add(itemId);
                row?.classList.add('checked');
            } else {
                selectedItems.delete(itemId);
                row?.classList.remove('checked');
            }
            
            updateBulkActionBar();
            updateSelectAllCheckbox();
        }
    });
    
    // NEW: Handle bulk action buttons
    document.addEventListener('click', function(e) {
        if (e.target && (e.target.classList.contains('bulk-action-button') || e.target.parentElement?.classList.contains('bulk-action-button'))) {
            const button = e.target.classList.contains('bulk-action-button') ? e.target : e.target.parentElement;
            const action = button.getAttribute('data-bulk-action');
            
            if (selectedItems.size === 0) {
                showNotification('Silakan pilih item terlebih dahulu', 'warning');
                return;
            }
            
            showBulkActionModal(action, Array.from(selectedItems), currentTransactionId);
        }
    });
    
    function showBulkActionModal(action, itemIds, 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 bulkSummary = document.getElementById('bulk-summary');
        const bulkSummaryText = document.getElementById('bulk-summary-text');
        const submitButton = document.getElementById('submit-action');
        const bulkActionFlag = document.getElementById('bulk-action-flag');
        const bulkItemIds = document.getElementById('bulk-item-ids');
        
        actionItemId.value = '';
        actionTransactionId.value = transactionId;
        actionType.value = action;
        bulkActionFlag.value = 'true';
        bulkItemIds.value = itemIds.join(',');
        
        // Reset form values but keep the action settings
        document.getElementById('action-note').value = '';
        
        // Show bulk summary
        bulkSummary.classList.remove('hidden');
        
        // Configure modal based on action
        switch (action) {
            case 'approve':
                actionModalTitle.innerHTML = '<i class="fas fa-laptop-code text-purple-600 mr-2"></i>Menyetujui Item Massal - IT Support';
                noteContainer.classList.add('hidden');
                conditionContainer.classList.add('hidden');
                submitButton.textContent = 'Setujui Semua';
                submitButton.className = 'px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600';
                bulkSummaryText.textContent = `Anda akan menyetujui ${itemIds.length} item sekaligus. Item yang sudah dipinjam akan dilewati.`;
                break;
                
            case 'reject':
                actionModalTitle.innerHTML = '<i class="fas fa-laptop-code text-purple-600 mr-2"></i>Menolak Item Massal - IT Support';
                noteContainer.classList.remove('hidden');
                conditionContainer.classList.add('hidden');
                submitButton.textContent = 'Tolak Semua';
                submitButton.className = 'px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600';
                bulkSummaryText.textContent = `Anda akan menolak ${itemIds.length} item sekaligus. Semua item akan ditolak tanpa terkecuali.`;
                break;
                
            case 'onprocess':
                actionModalTitle.innerHTML = '<i class="fas fa-laptop-code text-purple-600 mr-2"></i>OnProcess Item Massal - IT Support';
                noteContainer.classList.remove('hidden');
                conditionContainer.classList.add('hidden');
                submitButton.textContent = 'Process Semua';
                submitButton.className = 'px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600';
                bulkSummaryText.textContent = `Anda akan memproses ${itemIds.length} item sekaligus menjadi OnProcessing.`;
                break;
        }
        
        // Show the modal
        document.getElementById('action-modal').classList.remove('hidden');
    }
    
    // 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' : ''}`;
        }
    }
    
    // FIXED: Load transaction details
    function loadTransactionDetails(transactionId) {
        // Reset bulk selection when loading new transaction
        resetBulkSelection();
        currentTransactionId = transactionId;
        
        // 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-purple-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_it.php?id=${transactionId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    // 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>` : '';
                    
                    // Populate transaction details
                    document.getElementById('transaction-details').innerHTML = `
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            ${overdueWarning}
                            <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>
                    `;
                    
                    // FIXED: Reset and collect available items for bulk selection
                    availableItems = [];
                    allAvailableItemIds = []; // FIXED: Reset all available IDs
                    
                    // 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 bulkCheckbox = '';
                            
                            // FIXED: Check if item can be bulk selected
                            const canBulkSelect = item.quantity_approved === null && item.item_status === 'Tersedia';
                            const isUnavailable = item.quantity_approved === null && item.item_status !== 'Tersedia';
                            
                            if (canBulkSelect) {
                                availableItems.push({
                                    id: item.id,
                                    kode_barang: item.kode_barang,
                                    status: item.item_status
                                });
                                allAvailableItemIds.push(item.id); // FIXED: Store item ID
                            }
                            
                            // 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>
                                `;
                            }
                            
                            // Determine status badge and action buttons
                            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>';
                                
                                // NEW: Add bulk checkbox for pending items
                                if (canBulkSelect) {
                                    bulkCheckbox = `
                                        <input type="checkbox" class="item-checkbox bulk-checkbox" 
                                               data-item-id="${item.id}" 
                                               title="Pilih untuk aksi massal">
                                    `;
                                } else if (isUnavailable) {
                                    bulkCheckbox = `
                                        <input type="checkbox" class="item-checkbox bulk-checkbox" 
                                               data-item-id="${item.id}" 
                                               disabled 
                                               title="Item tidak tersedia untuk dipinjam">
                                    `;
                                }
                                
                                // 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-purple-500 text-white rounded hover:bg-purple-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 unavailable items
                            let containerClass = 'bg-gray-50 item-row';
                            if (currentlyOverdue) {
                                containerClass = 'bg-red-50 border-2 border-red-200 item-row';
                            } else if (isUnavailable) {
                                containerClass = 'bg-gray-50 item-row item-unavailable';
                            }
                            
                            itemsHtml += `
                                <div class="${containerClass} p-4 rounded-lg" data-item-id="${item.id}">
                                    ${overdueIndicator}
                                    <div class="flex items-start justify-between mb-2">
                                        <div class="flex items-start space-x-3">
                                            ${bulkCheckbox}
                                            <div class="flex-1">
                                                <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>` : ''}
                                            </div>
                                        </div>
                                        <div class="flex items-center space-x-2">
                                            ${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>
                            `;
                        });
                    } 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);
                        });
                    });
                    
                    // 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');
                    }
                } 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 bulkSummary = document.getElementById('bulk-summary');
        const submitButton = document.getElementById('submit-action');
        const bulkActionFlag = document.getElementById('bulk-action-flag');
        
        actionItemId.value = itemId;
        actionTransactionId.value = transactionId;
        actionType.value = action;
        bulkActionFlag.value = 'false';
        
        // Reset form
        actionForm.reset();
        
        // Hide bulk summary for single actions
        bulkSummary.classList.add('hidden');
        
        // Configure modal based on action
        switch (action) {
            case 'approve':
                actionModalTitle.innerHTML = '<i class="fas fa-laptop-code text-purple-600 mr-2"></i>Menyetujui Peminjaman - IT Support';
                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.innerHTML = '<i class="fas fa-laptop-code text-purple-600 mr-2"></i>Menolak Peminjaman - IT Support';
                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.innerHTML = '<i class="fas fa-laptop-code text-purple-600 mr-2"></i>Memproses Peminjaman - IT Support';
                noteContainer.classList.remove('hidden');
                conditionContainer.classList.add('hidden');
                submitButton.textContent = 'Proses';
                submitButton.className = 'px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600';
                break;
                
            case 'return':
                actionModalTitle.innerHTML = '<i class="fas fa-laptop-code text-purple-600 mr-2"></i>Mengembalikan Item - IT Support';
                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');
    }
    
    // Handle form submission for actions (both single and bulk)
    actionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(actionForm);
        const isBulkAction = document.getElementById('bulk-action-flag').value === 'true';
        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_it.php', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                // Reset button state
                submitButton.textContent = originalText;
                submitButton.disabled = false;
                
                if (data.status === 'success' || data.status === 'partial') {
                    // Hide action modal
                    actionModal.classList.add('hidden');
                    
                    // Show success notification
                    showNotification(data.message, data.status);
                    
                    // Refresh the transaction details in the modal
                    refreshTransactionDetails(transactionId, itemId, action, isBulkAction, data);
                    
                    // Reset bulk selection after successful bulk action
                    if (isBulkAction) {
                        resetBulkSelection();
                    }
                    
                    // 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');
            });
    });
    
    // Function to refresh transaction details without page reload
    function refreshTransactionDetails(transactionId, updatedItemId, lastAction, isBulkAction = false, bulkData = null) {
        // Simply reload the transaction details
        loadTransactionDetails(transactionId);
    }
});
</script>