// Add Item Page JavaScript

// Format Select2 options without delete icon
function formatSelectOption(option) {
    return option.text;
}

$(document).ready(function() {
    let isSubmitting = false;

    // Initialize Select2 on all select elements with select2 class
    $('.select2').select2({
        placeholder: 'Select an option',
        allowClear: true,
        width: '100%',
        dropdownAutoWidth: true
    });

    // Barcode Scanner Button Click Handler
    $('#scanBarcodeBtn').on('click', function(e) {
        e.preventDefault();
        if (typeof startBarcodeScanner === 'function') {
            startBarcodeScanner();
        } else {
            alert('Barcode scanner not available. Please refresh the page.');
        }
    });

    // Auto-calculate profit and sales price
    $('#purchasePrice, #profitMarginPercent').on('input', function() {
        calculateSalesPrice();
    });
    
    // Form submission - AJAX
    $('#itemForm').on('submit', function(e) {
        e.preventDefault();
        
        if (isSubmitting) {
            return false;
        }
        const itemName = $('input[name="itemName"]').val().trim();
        
        if (!itemName) {
            showToast('error', 'Please enter item name');
            $('input[name="itemName"]').focus();
            return false;
        }
        
        isSubmitting = true;
        
        // Add loading state to button
        $('.btn-save-bottom').addClass('loading').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
        
        // Prepare form data
        const formData = new FormData(this);
        formData.append('ajax', '1');
        
        $.ajax({
            url: 'add-item.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    showToast('success', response.message);
                    
                    const action = $('input[name="action"]').val();
                    // Add or update card in the grid
                    if (action === 'create') {
                        addCardToGrid(response.data);
                        // Reset form
                        $('#itemForm')[0].reset();
                        $('input[name="itemName"]').focus();
                        // Reinitialize Select2 after reset
                        $('.select2').val(null).trigger('change');
                    } else {
                        updateCardInGrid(response.data);
                        resetForm();
                    }
                } else {
                    showToast('error', response.message);
                }
            },
            error: function(xhr, status, error) {
                showToast('error', 'Failed to save item. Please try again.');
            },
            complete: function() {
                $('.btn-save-bottom').removeClass('loading').prop('disabled', false).html('<i class="fas fa-save"></i> Save Item');
                isSubmitting = false;
            }
        });
        
        return false;
    });
    
    // Number input validation
    $('input[type="number"]').on('keypress', function(e) {
        // Allow: backspace, delete, tab, escape, enter, decimal point
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
            // Allow: Ctrl+A, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
            // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
            return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
    
    // Auto-focus on first input
    $('input[name="itemName"]').focus();
    
    // Keyboard shortcuts
    $(document).on('keydown', function(e) {
        // Ctrl+S or Cmd+S to save
        if ((e.ctrlKey || e.metaKey) && e.keyCode === 83) {
            e.preventDefault();
            $('#itemForm').submit();
        }
    });

    // Card interactions - click to edit, button to delete
    $(document).on('click', '.product-card', function(e) {
        // Don't trigger if clicking delete button
        if ($(e.target).closest('.btn-delete-icon').length === 0) {
            const itemId = $(this).data('id');
            if (itemId) {
                editItem(itemId);
            }
        }
    });

    $(document).on('click', '.btn-delete-icon', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const itemId = $(this).closest('.product-card').data('id');
        if (itemId) {
            deleteItem(itemId);
        }
    });
    
    // Image preview
    $('input[name="itemImage"]').on('change', async function(e) {
        const file = e.target.files[0];
        if (file && file.type.startsWith('image/')) {
            // Validate file size (max 5MB)
            if (file.size > 5 * 1024 * 1024) {
                await modernAlert('Image size should not exceed 5MB', 'warning');
                $(this).val('');
                return;
            }
        }
    });
    
});

// Calculate sales price based on purchase price and profit margin
function calculateSalesPrice() {
    const purchasePrice = parseFloat($('#purchasePrice').val()) || 0;
    const profitMarginPercent = parseFloat($('#profitMarginPercent').val()) || 0;
    
    if (purchasePrice > 0 && profitMarginPercent > 0) {
        const profitAmount = (purchasePrice * profitMarginPercent) / 100;
        const salesPrice = purchasePrice + profitAmount;
        $('#salesPrice').val(salesPrice.toFixed(2));
    }
}

