/**
 * Shipping Details Management
 * Handles shipping address and purchase order information
 */

// Global variables for shipping details
let currentShippingData = {
    invoiceNumber: '',
    customerId: null,
    customerName: '',
    customerAddress: '',
    customerCity: '',
    customerState: '',
    customerPinCode: '',
    shippingAddress: '',
    shippingCity: '',
    shippingState: '',
    shippingPinCode: '',
    purchaseOrderNo: '',
    purchaseOrderDate: '',
    transportAmount: 0,
    transportName: '',
    vehicleNumber: '',
    transportGSTPercent: 0,
    transportGSTType: 'inclusive',
    notes: ''
};

/**
 * Initialize shipping details functionality
 */
function initShippingDetails() {
    // Button to open shipping modal
    $('#btnShippingDetails').on('click', async function() {
        await openShippingModal();
    });

    // Copy billing to shipping button
    $('#btnCopyBillingToShipping').on('click', async function() {
        await copyBillingToShipping();
    });

    // Clear shipping details
    $('#btnClearShipping').on('click', async function() {
        await clearShippingFields();
    });

    // Save shipping details
    $('#btnSaveShippingDetails').on('click', async function() {
        await saveShippingDetails();
    });

    // Transport amount input change
    $('#shippingTransportAmount').on('input', function() {
        updateTransportDisplay();
    });

    // Transport GST configuration button
    $('#btnShippingTransportGST').on('click', function() {
        openTransportGSTModal();
    });

    // Set today's date as default for PO date
    const today = new Date().toISOString().split('T')[0];
    $('#purchaseOrderDate').val(today);
}

/**
 * Open shipping details modal
 */
