/**
 * Hold Bills Management
 * Handles saving, loading, and resuming hold bills in POS
 */

// Hold Bill - Open Input Modal
$(document).on('click', '#btnHoldBill', async function() {
    // Check if cart has items
    if (typeof cart === 'undefined' || cart.length === 0) {
        await MsgBox.alert('Cart is empty. Nothing to hold.');
        return;
    }

    // Calculate totals
    var totalItems = cart.length;
    var grandTotal = $('#grandTotal').text();

    // Update summary in modal
    $('#holdSummaryItems').text(totalItems);
    $('#holdSummaryTotal').text(grandTotal);
    $('#holdBillNote').val('');

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

// Confirm Hold Bill
$(document).on('click', '#btnConfirmHoldBill', async function() {
    if (typeof cart === 'undefined' || cart.length === 0) {
        await MsgBox.alert('Cart is empty. Nothing to hold.');
        return;
    }

    var note = $('#holdBillNote').val().trim();

    // Get current customer info
    var customerId = $('#customerSelect').val() || 0;
    var customerName = $('#customerSelect option:selected').text() || 'Walk-in Customer';
    if (customerName === 'Select Customer' || customerName === '') {
        customerName = 'Walk-in Customer';
    }

    // Get sales type
    var salesType = $('#salesType').val() || 'GST';
    var invoiceNumber = $('#invoiceNumber').val();

    // Get totals
    var subTotal = parseFloat($('#subtotal').text().replace(/[^0-9.-]/g, '')) || 0;
    var taxAmount = parseFloat($('#taxAmount').text().replace(/[^0-9.-]/g, '')) || 0;
    var grandTotal = parseFloat($('#grandTotal').text().replace(/[^0-9.-]/g, '')) || 0;
    var discount = parseFloat($('#discountAmount').val()) || 0;
    var roundOff = parseFloat($('#roundOffAmount').text().replace(/[^0-9.-]/g, '')) || 0;

    // Clean cart items - remove any circular references or functions
    var cleanCart = [];
    try {
        cleanCart = JSON.parse(JSON.stringify(cart));
    } catch(e) {
        console.error('Error cleaning cart:', e);
        await MsgBox.alert('Error preparing cart data. Please check console.');
        $('#btnConfirmHoldBill').prop('disabled', false).html('<i class="fas fa-save"></i> Hold Bill');
        return;
    }

    // Prepare data
    var holdData = {
        customerId: customerId,
        customerName: customerName,
        salesType: salesType,
        invoiceNumber: invoiceNumber,
        items: cleanCart,
        subTotal: subTotal,
        taxAmount: taxAmount,
        grandTotal: grandTotal,
        discount: discount,
        roundOff: roundOff,
        notes: note
    };

    // Show loading
    $('#btnConfirmHoldBill').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');

    // Save to server
    $.ajax({
        url: 'api/save-hold-bill.php',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(holdData),
        dataType: 'json',
        success: async function(response) {
            if (response.success) {
                await MsgBox.alert('Bill held successfully! Hold Number: ' + response.holdNumber);
                
                // Clear cart
                if (typeof clearCart === 'function') {
                    clearCart();
                } else {
                    cart = [];
                    if (typeof updateDisplay === 'function') {
                        updateDisplay();
                    }
                }

                // Close modal
                $('#holdBillInputModal').modal('hide');
            } else {
                var errorMsg = response.message || 'Failed to hold bill';
                
                // Check if table doesn't exist
                if (errorMsg.includes("doesn't exist") || errorMsg.includes('tblhold_bills')) {
                    errorMsg += '\n\nThe database table needs to be created first.';
                    if (await MsgBox.confirm(errorMsg + '\n\nWould you like to go to the setup page now?')) {
                        window.open('../database/setup_hold_bills_web.php', '_blank');
                    }
                } else {
                    await MsgBox.alert('Failed to hold bill: ' + errorMsg);
                }
                console.error('Hold bill error:', response);
            }
        },
        error: async function(xhr, status, error) {
            console.error('AJAX Error:', xhr.responseText);
            var errorMsg = 'Error holding bill: ' + error;
            try {
                var response = JSON.parse(xhr.responseText);
                if (response.message) {
                    errorMsg = 'Failed to hold bill: ' + response.message;
                }
            } catch(e) {
                // Response is not JSON
                errorMsg += '\n\nServer response: ' + xhr.responseText.substring(0, 200);
            }
            await MsgBox.alert(errorMsg);
        },
        complete: function() {
            $('#btnConfirmHoldBill').prop('disabled', false).html('<i class="fas fa-save"></i> Hold Bill');
        }
    });
});

// View Hold Bills - Open Modal
$(document).on('click', '#btnViewHoldBills', function() {
    $('#holdBillsModal').modal('show');
    loadHoldBills();
});

// Load Hold Bills List
function loadHoldBills() {
    $('#holdBillsListContainer').html(`
        <div class="text-center py-5">
            <i class="fas fa-spinner fa-spin fa-3x text-primary"></i>
            <p class="mt-3">Loading hold bills...</p>
        </div>
    `);

    $.ajax({
        url: 'api/get-hold-bills.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                displayHoldBills(response.data);
            } else {
                $('#holdBillsListContainer').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle"></i> ${response.message}
                    </div>
                `);
            }
        },
        error: function(xhr, status, error) {
            $('#holdBillsListContainer').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Error loading hold bills: ${error}
                </div>
            `);
        }
    });
}

