// Refund/Exchange Modal Logic

// Open refund modal
function openRefundModal() {
    document.getElementById('refundModal').style.display = 'block';
}

// Close refund modal
function closeRefundModal() {
    document.getElementById('refundModal').style.display = 'none';
}

// Search sale by receipt number
async function searchSale() {
    const receiptId = document.getElementById('refundReceiptId').value.trim();
    const errorDiv = document.getElementById('refundSaleItems');
    errorDiv.innerHTML = '';
    if (!receiptId) {
        errorDiv.innerHTML = '<div class="alert alert-danger">Please enter a receipt number.</div>';
        return;
    }
    try {
        const response = await fetch('get_sale.php?id=' + encodeURIComponent(receiptId));
        const sale = await response.json();
        if (sale.success) {
            renderRefundSale(sale.data);
        } else {
            errorDiv.innerHTML = '<div class="alert alert-danger">' + (sale.message || 'Sale not found!') + '</div>';
        }
    } catch (err) {
        errorDiv.innerHTML = '<div class="alert alert-danger">Error searching sale. Please try again.</div>';
    }
}

// Render sale items for refund/exchange
function renderRefundSale(sale) {
    const container = document.getElementById('refundSaleItems');
    container.innerHTML = '';
    sale.items.forEach(item => {
        const isRefunded = Number(item.refunded) === 1;
        const refundedBadge = isRefunded ? '<span class="badge bg-success ms-2">Refunded</span>' : '';
        const disabledAttr = isRefunded ? 'disabled' : '';
        container.innerHTML += `
            <div class="refund-item">
                <div class="d-flex justify-content-between align-items-center">
                    <span>${item.product_name} (${item.quantity} x Rs ${item.unit_price}) ${refundedBadge}</span>
                    <div>
                        <button onclick="refundItem(${item.id}, ${item.sale_id})" class="btn btn-danger btn-sm me-2" ${disabledAttr}>Refund</button>
                        <button onclick="exchangeItem(${item.id}, ${item.sale_id})" class="btn btn-warning btn-sm" ${disabledAttr}>Exchange</button>
                    </div>
                </div>
            </div>
        `;
    });
}

// Refund item
async function refundItem(itemId, saleId) {
    if (!confirm('Refund this item?')) return;
    const response = await fetch('refund_item.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ item_id: itemId, sale_id: saleId })
    });
    const result = await response.json();
    if (result.success) {
        alert('Item refunded!');
        // Reload sale data to reflect refunded status
        searchSale();
    } else {
        alert('Refund failed: ' + result.message);
    }
}

// Exchange item
async function exchangeItem(itemId, saleId) {
    // Fetch products for dropdown
    const response = await fetch('get_products.php');
    const products = await response.json();
    // Fetch old item details
    const saleResponse = await fetch('get_sale.php?id=' + saleId);
    const saleData = await saleResponse.json();
    let oldItem = null;
    if (saleData.success && saleData.data && saleData.data.items) {
        oldItem = saleData.data.items.find(i => i.id == itemId);
    }
    const container = document.getElementById('refundSaleItems');
    let options = '';
    products.forEach(p => {
        options += `<option value="${p.id}" data-barcode="${p.barcode || ''}" data-price="${p.price}">${p.name} (Rs ${p.price})</option>`;
    });
    let oldPrice = oldItem ? oldItem.unit_price : 0;
    container.innerHTML = `
        <div class="exchange-section">
            <label>Old item price:</label>
            <input type="text" id="oldItemPrice" class="form-control mb-2" value="Rs ${oldPrice}" readonly>
            <label>Scan or enter barcode:</label>
            <input type="text" id="exchangeBarcode" class="form-control mb-2" placeholder="Scan barcode...">
            <label>Select replacement product:</label>
            <select id="exchangeProductId" class="form-control mb-2">${options}</select>
            <label>Quantity:</label>
            <input type="number" id="exchangeQuantity" class="form-control mb-2" value="1" min="1">
            <div id="exchangePriceDiff" class="alert alert-info mt-2" style="display:none;"></div>
            <button class="btn btn-success" onclick="confirmExchange(${itemId}, ${saleId})">Confirm Exchange</button>
            <button class="btn btn-secondary" onclick="searchSale()">Cancel</button>
        </div>
    `;
    // Barcode input event
    document.getElementById('exchangeBarcode').addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            const barcode = this.value.trim();
            const select = document.getElementById('exchangeProductId');
            for (let opt of select.options) {
                if (opt.getAttribute('data-barcode') === barcode) {
                    select.value = opt.value;
                    break;
                }
            }
            updateExchangePriceDiff();
        }
    });
    document.getElementById('exchangeProductId').addEventListener('change', updateExchangePriceDiff);
    document.getElementById('exchangeQuantity').addEventListener('input', updateExchangePriceDiff);

    function updateExchangePriceDiff() {
        const select = document.getElementById('exchangeProductId');
        const newPrice = parseFloat(select.options[select.selectedIndex].getAttribute('data-price')) || 0;
        const qty = parseInt(document.getElementById('exchangeQuantity').value) || 1;
        const totalOld = oldPrice;
        const totalNew = newPrice * qty;
        const diff = totalNew - totalOld;
        const diffDiv = document.getElementById('exchangePriceDiff');
        if (diff > 0) {
            diffDiv.innerHTML = `Customer should pay <strong>Rs ${diff.toFixed(2)}</strong> for the exchange.`;
            diffDiv.style.display = 'block';
        } else if (diff < 0) {
            diffDiv.innerHTML = `Cashier should refund <strong>Rs ${Math.abs(diff).toFixed(2)}</strong> to the customer.`;
            diffDiv.style.display = 'block';
        } else {
            diffDiv.innerHTML = `No price difference.`;
            diffDiv.style.display = 'block';
        }
    }
    // Initial calculation
    updateExchangePriceDiff();
}

async function confirmExchange(itemId, saleId) {
    const newProductId = document.getElementById('exchangeProductId').value;
    const newQuantity = parseInt(document.getElementById('exchangeQuantity').value) || 1;
    const select = document.getElementById('exchangeProductId');
    const newPrice = parseFloat(select.options[select.selectedIndex].getAttribute('data-price')) || 0;
    const qty = newQuantity;
    const oldPrice = parseFloat(document.getElementById('oldItemPrice').value.replace('Rs ', '')) || 0;
    const totalOld = oldPrice;
    const totalNew = newPrice * qty;
    const priceDiff = totalNew - totalOld;
    const response = await fetch('exchange_item.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ item_id: itemId, sale_id: saleId, new_product_id: newProductId, new_quantity: newQuantity, price_diff: priceDiff })
    });
    const result = await response.json();
    if (result.success) {
        alert('Exchange completed!');
        closeRefundModal();
        // Open receipt in new tab
        window.open('receipt.php?id=' + saleId, '_blank');
    } else {
        alert('Exchange failed: ' + result.message);
    }
}

// Attach modal open to POS (ensure after DOM is loaded)
document.addEventListener('DOMContentLoaded', function() {
    var btn = document.getElementById('openRefundBtn');
    if (btn) {
        btn.onclick = openRefundModal;
    }
});