<div class="d-flex justify-content-between align-items-center mb-4">
    <h4 class="mb-0 text-primary fw-bold"><i class="bi bi-arrow-return-left me-2"></i> <?php echo __('purchase_returns'); ?></h4>
    <button type="button" class="btn btn-primary" onclick="openCreateReturnModal()">
        <i class="bi bi-plus-lg me-2"></i> <?php echo __('create_return'); ?>
    </button>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle" id="returnsTable">
                <thead class="table-light">
                    <tr>
                        <th>#</th>
                        <th><?php echo __('date'); ?></th>
                        <th><?php echo __('supplier'); ?></th>
                        <th><?php echo __('total_amount'); ?></th>
                        <th><?php echo __('reason'); ?></th>
                        <th><?php echo __('actions'); ?></th>
                    </tr>
                </thead>
                <tbody id="returnsTableBody">
                    <tr><td colspan="6" class="text-center py-4"><div class="spinner-border text-primary" role="status"></div></td></tr>
                </tbody>
            </table>
        </div>
        <!-- Pagination -->
        <nav id="paginationContainer" class="mt-3" aria-label="Page navigation"></nav>
    </div>
</div>

<!-- Create Return Modal -->
<div class="modal fade" id="createReturnModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <form id="createReturnForm" onsubmit="submitReturn(event)">
            <div class="modal-content border-0 shadow">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title fw-bold"><i class="bi bi-plus-circle me-2"></i> <?php echo __('create_return'); ?></h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body bg-light">
                    <div class="card mb-3 border-0 shadow-sm">
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label fw-bold"><?php echo __('supplier'); ?></label>
                                    <select name="supplier_id" id="return_supplier_id" class="form-select select2-modal" required>
                                        <option value=""><?php echo __('select_supplier'); ?>...</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label fw-bold"><?php echo __('return_date'); ?></label>
                                    <input type="date" name="return_date" id="return_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label"><?php echo __('reason'); ?></label>
                                    <textarea name="reason" id="return_reason" class="form-control" rows="2"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-white py-3">
                            <div class="d-flex justify-content-between align-items-center">
                                <h6 class="mb-0 fw-bold text-primary"><?php echo __('items'); ?></h6>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="addReturnItemRow()">
                                    <i class="bi bi-plus-lg me-1"></i> <?php echo __('add_item'); ?>
                                </button>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-bordered mb-0" id="returnItemsTable">
                                    <thead class="table-light">
                                        <tr>
                                            <th style="width: 30%;"><?php echo __('drug_name'); ?></th>
                                            <th style="width: 25%;"><?php echo __('batch_number'); ?></th>
                                            <th style="width: 15%;"><?php echo __('quantity'); ?></th>
                                            <th style="width: 15%;"><?php echo __('unit_price'); ?></th>
                                            <th style="width: 15%;"><?php echo __('total_price'); ?></th>
                                            <th style="width: 5%;"></th>
                                        </tr>
                                    </thead>
                                    <tbody id="returnItemsBody">
                                        <!-- Dynamic Rows -->
                                    </tbody>
                                    <tfoot class="table-light">
                                        <tr>
                                            <td colspan="4" class="text-end fw-bold"><?php echo __('total_amount'); ?>:</td>
                                            <td class="fw-bold text-primary fs-5" id="returnTotalDisplay">0.00</td>
                                            <td></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-white">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                    <button type="submit" class="btn btn-primary px-4"><i class="bi bi-save me-2"></i> <?php echo __('save'); ?></button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- View Return Modal -->