// Display Hold Bills in Grid
function displayHoldBills(holdBills) {
    if (!holdBills || holdBills.length === 0) {
        $('#holdBillsListContainer').html(`
            <div class="text-center py-5 text-muted">
                <i class="fas fa-inbox fa-3x mb-3"></i>
                <p>No hold bills found</p>
            </div>
        `);
        return;
    }

    var html = '<div class="row">';

    holdBills.forEach(function(bill) {
        var heldDate = new Date(bill.HeldDate);
        var dateStr = heldDate.toLocaleDateString() + ' ' + heldDate.toLocaleTimeString();
        var customerName = bill.CustomerName || 'Walk-in Customer';
        var notes = bill.Notes || 'No notes';

        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card shadow-sm border-primary hold-bill-card" data-hold-id="${bill.ID}">
                    <div class="card-header bg-primary text-white py-2">
                        <div class="d-flex justify-content-between align-items-center">
                            <strong><i class="fas fa-receipt"></i> ${bill.HoldNumber}</strong>
                            <button class="btn btn-sm btn-danger delete-hold-bill" data-hold-id="${bill.ID}">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body hold-bill-body" data-hold-id="${bill.ID}" style="cursor: pointer;">
                        <div class="row mb-2">
                            <div class="col-6">
                                <small class="text-muted">Customer:</small><br>
                                <strong>${customerName}</strong>
                            </div>
                            <div class="col-6 text-right">
                                <small class="text-muted">Items:</small><br>
                                <strong>${bill.TotalItems}</strong>
                            </div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-12">
                                <small class="text-muted">Grand Total:</small><br>
                                <h5 class="text-success mb-0">₹${parseFloat(bill.GrandTotal).toFixed(2)}</h5>
                            </div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-12">
                                <small class="text-muted"><i class="fas fa-sticky-note"></i> Note:</small><br>
                                <small>${notes}</small>
                            </div>
                        </div>
                        <hr class="my-2">
                        <small class="text-muted">
                            <i class="fas fa-clock"></i> ${dateStr}
                        </small>
                    </div>
                    <div class="card-footer py-2 bg-light">
                        <button class="btn btn-sm btn-success btn-block resume-hold-bill" data-hold-id="${bill.ID}">
                            <i class="fas fa-play"></i> Resume Bill
                        </button>
                    </div>
                </div>
            </div>
        `;
    });

    html += '</div>';
    $('#holdBillsListContainer').html(html);
}

// Resume Hold Bill - Click on card body
$(document).on('click', '.hold-bill-body', function(e) {
    e.stopPropagation();
    var holdId = $(this).data('hold-id');
    resumeHoldBill(holdId);
});

// Resume Hold Bill - Click on Resume button
$(document).on('click', '.resume-hold-bill', function(e) {
    e.stopPropagation();
    var holdId = $(this).data('hold-id');
    resumeHoldBill(holdId);
});

// Resume Hold Bill Function
async function resumeHoldBill(holdId) {
    if (!await MsgBox.confirm('Resume this hold bill? Current cart will be cleared.')) {
        return;
    }

    // Show loading
    $.ajax({
        url: 'api/get-hold-bill-details.php?id=' + holdId,
        type: 'GET',
        dataType: 'json',
        success: async function(response) {
            if (response.success) {
                var holdBill = response.data;

                // Clear current cart
                if (typeof clearCart === 'function') {
                    clearCart();
                } else {
                    cart = [];
                }

                // Load hold bill data
                cart = holdBill.Items || [];

                // Set customer
                if (holdBill.CustomerID && holdBill.CustomerID > 0) {
                    $('#customerSelect').val(holdBill.CustomerID).trigger('change');
                }

                // Set sales type
                if (holdBill.SalesType) {
                    $('#salesType').val(holdBill.SalesType).trigger('change');
                }

                // Update display
                if (typeof updateDisplay === 'function') {
                    updateDisplay();
                }

                // Delete hold bill after resuming
                deleteHoldBillAfterResume(holdId);

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

                await MsgBox.alert('Hold bill resumed successfully!');
            } else {
                await MsgBox.alert('Failed to load hold bill: ' + response.message);
            }
        },
        error: async function(xhr, status, error) {
            await MsgBox.alert('Error loading hold bill: ' + error);
        }
    });
}

// Delete Hold Bill After Resume
function deleteHoldBillAfterResume(holdId) {
    $.ajax({
        url: 'api/delete-hold-bill.php',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ id: holdId }),
        success: function(response) {
            console.log('Hold bill deleted after resume:', response);
        },
        error: function(xhr, status, error) {
            console.error('Error deleting hold bill:', error);
        }
    });
}

// Delete Hold Bill - Click on delete button
$(document).on('click', '.delete-hold-bill', async function(e) {
    e.stopPropagation();
    var holdId = $(this).data('hold-id');

    if (!await MsgBox.confirm('Delete this hold bill permanently?')) {
        return;
    }

    // Show loading
    $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');

    $.ajax({
        url: 'api/delete-hold-bill.php',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ id: holdId }),
        success: async function(response) {
            if (response.success) {
                await MsgBox.alert('Hold bill deleted successfully!');
                loadHoldBills(); // Reload list
            } else {
                await MsgBox.alert('Failed to delete hold bill: ' + response.message);
            }
        },
        error: async function(xhr, status, error) {
            await MsgBox.alert('Error deleting hold bill: ' + error);
        }
    });
});

// Add CSS for hold bill cards
$('<style>')
    .text(`
        .hold-bill-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .hold-bill-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 20px rgba(0,0,0,0.2) !important;
        }
        .hold-bill-body:hover {
            background-color: #f8f9fa;
        }
    `)
    .appendTo('head');