// Format number inputs on blur
$(document).on('blur', 'input[type="number"]', function() {
    const val = parseFloat($(this).val());
    if (!isNaN(val)) {
        const step = $(this).attr('step');
        if (step && step.includes('.')) {
            const decimals = step.split('.')[1].length;
            $(this).val(val.toFixed(decimals));
        }
    }
});

// Quick Add Master Functionality
let currentMasterType = '';

function openQuickAdd(masterType) {
    currentMasterType = masterType;
    const modalTitle = 'Add New ' + masterType.charAt(0).toUpperCase() + masterType.slice(1);
    $('#quickAddTitle').text(modalTitle);
    
    let formHtml = '';
    
    switch(masterType) {
        case 'category':
            formHtml = `
                <div class="form-group">
                    <label>Category Name <span class="text-danger">*</span></label>
                    <input type="text" id="quickMasterName" class="form-control" placeholder="Enter category name" required>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea id="quickMasterDesc" class="form-control" rows="2" placeholder="Enter description"></textarea>
                </div>
            `;
            break;
        case 'brand':
            formHtml = `
                <div class="form-group">
                    <label>Brand Name <span class="text-danger">*</span></label>
                    <input type="text" id="quickMasterName" class="form-control" placeholder="Enter brand name" required>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea id="quickMasterDesc" class="form-control" rows="2" placeholder="Enter description"></textarea>
                </div>
            `;
            break;
        case 'supplier':
            formHtml = `
                <div class="form-group">
                    <label>Supplier Name <span class="text-danger">*</span></label>
                    <input type="text" id="quickMasterName" class="form-control" placeholder="Enter supplier name" required>
                </div>
                <div class="form-group">
                    <label>Contact Person</label>
                    <input type="text" id="quickContactPerson" class="form-control" placeholder="Enter contact person">
                </div>
                <div class="form-group">
                    <label>Phone Number</label>
                    <input type="text" id="quickPhone" class="form-control" placeholder="Enter phone number">
                </div>
            `;
            break;
        case 'unit':
            formHtml = `
                <div class="form-group">
                    <label>Unit Name <span class="text-danger">*</span></label>
                    <input type="text" id="quickMasterName" class="form-control" placeholder="Enter unit name (e.g., Pieces)" required>
                </div>
                <div class="form-group">
                    <label>Unit Symbol</label>
                    <input type="text" id="quickSymbol" class="form-control" placeholder="Enter symbol (e.g., Pcs)">
                </div>
            `;
            break;
        case 'tax':
            formHtml = `
                <div class="form-group">
                    <label>Tax Name <span class="text-danger">*</span></label>
                    <input type="text" id="quickMasterName" class="form-control" placeholder="Enter tax name" required>
                </div>
                <div class="form-group">
                    <label>Tax Type <span class="text-danger">*</span></label>
                    <select id="quickTaxType" class="form-control" required>
                        <option value="">Select Type</option>
                        <option value="CGST">CGST</option>
                        <option value="SGST">SGST</option>
                        <option value="IGST">IGST</option>
                        <option value="CESS">CESS</option>
                        <option value="VAT">VAT</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Tax Rate (%) <span class="text-danger">*</span></label>
                    <input type="number" step="0.01" id="quickTaxRate" class="form-control" placeholder="Enter rate" required>
                </div>
            `;
            break;
        case 'location':
            formHtml = `
                <div class="form-group">
                    <label>Location Name <span class="text-danger">*</span></label>
                    <input type="text" id="quickMasterName" class="form-control" placeholder="Enter location name" required>
                </div>
                <div class="form-group">
                    <label>Location Code</label>
                    <input type="text" id="quickLocationCode" class="form-control" placeholder="Enter code">
                </div>
                <div class="form-group">
                    <label>Location Type</label>
                    <select id="quickLocationType" class="form-control">
                        <option value="Warehouse">Warehouse</option>
                        <option value="Store">Store</option>
                        <option value="Site">Site</option>
                        <option value="Office">Office</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
            `;
            break;
        case 'rack':
            formHtml = `
                <div class="form-group">
                    <label>Rack Name <span class="text-danger">*</span></label>
                    <input type="text" id="quickMasterName" class="form-control" placeholder="Enter rack name" required>
                </div>
                <div class="form-group">
                    <label>Rack Code</label>
                    <input type="text" id="quickRackCode" class="form-control" placeholder="Enter code">
                </div>
                <div class="form-group">
                    <label>Location</label>
                    <select id="quickLocationID" class="form-control">
                        <option value="">Select Location</option>
                    </select>
                </div>
            `;
            // Load locations for rack
            $.ajax({
                url: 'api/get-locations.php',
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        response.data.forEach(function(loc) {
                            $('#quickLocationID').append(`<option value="${loc.ID}">${loc.LocationName}</option>`);
                        });
                    }
                }
            });
            break;
    }
    
    $('#quickAddBody').html(formHtml);
    $('#quickAddModal').modal('show');
    
    // Focus on first input
    setTimeout(function() {
        $('#quickMasterName').focus();
    }, 500);
}

