/**
 * Delete Bill Module
 * Handles bill deletion with complete data review
 */

(function() {
    'use strict';

    let currentBillData = null;

    // Initialize on document ready
    $(document).ready(function() {
        initDeleteBill();
    });

    function initDeleteBill() {
        // Event: Delete Bill Button Click - handle all delete bill buttons
        $('#btnDeleteBillHeader, #btnDeleteBillModal, #btnDeleteBill').on('click', function() {
            openDeleteBillModal();
        });

        // Event: Confirmation Input Change
        $('#deleteConfirmInput').on('input', function() {
            const inputValue = $(this).val().trim();
            if (inputValue === 'DELETE') {
                $('#btnConfirmDeleteBill').prop('disabled', false);
            } else {
                $('#btnConfirmDeleteBill').prop('disabled', true);
            }
        });

        // Event: Confirm Delete Button
        $('#btnConfirmDeleteBill').on('click', function() {
            confirmDeleteBill();
        });

        // Event: Modal Hidden - Reset
        $('#deleteBillModal').on('hidden.bs.modal', function() {
            resetDeleteModal();
        });
    }

    async function openDeleteBillModal() {
        // Get current bill ID from editing mode or current invoice
        const editingSaleId = $('#editingSaleId').val();
        
        if (!editingSaleId || editingSaleId == 0) {
            await MsgBox.alert('No bill is currently loaded for deletion.');
            return;
        }

        // Store bill ID
        $('#deleteBillId').val(editingSaleId);

        // Load bill delete details
        await loadBillDeleteDetails(editingSaleId);

        // Show modal
        $('#deleteBillModal').modal('show');
    }

    async function loadBillDeleteDetails(billId) {
        // Show loading state
        $('#delBillItemsList').html('<tr><td colspan="4" class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');
        $('#delBillAccountTransactions').html('<tr><td colspan="4" class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>');

        try {
            const response = await $.ajax({
                url: 'api/get-bill-delete-details.php',
                method: 'GET',
                data: { billId: billId },
                dataType: 'json'
            });

            if (response.success) {
                currentBillData = response;
                displayBillDeleteDetails(response);
            } else {
                await MsgBox.alert('Error loading bill details: ' + (response.message || 'Unknown error'));
                $('#deleteBillModal').modal('hide');
            }
        } catch (error) {
            console.error('Error loading bill details:', error);
            await MsgBox.alert('Error loading bill details. Check console for details.');
            $('#deleteBillModal').modal('hide');
        }
    }

    function displayBillDeleteDetails(data) {
        const bill = data.bill;
        const items = data.items;
        const accountTransactions = data.accountTransactions;
        const loyaltyTransactions = data.loyaltyTransactions;
        const counts = data.counts;
        const impact = data.impact;

        // Display bill information
        $('#delBillInvoiceNo').text(bill.invoiceNumber);
        $('#delBillCustomerName').text(bill.customerName + ' (' + bill.customerCode + ')');
        $('#delBillDate').text(formatDate(bill.saleDate));
        $('#delBillTotalAmount').text('₹' + parseFloat(bill.totalAmount).toFixed(2));
        $('#delBillPaidAmount').text('₹' + parseFloat(bill.paidAmount).toFixed(2));
        
        // Display status badge
        let statusClass = 'badge-success';
        if (bill.paymentStatus === 'Unpaid') statusClass = 'badge-danger';
        if (bill.paymentStatus === 'Partial') statusClass = 'badge-warning';
        $('#delBillStatus').attr('class', 'badge ' + statusClass).text(bill.paymentStatus);

        // Display items
        $('#delBillItemCount').text(counts.items);
        let itemsHtml = '';
        if (items.length > 0) {
            items.forEach(function(item) {
                itemsHtml += '<tr>';
                itemsHtml += '<td>' + item.ProductName + ' <small class="text-muted">(' + item.ProductCode + ')</small></td>';
                itemsHtml += '<td class="text-right">' + parseFloat(item.Quantity).toFixed(2) + '</td>';
                itemsHtml += '<td class="text-right">₹' + parseFloat(item.Rate).toFixed(2) + '</td>';
                itemsHtml += '<td class="text-right">₹' + parseFloat(item.Amount).toFixed(2) + '</td>';
                itemsHtml += '</tr>';
            });
        } else {
            itemsHtml = '<tr><td colspan="4" class="text-center text-muted">No items found</td></tr>';
        }
        $('#delBillItemsList').html(itemsHtml);

        // Display account transactions
        let accountHtml = '';
        if (accountTransactions.length > 0) {
            accountTransactions.forEach(function(trans) {
                let typeClass = trans.TransactionType === 'Debit' ? 'text-danger' : 'text-success';
                let typeIcon = trans.TransactionType === 'Debit' ? 'fa-arrow-up' : 'fa-arrow-down';
                
                accountHtml += '<tr>';
                accountHtml += '<td><i class="fas ' + typeIcon + ' ' + typeClass + '"></i> ' + trans.TransactionType + '</td>';
                accountHtml += '<td>' + formatDate(trans.TransactionDate) + '</td>';
                accountHtml += '<td class="text-right ' + typeClass + '">₹' + parseFloat(trans.Amount).toFixed(2) + '</td>';
                accountHtml += '<td>' + trans.Description + '</td>';
                accountHtml += '</tr>';
            });
        } else {
            accountHtml = '<tr><td colspan="4" class="text-center text-muted">No account transactions found</td></tr>';
        }
        $('#delBillAccountTransactions').html(accountHtml);

        // Display loyalty transactions
        if (loyaltyTransactions.length > 0) {
            $('#delBillLoyaltyCard').show();
            let loyaltyHtml = '';
            loyaltyTransactions.forEach(function(trans) {
                let typeClass = trans.TransactionType === 'EARNED' ? 'text-success' : 'text-warning';
                loyaltyHtml += '<tr>';
                loyaltyHtml += '<td><span class="badge badge-' + (trans.TransactionType === 'EARNED' ? 'success' : 'warning') + '">' + trans.TransactionType + '</span></td>';
                loyaltyHtml += '<td class="text-right ' + typeClass + '">' + parseFloat(trans.Points).toFixed(0) + ' pts</td>';
                loyaltyHtml += '<td>' + trans.Reference + '</td>';
                loyaltyHtml += '</tr>';
            });
            $('#delBillLoyaltyTransactions').html(loyaltyHtml);
        } else {
            $('#delBillLoyaltyCard').hide();
        }

        // Display summary counts
        $('#delItemsCount').text(counts.items);
        $('#delAccountCount').text(counts.accountTransactions);
        $('#delLoyaltyCount').text(counts.loyaltyTransactions);

        // Display impact
        const balanceChange = parseFloat(impact.balanceAdjustment).toFixed(2);
        const balanceClass = impact.balanceAdjustment > 0 ? 'text-success' : 'text-danger';
        $('#delBalanceAdjustment').html('<span class="' + balanceClass + '">₹' + balanceChange + '</span>');

        const pointsChange = parseFloat(impact.pointsAdjustment).toFixed(0);
        const pointsClass = impact.pointsAdjustment > 0 ? 'text-success' : 'text-danger';
        $('#delPointsAdjustment').html('<span class="' + pointsClass + '">' + pointsChange + '</span>');
    }

    async function confirmDeleteBill() {
        const billId = $('#deleteBillId').val();
        const confirmation = $('#deleteConfirmInput').val().trim();

        if (!billId) {
            await MsgBox.alert('No bill selected for deletion');
            return;
        }

        if (confirmation !== 'DELETE') {
            await MsgBox.alert('Please type DELETE to confirm');
            return;
        }

        // Disable button and show loading
        const btn = $('#btnConfirmDeleteBill');
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Deleting...');

        try {
            const response = await $.ajax({
                url: 'api/delete-bill.php',
                method: 'POST',
                data: JSON.stringify({
                    billId: billId,
                    confirmation: confirmation
                }),
                contentType: 'application/json',
                dataType: 'json'
            });

            if (response.success) {
                await MsgBox.alert('Bill deleted successfully!\n\n' +
                      'Invoice: ' + response.deletedBill.invoiceNumber + '\n' +
                      'Customer: ' + response.deletedBill.customerName + '\n' +
                      'Amount: ₹' + parseFloat(response.deletedBill.amount).toFixed(2) + '\n\n' +
                      'Deleted Records:\n' +
                      '- Sale Items: ' + response.deletedRecords.saleItems + '\n' +
                      '- Account Transactions: ' + response.deletedRecords.accountTransactions + '\n' +
                      '- Loyalty Transactions: ' + response.deletedRecords.loyaltyTransactions + '\n\n' +
                      'Customer Adjustments:\n' +
                      '- Balance Change: ₹' + parseFloat(response.customerAdjustments.balanceChange).toFixed(2) + '\n' +
                      '- Points Change: ' + parseFloat(response.customerAdjustments.pointsChange).toFixed(0));

                // Close modal
                $('#deleteBillModal').modal('hide');

                // Redirect to new sale or reload
                setTimeout(function() {
                    window.location.href = 'index.php';
                }, 500);
            } else {
                await MsgBox.alert('Error deleting bill: ' + (response.message || 'Unknown error'));
                btn.prop('disabled', false).html('<i class="fas fa-trash-alt"></i> Delete Bill Permanently');
            }
        } catch (error) {
            console.error('Error deleting bill:', error);
            await MsgBox.alert('Error deleting bill. Please try again.');
            btn.prop('disabled', false).html('<i class="fas fa-trash-alt"></i> Delete Bill Permanently');
        }
    }

    function resetDeleteModal() {
        currentBillData = null;
        $('#deleteBillId').val('');
        $('#deleteConfirmInput').val('');
        $('#btnConfirmDeleteBill').prop('disabled', true).html('<i class="fas fa-trash-alt"></i> Delete Bill Permanently');
        
        // Clear displays
        $('#delBillInvoiceNo, #delBillCustomerName, #delBillDate, #delBillTotalAmount, #delBillPaidAmount').text('');
        $('#delBillItemsList, #delBillAccountTransactions, #delBillLoyaltyTransactions').html('');
        $('#delBillLoyaltyCard').hide();
    }

    function formatDate(dateString) {
        if (!dateString) return '-';
        const date = new Date(dateString);
        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = date.getFullYear();
        return day + '-' + month + '-' + year;
    }

})();