<div class="modal fade" id="viewReturnModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title fw-bold"><i class="bi bi-eye me-2"></i> <?php echo __('view_return'); ?> #<span id="view_return_id"></span></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-4">
                    <div class="col-md-6">
                        <p class="mb-1 text-muted small"><?php echo __('supplier'); ?></p>
                        <h6 class="fw-bold" id="view_return_supplier"></h6>
                    </div>
                    <div class="col-md-6 text-end">
                        <p class="mb-1 text-muted small"><?php echo __('date'); ?></p>
                        <h6 class="fw-bold" id="view_return_date"></h6>
                    </div>
                </div>
                
                <h6 class="border-bottom pb-2 mb-3 fw-bold text-primary"><?php echo __('items'); ?></h6>
                <div class="table-responsive">
                    <table class="table table-bordered table-sm">
                        <thead class="table-light">
                            <tr>
                                <th><?php echo __('drug_name'); ?></th>
                                <th><?php echo __('batch_number'); ?></th>
                                <th class="text-center"><?php echo __('quantity'); ?></th>
                                <th class="text-end"><?php echo __('unit_price'); ?></th>
                                <th class="text-end"><?php echo __('total_price'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="viewReturnItemsBody"></tbody>
                        <tfoot class="table-light">
                            <tr>
                                <td colspan="4" class="text-end fw-bold"><?php echo __('total_amount'); ?></td>
                                <td class="text-end fw-bold text-primary" id="view_return_total"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="mt-3">
                    <p class="mb-1 text-muted small"><?php echo __('reason'); ?></p>
                    <p class="bg-light p-2 rounded" id="view_return_reason"></p>
                </div>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('close'); ?></button>
            </div>
        </div>
    </div>
</div>

<script>
let allDrugs = [];
let allSuppliers = [];
let currentPage = 1;

document.addEventListener('DOMContentLoaded', function() {
    loadReturns(1);
    fetchSuppliers();
    fetchDrugs();
    
    // Calculate total when inputs change in the table
    document.getElementById('returnItemsBody').addEventListener('input', function(e) {
        if (e.target.classList.contains('return-qty') || e.target.classList.contains('return-price')) {
            calculateRowTotal(e.target.closest('tr'));
            calculateGrandTotal();
        }
    });

    // Re-initialize Select2 when modal is shown
    $('#createReturnModal').on('shown.bs.modal', function () {
        $('.select2-modal').select2({
            dropdownParent: $('#createReturnModal'),
            width: '100%'
        });
    });
});

function loadReturns(page = 1) {
    currentPage = page;
    fetch('api/pharmacy_lpo.php?action=get_returns&page=' + page)
        .then(response => response.json())
        .then(data => {
            const tbody = document.getElementById('returnsTableBody');
            const paginationContainer = document.getElementById('paginationContainer');
            tbody.innerHTML = '';
            
            const returns = data.data || (Array.isArray(data) ? data : []);
            const totalPages = data.pages || 1;
            
            if (returns.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-muted"><?php echo __('no_data_found'); ?></td></tr>';
                paginationContainer.innerHTML = '';
                return;
            }
            
            returns.forEach(r => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${r.id}</td>
                    <td>${r.return_date}</td>
                    <td>${r.supplier_name || '-'}</td>
                    <td class="fw-bold text-danger">${formatCurrency(r.total_amount)}</td>
                    <td>${r.reason || '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewReturn(${r.id}, '${r.supplier_name}', '${r.return_date}', '${r.total_amount}', '${r.reason || ''}')">
                            <i class="bi bi-eye"></i>
                        </button>
                    </td>
                `;
                tbody.appendChild(tr);
            });

            renderPagination(currentPage, totalPages);
        })
        .catch(err => {
            console.error(err);
            document.getElementById('returnsTableBody').innerHTML = '<tr><td colspan="6" class="text-center text-danger">Error loading data</td></tr>';
        });
}

function renderPagination(current, total) {
    const container = document.getElementById('paginationContainer');
    if (total <= 1) {
        container.innerHTML = '';
        return;
    }
    let html = '<ul class="pagination justify-content-center">';
    html += `<li class="page-item ${current <= 1 ? 'disabled' : ''}"><a class="page-link" href="#" onclick="event.preventDefault(); loadReturns(${current - 1})"><?php echo __('previous'); ?></a></li>`;
    let start = Math.max(1, current - 2);
    let end = Math.min(total, start + 4);
    if (end - start < 4) start = Math.max(1, end - 4);
    for (let i = start; i <= end; i++) {
        html += `<li class="page-item ${current === i ? 'active' : ''}"><a class="page-link" href="#" onclick="event.preventDefault(); loadReturns(${i})">${i}</a></li>`;
    }
    html += `<li class="page-item ${current >= total ? 'disabled' : ''}"><a class="page-link" href="#" onclick="event.preventDefault(); loadReturns(${current + 1})"><?php echo __('next'); ?></a></li>`;
    html += '</ul>';
    container.innerHTML = html;
}

function fetchSuppliers() {
    fetch('api/pharmacy_lpo.php?action=get_suppliers')
        .then(response => response.json())
        .then(data => {
            allSuppliers = data;
            const select = document.getElementById('return_supplier_id');
            select.innerHTML = '<option value=""><?php echo __('select_supplier'); ?>...</option>';
            data.forEach(s => {
                select.innerHTML += `<option value="${s.id}">${s.name_en} / ${s.name_ar}</option>`;
            });
        });
}

function fetchDrugs() {
    fetch('api/pharmacy_lpo.php?action=get_drugs')
        .then(response => response.json())
        .then(data => {
            allDrugs = data;
        });
}

function openCreateReturnModal() {
    document.getElementById('createReturnForm').reset();
    $('#return_supplier_id').val('').trigger('change');
    document.getElementById('returnItemsBody').innerHTML = '';
    document.getElementById('returnTotalDisplay').innerText = '0.00';
    addReturnItemRow();
    
    var modal = new bootstrap.Modal(document.getElementById('createReturnModal'));
    modal.show();
}

function addReturnItemRow() {
    const tbody = document.getElementById('returnItemsBody');
    const tr = document.createElement('tr');
    
    let drugOptions = '<option value="">Select Drug...</option>';
    allDrugs.forEach(d => {
        drugOptions += `<option value="${d.id}" data-price="${d.price}">${d.name_en} (${d.sku || '-'})</option>`;
    });
    
    tr.innerHTML = `
        <td>
            <select name="items[drug_id][]" class="form-select select2-modal-row return-drug" onchange="returnDrugSelected(this)" required>
                ${drugOptions}
            </select>
        </td>
        <td>
            <select name="items[batch_id][]" class="form-select select2-modal-row return-batch" onchange="returnBatchSelected(this)" required disabled>
                <option value="">Select Batch...</option>
            </select>
        </td>
        <td><input type="number" name="items[quantity][]" class="form-control return-qty" min="1" value="1" required></td>
        <td><input type="number" name="items[unit_price][]" class="form-control return-price" step="0.01" min="0" value="0.00" required></td>
        <td><input type="text" class="form-control return-total" readonly value="0.00"></td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeReturnRow(this)"><i class="bi bi-trash"></i></button>
        </td>
    `;
    tbody.appendChild(tr);
    
    $(tr).find('.select2-modal-row').select2({
        dropdownParent: $('#createReturnModal'),
        width: '100%'
    });
}

function removeReturnRow(btn) {
    const tbody = document.getElementById('returnItemsBody');
    if (tbody.children.length > 1) {
        btn.closest('tr').remove();
        calculateGrandTotal();
    }
}

function returnDrugSelected(select) {
    const drugId = select.value;
    const row = select.closest('tr');
    const batchSelect = row.querySelector('.return-batch');
    
    // Clear and disable batch select
    batchSelect.innerHTML = '<option value="">Select Batch...</option>';
    batchSelect.disabled = true;
    $(batchSelect).trigger('change'); // Notify Select2
    
    if (!drugId) return;

    // Fetch Batches
    fetch('api/pharmacy.php?action=get_batches&drug_id=' + drugId)
        .then(response => response.json())
        .then(data => {
            batchSelect.disabled = false;
            data.forEach(b => {
                // Show expiry and qty
                const label = `${b.batch_number} (Exp: ${b.expiry_date}, Qty: ${b.quantity})`;
                const option = new Option(label, b.id, false, false);
                option.setAttribute('data-qty', b.quantity);
                option.setAttribute('data-cost', b.cost_price);
                batchSelect.add(option);
            });
            $(batchSelect).trigger('change'); // Update UI
        });
}

function returnBatchSelected(select) {
    const option = select.options[select.selectedIndex];
    const row = select.closest('tr');
    const qtyInput = row.querySelector('.return-qty');
    const priceInput = row.querySelector('.return-price');
    
    const maxQty = option.getAttribute('data-qty') || 1;
    const costPrice = option.getAttribute('data-cost') || 0;
    
    // Set max quantity
    qtyInput.max = maxQty;
    qtyInput.value = Math.min(qtyInput.value, maxQty);
    
    // Suggest refund price as cost price
    priceInput.value = costPrice;
    
    calculateRowTotal(row);
    calculateGrandTotal();
}

function calculateRowTotal(row) {
    const qty = parseFloat(row.querySelector('.return-qty').value) || 0;
    const price = parseFloat(row.querySelector('.return-price').value) || 0;
    const total = qty * price;
    row.querySelector('.return-total').value = total.toFixed(2);
}

function calculateGrandTotal() {
    let total = 0;
    document.querySelectorAll('.return-total').forEach(input => {
        total += parseFloat(input.value) || 0;
    });
    document.getElementById('returnTotalDisplay').innerText = total.toFixed(2);
}

function submitReturn(e) {
    e.preventDefault();
    
    const supplierId = document.getElementById('return_supplier_id').value;
    const date = document.getElementById('return_date').value;
    const reason = document.getElementById('return_reason').value;
    const totalAmount = document.getElementById('returnTotalDisplay').innerText;
    
    const items = [];
    document.querySelectorAll('#returnItemsBody tr').forEach(row => {
        const drugId = $(row).find('.return-drug').val();
        const batchId = $(row).find('.return-batch').val();
        const quantity = row.querySelector('.return-qty').value;
        const unitPrice = row.querySelector('.return-price').value;
        const totalPrice = row.querySelector('.return-total').value;
        
        if (drugId && batchId) {
            items.push({
                drug_id: drugId,
                batch_id: batchId,
                quantity: quantity,
                unit_price: unitPrice,
                total_price: totalPrice
            });
        }
    });
    
    if (items.length === 0) {
        alert('Please add at least one item.');
        return;
    }

    fetch('api/pharmacy_lpo.php?action=create_return', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ supplier_id: supplierId, return_date: date, reason: reason, total_amount: totalAmount, items: items })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('createReturnModal')).hide();
            loadReturns();
        } else {
            alert('Error: ' + (data.error || 'Unknown error'));
        }
    });
}

function viewReturn(id, supplier, date, total, reason) {
    document.getElementById('view_return_id').innerText = id;
    document.getElementById('view_return_supplier').innerText = supplier;
    document.getElementById('view_return_date').innerText = date;
    document.getElementById('view_return_total').innerText = formatCurrency(total);
    document.getElementById('view_return_reason').innerText = reason;
    
    const tbody = document.getElementById('viewReturnItemsBody');
    tbody.innerHTML = '<tr><td colspan="5" class="text-center">Loading...</td></tr>';
    
    var modal = new bootstrap.Modal(document.getElementById('viewReturnModal'));
    modal.show();
    
    fetch('api/pharmacy_lpo.php?action=get_return_details&id=' + id)
        .then(response => response.json())
        .then(data => {
            tbody.innerHTML = '';
            data.forEach(item => {
                tbody.innerHTML += `
                    <tr>
                        <td>${item.drug_name} <small class="text-muted">(${item.sku || '-'})</small></td>
                        <td>${item.batch_number || '-'}</td>
                        <td class="text-center">${item.quantity}</td>
                        <td class="text-end">${formatCurrency(item.unit_price)}</td>
                        <td class="text-end">${formatCurrency(item.total_price)}</td>
                    </tr>
                `;
            });
        });
}
</script>