// Save Quick Add Master
$('#saveQuickAdd').on('click', async function() {
    const masterName = $('#quickMasterName').val().trim();
    
    if (!masterName) {
        await modernAlert('Please enter the name', 'warning');
        $('#quickMasterName').focus();
        return;
    }
    
    // Build data object based on master type
    const data = {
        action: 'quick_add',
        masterType: currentMasterType,
        status: 'Active'
    };
    
    // Add specific fields based on master type
    switch(currentMasterType) {
        case 'category':
            data.categoryName = masterName;
            data.categoryCode = '';
            data.description = $('#quickMasterDesc').val() || '';
            break;
        case 'brand':
            data.brandName = masterName;
            data.brandCode = '';
            data.manufacturer = '';
            data.contactInfo = $('#quickMasterDesc').val() || '';
            break;
        case 'supplier':
            data.supplierName = masterName;
            data.contactPerson = $('#quickContactPerson').val() || '';
            data.phone = $('#quickPhone').val() || '';
            break;
        case 'unit':
            data.unitName = masterName;
            data.unitSymbol = $('#quickSymbol').val() || '';
            data.description = '';
            break;
        case 'tax':
            data.taxName = masterName;
            data.taxType = $('#quickTaxType').val() || '';
            data.taxRate = $('#quickTaxRate').val() || 0;
            data.description = '';
            break;
        case 'location':
            data.locationName = masterName;
            data.locationCode = $('#quickLocationCode').val() || '';
            data.locationType = $('#quickLocationType').val() || 'Warehouse';
            data.address = '';
            break;
        case 'rack':
            data.rackName = masterName;
            data.rackCode = $('#quickRackCode').val() || '';
            data.locationID = $('#quickLocationID').val() || null;
            data.capacity = null;
            break;
    }
    
    // Disable button and show loading
    $('#saveQuickAdd').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
    
    $.ajax({
        url: 'api/quick-add-master.php',
        method: 'POST',
        data: data,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Add to dropdown
                const selectId = currentMasterType + 'ID';
                const $select = $('#' + selectId);
                
                // Get the appropriate display name from response data
                let displayName = '';
                let newId = response.data.ID;
                
                switch(currentMasterType) {
                    case 'category':
                        displayName = response.data.CategoryName;
                        break;
                    case 'brand':
                        displayName = response.data.BrandName;
                        break;
                    case 'supplier':
                        displayName = response.data.SupplierName;
                        break;
                    case 'unit':
                        displayName = response.data.UnitName;
                        break;
                    case 'tax':
                        displayName = response.data.TaxName + ' (' + response.data.TaxRate + '%)';
                        break;
                    case 'location':
                        displayName = response.data.LocationName;
                        break;
                    case 'rack':
                        displayName = response.data.RackName;
                        break;
                }
                
                const newOption = new Option(displayName, newId, true, true);
                $select.append(newOption);
                
                // Trigger Select2 update
                if ($select.hasClass('select2')) {
                    $select.trigger('change');
                }
                
                // Close modal
                $('#quickAddModal').modal('hide');
                
                // Show success message
                showToast('success', response.message);
            } else {
                modernAlert('Error: ' + response.message, 'error');
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', xhr.responseText);
            modernAlert('Failed to add ' + currentMasterType + '. Please try again.', 'error');
        },
        complete: function() {
            $('#saveQuickAdd').prop('disabled', false).html('Save');
        }
    });
});