async function openShippingModal() {
    const invoiceNumber = $('#currentInvoiceNumber').text();
    const customerId = $('#customerSelect').val();

    if (!customerId) {
        await MsgBox.alert('Please select a customer first!', 'warning');
        return;
    }

    // Store current invoice and customer
    currentShippingData.invoiceNumber = invoiceNumber;
    currentShippingData.customerId = customerId;

    // Get customer details
    const selectedOption = $('#customerSelect option:selected');
    currentShippingData.customerName = selectedOption.data('name') || '';
    
    // Get customer address from tblcustomers (we'll need to fetch this)
    await loadCustomerBillingAddress(customerId);

    // Load existing shipping details if available
    await loadShippingDetails(invoiceNumber);

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

/**
 * Load customer billing address
 */
async function loadCustomerBillingAddress(customerId) {
    try {
        const response = await $.ajax({
            url: 'api/get-customer-address.php',
            type: 'POST',
            data: { customer_id: customerId },
            dataType: 'json'
        });
        if (response.success) {
            // Update billing address display
            $('#billCustomerName').text(response.data.CustomerName || '-');
            $('#billAddress').text(response.data.Address || '-');
            $('#billCity').text(response.data.City || '-');
            $('#billState').text(response.data.State || '-');
            $('#billPinCode').text(response.data.PinCode || '-');

            // Store for later use
            currentShippingData.customerAddress = response.data.Address || '';
            currentShippingData.customerCity = response.data.City || '';
            currentShippingData.customerState = response.data.State || '';
            currentShippingData.customerPinCode = response.data.PinCode || '';
        }
    } catch (error) {
        console.error('Error loading customer address', error);
    }
}

/**
 * Load existing shipping details for an invoice
 */
async function loadShippingDetails(invoiceNumber) {
    try {
        const response = await $.ajax({
            url: 'api/get-shipping-details.php',
            type: 'POST',
            data: { invoice_number: invoiceNumber },
            dataType: 'json'
        });
        if (response.success && response.data) {
            // Populate purchase order fields
            $('#purchaseOrderNo').val(response.data.PurchaseOrderNo || '');
            $('#purchaseOrderDate').val(response.data.PurchaseOrderDate || '');

            // Populate shipping address fields
            $('#shippingAddress').val(response.data.ShippingAddress || '');
            $('#shippingCity').val(response.data.ShippingCity || '');
            $('#shippingState').val(response.data.ShippingState || '');
            $('#shippingPinCode').val(response.data.ShippingPinCode || '');

            // Populate transport and notes fields
            $('#shippingTransportAmount').val(response.data.TransportAmount || 0);
            $('#shippingNotes').val(response.data.Notes || '');

            // Store in current data
            currentShippingData.shippingAddress = response.data.ShippingAddress || '';
            currentShippingData.shippingCity = response.data.ShippingCity || '';
            currentShippingData.shippingState = response.data.ShippingState || '';
            currentShippingData.shippingPinCode = response.data.ShippingPinCode || '';
            currentShippingData.purchaseOrderNo = response.data.PurchaseOrderNo || '';
            currentShippingData.purchaseOrderDate = response.data.PurchaseOrderDate || '';
            currentShippingData.transportAmount = parseFloat(response.data.TransportAmount) || 0;
            currentShippingData.notes = response.data.Notes || '';

            // Load transport GST details if available
            if (response.data.TransportName || response.data.TransportGSTPercent) {
                currentShippingData.transportName = response.data.TransportName || '';
                currentShippingData.vehicleNumber = response.data.VehicleNumber || '';
                currentShippingData.transportGSTPercent = parseFloat(response.data.TransportGSTPercent) || 0;
                currentShippingData.transportGSTType = response.data.TransportGSTType || 'inclusive';

                // Update display
                updateTransportDetailsDisplay();
            }

            // Update transport display in main form
            updateTransportDisplay();
        }
    } catch (error) {
        console.error('Error loading shipping details', error);
    }
}

/**
 * Copy billing address to shipping address
 */
async function copyBillingToShipping() {
    $('#shippingAddress').val(currentShippingData.customerAddress);
    $('#shippingCity').val(currentShippingData.customerCity);
    $('#shippingState').val(currentShippingData.customerState);
    $('#shippingPinCode').val(currentShippingData.customerPinCode);

    await MsgBox.alert('Billing address copied to shipping address', 'success');
}

/**
 * Clear shipping fields
 */
async function clearShippingFields() {
    $('#shippingAddress').val('');
    $('#shippingCity').val('');
    $('#shippingState').val('');
    $('#shippingPinCode').val('');
    $('#purchaseOrderNo').val('');
    $('#shippingTransportAmount').val('0');
    $('#shippingNotes').val('');
    
    const today = new Date().toISOString().split('T')[0];
    $('#purchaseOrderDate').val(today);

    // Clear transport details
    currentShippingData.transportName = '';
    currentShippingData.vehicleNumber = '';
    currentShippingData.transportGSTPercent = 0;
    currentShippingData.transportGSTType = 'inclusive';
    $('#transportDetailsDisplay').hide();

    await MsgBox.alert('Shipping details cleared', 'info');
}

/**
 * Save shipping details
 */
async function saveShippingDetails() {
    const invoiceNumber = currentShippingData.invoiceNumber;
    const customerId = currentShippingData.customerId;

    // Get shipping address values
    let shippingAddress = $('#shippingAddress').val().trim();
    let shippingCity = $('#shippingCity').val().trim();
    let shippingState = $('#shippingState').val().trim();
    let shippingPinCode = $('#shippingPinCode').val().trim();

    // If shipping address is empty, use billing address
    if (!shippingAddress && !shippingCity && !shippingState && !shippingPinCode) {
        shippingAddress = currentShippingData.customerAddress;
        shippingCity = currentShippingData.customerCity;
        shippingState = currentShippingData.customerState;
        shippingPinCode = currentShippingData.customerPinCode;
    }

    const shippingData = {
        invoice_number: invoiceNumber,
        customer_id: customerId,
        shipping_address: shippingAddress,
        shipping_city: shippingCity,
        shipping_state: shippingState,
        shipping_pincode: shippingPinCode,
        purchase_order_no: $('#purchaseOrderNo').val().trim(),
        purchase_order_date: $('#purchaseOrderDate').val(),
        transport_amount: parseFloat($('#shippingTransportAmount').val()) || 0,
        transport_name: currentShippingData.transportName,
        vehicle_number: currentShippingData.vehicleNumber,
        transport_gst_percent: currentShippingData.transportGSTPercent,
        transport_gst_type: currentShippingData.transportGSTType,
        notes: $('#shippingNotes').val().trim()
    };

    // Update hidden fields in main form for compatibility
    $('#cooliAmount').val(shippingData.transport_amount);
    $('#transportNameValue').val(shippingData.transport_name);
    $('#vehicleNumberValue').val(shippingData.vehicle_number);
    $('#transportGSTPercent').val(shippingData.transport_gst_percent);
    $('#transportGSTTypeValue').val(shippingData.transport_gst_type);
    $('#notes').val(shippingData.notes);

    // Save to database
    try {
        const response = await $.ajax({
            url: 'api/save-shipping-details.php',
            type: 'POST',
            data: shippingData,
            dataType: 'json'
        });
        if (response.success) {
            await MsgBox.alert('Shipping details saved successfully!', 'success');
            
            // Update current data
            currentShippingData.shippingAddress = shippingAddress;
            currentShippingData.shippingCity = shippingCity;
            currentShippingData.shippingState = shippingState;
            currentShippingData.shippingPinCode = shippingPinCode;
            currentShippingData.purchaseOrderNo = shippingData.purchase_order_no;
            currentShippingData.purchaseOrderDate = shippingData.purchase_order_date;
            currentShippingData.transportAmount = shippingData.transport_amount;
            currentShippingData.notes = shippingData.notes;

            // Update button badge if PO number exists
            updateShippingButtonBadge();

            // Update transport display in main form
            updateTransportDisplay();

            // Recalculate totals if calculateTotals function exists
            if (typeof calculateTotals === 'function') {
                calculateTotals();
            }

            // Close modal
            $('#shippingDetailsModal').modal('hide');
        } else {
            await MsgBox.alert(response.message || 'Error saving shipping details', 'danger');
        }
    } catch (error) {
        console.error('Error saving shipping details:', error);
        await MsgBox.alert('Error saving shipping details. Please try again.', 'danger');
    }
}

/**
 * Update shipping button badge to show if PO exists
 */
function updateShippingButtonBadge() {
    if (currentShippingData.purchaseOrderNo) {
        $('#btnShippingDetails').addClass('btn-info').removeClass('btn-primary');
        $('#btnShippingDetails').attr('title', 'PO: ' + currentShippingData.purchaseOrderNo);
    } else {
        $('#btnShippingDetails').addClass('btn-primary').removeClass('btn-info');
        $('#btnShippingDetails').attr('title', 'Shipping Details');
    }
}

/**
 * Reset shipping data (when creating new invoice)
 */
function resetShippingData() {
    currentShippingData = {
        invoiceNumber: '',
        customerId: null,
        customerName: '',
        customerAddress: '',
        customerCity: '',
        customerState: '',
        customerPinCode: '',
        shippingAddress: '',
        shippingCity: '',
        shippingState: '',
        shippingPinCode: '',
        purchaseOrderNo: '',
        purchaseOrderDate: '',
        transportAmount: 0,
        transportName: '',
        vehicleNumber: '',
        transportGSTPercent: 0,
        transportGSTType: 'inclusive',
        notes: ''
    };

    $('#btnShippingDetails').addClass('btn-primary').removeClass('btn-info');
    $('#btnShippingDetails').attr('title', 'Shipping Details');

    // Reset hidden fields
    $('#cooliAmount').val('0');
    $('#notes').val('');
    $('#transportNameValue').val('');
    $('#vehicleNumberValue').val('');
    $('#transportGSTPercent').val('0');
    $('#transportGSTTypeValue').val('inclusive');
}

/**
 * Update transport display in main form
 */
function updateTransportDisplay() {
    const transportAmount = parseFloat($('#shippingTransportAmount').val()) || 0;
    $('#cooliAmount').val(transportAmount);
    $('#cooliDisplay').text('₹' + transportAmount.toFixed(2));
}

/**
 * Update transport details display in modal
 */
function updateTransportDetailsDisplay() {
    if (currentShippingData.transportName || currentShippingData.transportGSTPercent > 0) {
        $('#displayTransportName').text(currentShippingData.transportName || '-');
        $('#displayVehicleNumber').text(currentShippingData.vehicleNumber || '-');
        $('#displayTransportGSTPercent').text(currentShippingData.transportGSTPercent.toFixed(2));
        $('#displayTransportGSTType').text(currentShippingData.transportGSTType);
        $('#transportDetailsDisplay').show();
    } else {
        $('#transportDetailsDisplay').hide();
    }
}

/**
 * Open transport GST modal (from shipping modal)
 */
function openTransportGSTModal() {
    // Get current transport amount from shipping modal
    const transportAmount = parseFloat($('#shippingTransportAmount').val()) || 0;
    
    // Populate the main transport GST modal
    $('#transportGSTAmount').val(transportAmount);
    $('#transportName').val(currentShippingData.transportName || '');
    $('#vehicleNumber').val(currentShippingData.vehicleNumber || '');
    $('#transportGSTPercentage').val(currentShippingData.transportGSTPercent || 0);
    
    // Set GST type radio buttons
    if (currentShippingData.transportGSTType === 'exclusive') {
        $('#transportGSTExclusive').prop('checked', true);
        $('#transportGSTExclusive').parent().addClass('active');
        $('#transportGSTInclusive').parent().removeClass('active');
    } else {
        $('#transportGSTInclusive').prop('checked', true);
        $('#transportGSTInclusive').parent().addClass('active');
        $('#transportGSTExclusive').parent().removeClass('active');
    }
    
    // Calculate and show the modal
    if (typeof calculateTransportGST === 'function') {
        calculateTransportGST();
    }
    
    // Override the apply button to save to shipping data
    $('#btnApplyTransportGST').off('click').on('click', function() {
        applyTransportGSTToShipping();
    });
    
    // Show the transport modal with proper z-index handling
    $('#transportGSTModal').modal('show');
    
    // Ensure transport modal appears in front of shipping modal
    $('#transportGSTModal').on('shown.bs.modal', function() {
        $(this).css('z-index', parseInt($('#shippingDetailsModal').css('z-index')) + 10);
        $('.modal-backdrop').not(':first').css('z-index', parseInt($('#shippingDetailsModal').css('z-index')) + 5);
    });
}

/**
 * Apply transport GST to shipping data
 */
async function applyTransportGSTToShipping() {
    currentShippingData.transportName = $('#transportName').val().trim();
    currentShippingData.vehicleNumber = $('#vehicleNumber').val().trim();
    currentShippingData.transportGSTPercent = parseFloat($('#transportGSTPercentage').val()) || 0;
    currentShippingData.transportGSTType = $('input[name="transportGSTType"]:checked').val();
    
    const transportAmount = parseFloat($('#transportGSTAmount').val()) || 0;
    $('#shippingTransportAmount').val(transportAmount);
    
    // Update display
    updateTransportDetailsDisplay();
    
    // Update hidden fields
    $('#transportNameValue').val(currentShippingData.transportName);
    $('#vehicleNumberValue').val(currentShippingData.vehicleNumber);
    $('#transportGSTPercent').val(currentShippingData.transportGSTPercent);
    $('#transportGSTTypeValue').val(currentShippingData.transportGSTType);
    
    // Trigger recalculation of bill discount and totals
    if (window.SalesEnhancements && window.SalesEnhancements.BillDiscountManager) {
        window.SalesEnhancements.BillDiscountManager.calculateBillDiscount();
    }
    
    // Close modal
    $('#transportGSTModal').modal('hide');
    
    await MsgBox.alert('Transport details updated', 'success');
}

/**
 * Show alert message
 */
async function showAlert(type, message) {
    await MsgBox.alert(message, type);
}

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