// Show notification function
function showNotification(type, message) {
    showToast(type, message);
}

// Toast notification function
function showToast(type, message) {
    const toast = $('#toastNotification');
    const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    toast.removeClass('success error').addClass(type);
    toast.html(`<i class="fas ${icon}"></i> ${message}`);
    toast.addClass('show');
    
    setTimeout(function() {
        toast.removeClass('show');
    }, 3000);
}

function escapeHtml(value) {
    if (value === null || value === undefined) {
        return '';
    }
    return $('<div>').text(value).html();
}

// Add card to grid
function addCardToGrid(item) {
    // Remove "no products" message if exists
    $('.no-products').remove();
    
    const itemName = escapeHtml(item.ItemName || '');
    const salesPrice = parseFloat(item.SalesPrice || 0).toFixed(2);
    const purchasePrice = parseFloat(item.PurchasePrice || 0).toFixed(2);
    const currentStock = parseFloat(item.CurrentStock || 0).toFixed(2);
    const stockValue = (parseFloat(item.PurchasePrice || 0) * parseFloat(item.CurrentStock || 0)).toFixed(2);
    const category = escapeHtml(item.CategoryName || 'N/A');

    const cardHtml = `
        <div class="product-card" 
             data-id="${item.ID}"
             data-category="${category}"
             data-purchase-price="${purchasePrice}"
             data-stock="${currentStock}"
             data-stock-value="${stockValue}">
            <div class="product-card-header">
                <div class="product-info">
                    <div class="product-name">${itemName}</div>
                    <div class="product-price">₹${salesPrice}</div>
                </div>
                <button class="btn-delete-icon" onclick="deleteItem(${item.ID})" title="Delete">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `;
    
    $('.product-grid').prepend(cardHtml);
}

// Update card in grid
function updateCardInGrid(item) {
    const card = $(`.product-card[data-id="${item.ID}"]`);
    
    if (card.length) {
        const itemName = escapeHtml(item.ItemName || '');
        const salesPrice = parseFloat(item.SalesPrice || 0).toFixed(2);
        const purchasePrice = parseFloat(item.PurchasePrice || 0).toFixed(2);
        const currentStock = parseFloat(item.CurrentStock || 0).toFixed(2);
        const stockValue = (parseFloat(item.PurchasePrice || 0) * parseFloat(item.CurrentStock || 0)).toFixed(2);
        const category = escapeHtml(item.CategoryName || 'N/A');
        
        // Update tooltip data attributes
        card.attr('data-category', category);
        card.attr('data-purchase-price', purchasePrice);
        card.attr('data-stock', currentStock);
        card.attr('data-stock-value', stockValue);
        
        // Update card display
        card.find('.product-name').text(itemName);
        card.find('.product-price').text('₹' + salesPrice);
        
        card.removeClass('editing');
    }
}

// Product List - Search Functionality
$('#searchProduct').on('input', function() {
    const searchTerm = $(this).val().toLowerCase();
    
    $('.product-card').each(function() {
        const itemName = $(this).find('.product-name').text().toLowerCase();
        const itemPrice = $(this).find('.product-price').text().toLowerCase();
        
        if (itemName.includes(searchTerm) || itemPrice.includes(searchTerm)) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
});

// Edit Item - Populate form with item data
function editItem(itemId) {
    // Show loading - scroll to top first
    $('.left-column').animate({ scrollTop: 0 }, 300);
    
    $.ajax({
        url: '../api/get-item.php',
        method: 'GET',
        data: { id: itemId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                const item = response.data;
                
                // Populate form fields
                $('input[name="itemName"]').val(item.ItemName);
                $('select[name="categoryID"]').val(item.CategoryID || '').trigger('change');
                $('select[name="brandID"]').val(item.BrandID || '').trigger('change');
                $('select[name="supplierID"]').val(item.SupplierID || '').trigger('change');
                $('select[name="unitID"]').val(item.UnitID || '').trigger('change');
                $('input[name="hsn"]').val(item.HSN || '');
                $('input[name="alertQuantity"]').val(item.AlertQuantity || 0);
                $('input[name="barcode"]').val(item.Barcode || '');
                $('select[name="taxabilityType"]').val(item.TaxabilityType || 'Taxable');
                $('select[name="taxID"]').val(item.TaxID || '').trigger('change');
                $('input[name="purchasePrice"]').val(item.PurchasePrice || 0);
                $('input[name="profitMarginPercent"]').val(item.ProfitMarginPercent || 0);
                $('input[name="salesPrice"]').val(item.SalesPrice || 0);
                $('input[name="shopRate"]').val(item.ShopRate || 0);
                $('input[name="wholesaleRate"]').val(item.WholesaleRate || 0);
                $('input[name="mrp"]').val(item.MRP || 0);
                $('select[name="locationID"]').val(item.LocationID || '').trigger('change');
                $('select[name="rackID"]').val(item.RackID || '').trigger('change');
                $('input[name="openingStock"]').val(item.OpeningStock || 0);
                $('select[name="status"]').val(item.Status || 'Active');
                
                // Change form to edit mode
                $('input[name="action"]').val('update');
                
                // Add hidden field for item ID
                if ($('#editItemId').length === 0) {
                    $('#itemForm').append('<input type="hidden" id="editItemId" name="itemId" value="">');
                }
                $('#editItemId').val(itemId);
                
                // Update header
                $('.form-header .header-left h5').text('Edit Item: ' + item.ItemName);
                
                // Highlight the card being edited
                $('.product-card').removeClass('editing');
                $('.product-card[data-id="' + itemId + '"]').addClass('editing');
                
                showToast('success', 'Item loaded for editing');
            } else {
                showToast('error', 'Failed to load item data');
            }
        },
        error: function() {
            showToast('error', 'Failed to load item data. Please try again.');
        }
    });
}

// Delete Item
async function deleteItem(itemId) {
    const confirmed = await modernConfirm('Are you sure you want to delete this item? This action cannot be undone.', {
        confirmText: 'Delete',
        confirmStyle: 'danger',
        cancelText: 'Cancel'
    });

    if (!confirmed) {
        return;
    }

    $.ajax({
        url: '../api/delete-item.php',
        method: 'POST',
        data: { id: itemId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Remove card from grid
                $('.product-card[data-id="' + itemId + '"]').fadeOut(300, function() {
                    $(this).remove();
                    
                    // Check if grid is empty
                    if ($('.product-card').length === 0) {
                        $('.product-grid').html(`
                            <div class="no-products">
                                <i class="fas fa-box-open"></i>
                                <p>No products found</p>
                            </div>
                        `);
                    }
                });
                
                showToast('success', 'Item deleted successfully');
            } else {
                showToast('error', 'Failed to delete item: ' + response.message);
            }
        },
        error: function() {
            showToast('error', 'Failed to delete item. Please try again.');
        }
    });
}

// Reset form to add mode
function resetForm() {
    $('#itemForm')[0].reset();
    $('input[name="action"]').val('create');
    $('#editItemId').remove();
    $('.form-header .header-left h5').text('Add New Item');
    $('.product-card').removeClass('editing');
    $('input[name="itemName"]').focus();
}

// Add reset button handler
$(document).on('click', '.btn-back', async function(e) {
    if ($('input[name="action"]').val() === 'update') {
        e.preventDefault();
        const shouldReset = await modernConfirm('Do you want to cancel editing and create a new item?', {
            confirmText: 'Yes, reset',
            cancelText: 'Continue editing'
        });
        if (shouldReset) {
            resetForm();
        }
    }
});

