// Item Management JavaScript

let variantCount = 0;

$(document).ready(function() {
    // Initialize any existing functionality
});

function openItemModal() {
    const modalTitle = document.getElementById('modalTitle');
    const modalBody = document.getElementById('modalBody');
    const itemForm = document.getElementById('itemForm');
    
    modalTitle.textContent = 'Add New Item';
    itemForm.reset();
    variantCount = 0;
    
    const formHTML = generateItemForm();
    modalBody.innerHTML = formHTML;
    
    // Initialize form handlers
    initializeFormHandlers();
    
    // Load dropdown data
    loadDropdownData();
    
    $('#itemModal').modal('show');
}

function generateItemForm() {
    return `
        <input type="hidden" name="action" value="create">

        <!-- Basic Information -->
        <div class="form-section">
            <div class="form-section-title">
                <i class="fas fa-info-circle"></i> Basic Information
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="itemName">Item Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="itemName" id="itemName" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="itemNameTamil">Item Name (Tamil)</label>
                        <input type="text" class="form-control" name="itemNameTamil" id="itemNameTamil">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="brandID">Brand</label>
                        <div class="input-group">
                            <select class="form-control" name="brandID" id="brandID">
                                <option value="">Select Brand</option>
                            </select>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-success btn-sm" onclick="openQuickAddModal('brand')" title="Add New Brand">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="categoryID">Category <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <select class="form-control" name="categoryID" id="categoryID" required>
                                <option value="">Select Category</option>
                            </select>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-success btn-sm" onclick="openQuickAddModal('category')" title="Add New Category">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="unitID">Unit <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <select class="form-control" name="unitID" id="unitID" required>
                                <option value="">Select Unit</option>
                            </select>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-success btn-sm" onclick="openQuickAddModal('unit')" title="Add New Unit">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="sku">SKU</label>
                        <input type="text" class="form-control" name="sku" id="sku">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="hsn">HSN Code</label>
                        <input type="text" class="form-control" name="hsn" id="hsn">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="barcode">Barcode</label>
                        <input type="text" class="form-control" name="barcode" id="barcode">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="alertQuantity">Alert Quantity</label>
                        <input type="number" step="0.01" class="form-control" name="alertQuantity" id="alertQuantity" value="0">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="sellerPoints">Seller Points</label>
                        <input type="number" class="form-control" name="sellerPoints" id="sellerPoints" value="0">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="description">Description</label>
                <textarea class="form-control" name="description" id="description" rows="3"></textarea>
            </div>
            <div class="form-group">
                <label for="itemImage">Product Image</label>
                <input type="file" class="form-control-file" name="itemImage" id="itemImage" accept="image/*">
                <small class="form-text text-muted">Accepted formats: JPG, PNG, GIF (Max 2MB)</small>
                <div id="imagePreview" class="image-preview" style="display:none;">
                    <img src="" alt="Preview" id="previewImg">
                </div>
            </div>
        </div>

        <!-- Pricing Information -->
        <div class="form-section">
            <div class="form-section-title">
                <i class="fas fa-rupee-sign"></i> Pricing & Tax Information
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="discountType">Discount Type</label>
                        <select class="form-control" name="discountType" id="discountType">
                            <option value="Percentage">Percentage (%)</option>
                            <option value="Fixed">Fixed Amount</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="discount">Discount</label>
                        <input type="number" step="0.01" class="form-control" name="discount" id="discount" value="0">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="price">Price <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" class="form-control" name="price" id="price" required>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="priceWithoutTax">Price w/o Tax</label>
                        <input type="number" step="0.01" class="form-control" name="priceWithoutTax" id="priceWithoutTax" readonly>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="taxabilityType">Taxability Type</label>
                        <select class="form-control" name="taxabilityType" id="taxabilityType">
                            <option value="Taxable">Taxable</option>
                            <option value="Non-Taxable">Non-Taxable</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="taxID">Tax <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <select class="form-control" name="taxID" id="taxID" required>
                                <option value="">Select Tax</option>
                            </select>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-success btn-sm" onclick="openQuickAddModal('tax')" title="Add New Tax">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="purchasePrice">Purchase Price <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" class="form-control" name="purchasePrice" id="purchasePrice" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="profitMarginPercent">Profit Margin (%)</label>
                        <input type="number" step="0.01" class="form-control" name="profitMarginPercent" id="profitMarginPercent">
                    </div>
                </div>
            </div>
        </div>

        <!-- Sales Pricing -->
        <div class="form-section">
            <div class="form-section-title">
                <i class="fas fa-tags"></i> Sales Pricing
            </div>
            <div class="row">
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="salesPrice">Sales Price</label>
                        <input type="number" step="0.01" class="form-control" name="salesPrice" id="salesPrice">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="shopRate">Shop Rate</label>
                        <input type="number" step="0.01" class="form-control" name="shopRate" id="shopRate">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="wholesaleRate">Wholesale Rate</label>
                        <input type="number" step="0.01" class="form-control" name="wholesaleRate" id="wholesaleRate">
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <label for="mrp">MRP</label>
                        <input type="number" step="0.01" class="form-control" name="mrp" id="mrp">
                    </div>
                </div>
            </div>
        </div>

        <!-- Location & Stock -->
        <div class="form-section">
            <div class="form-section-title">
                <i class="fas fa-warehouse"></i> Location & Stock
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="locationID">Location</label>
                        <div class="input-group">
                            <select class="form-control" name="locationID" id="locationID">
                                <option value="">Select Location</option>
                            </select>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-success btn-sm" onclick="openQuickAddModal('location')" title="Add New Location">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="rackID">Rack</label>
                        <div class="input-group">
                            <select class="form-control" name="rackID" id="rackID">
                                <option value="">Select Rack</option>
                            </select>
                            <div class="input-group-append">
                                <button type="button" class="btn btn-success btn-sm" onclick="openQuickAddModal('rack')" title="Add New Rack">
                                    <i class="fas fa-plus"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <label for="openingStock">Opening Stock</label>
                        <input type="number" step="0.01" class="form-control" name="openingStock" id="openingStock" value="0">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="status">Status</label>
                <select class="form-control" name="status" id="status">
                    <option value="Active">Active</option>
                    <option value="Inactive">Inactive</option>
                </select>
            </div>
        </div>

        <!-- Variants Section (Hidden by default) -->
        <div id="variantsSection" style="display: none;">
    `;
}

function initializeFormHandlers() {
    // Image preview handler
    $('#itemImage').on('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#previewImg').attr('src', e.target.result);
                $('#imagePreview').fadeIn();
            };
            reader.readAsDataURL(file);
        }
    });

    // Price calculation handlers
    $('#price, #taxID').on('change', function() {
        calculatePriceWithTax();
    });

    $('#purchasePrice, #profitMarginPercent').on('input', function() {
        calculateProfitAndSalesPrice();
    });

    $('#taxabilityType').on('change', function() {
        if ($(this).val() === 'Non-Taxable') {
            $('#taxID').prop('required', false);
        } else {
            $('#taxID').prop('required', true);
        }
    });
}

function loadDropdownData() {
    // Load brands
    if (masterData.brands) {
        const brandSelect = $('#brandID');
        masterData.brands.forEach(brand => {
            brandSelect.append(`<option value="${brand.ID}">${brand.BrandName}</option>`);
        });
    }

    // Load categories
    if (masterData.categories) {
        const categorySelect = $('#categoryID');
        masterData.categories.forEach(category => {
            categorySelect.append(`<option value="${category.ID}">${category.CategoryName}</option>`);
        });
    }

    // Load units
    if (masterData.units) {
        const unitSelect = $('#unitID');
        masterData.units.forEach(unit => {
            unitSelect.append(`<option value="${unit.ID}">${unit.UnitName}</option>`);
        });
    }

    // Load taxes
    if (masterData.taxes) {
        const taxSelect = $('#taxID');
        masterData.taxes.forEach(tax => {
            taxSelect.append(`<option value="${tax.ID}">${tax.TaxName} (${tax.TaxRate}%)</option>`);
        });
    }

    // Load locations
    if (masterData.locations) {
        const locationSelect = $('#locationID');
        masterData.locations.forEach(location => {
            locationSelect.append(`<option value="${location.ID}">${location.LocationName}</option>`);
        });
    }

    // Load racks
    if (masterData.racks) {
        const rackSelect = $('#rackID');
        masterData.racks.forEach(rack => {
            rackSelect.append(`<option value="${rack.ID}">${rack.RackName}</option>`);
        });
    }
}

function calculatePriceWithTax() {
    const price = parseFloat($('#price').val()) || 0;
    const taxID = $('#taxID').val();
    
    if (taxID && masterData.taxes) {
        const tax = masterData.taxes.find(t => t.ID == taxID);
        if (tax) {
            const taxRate = parseFloat(tax.TaxRate) || 0;
            const priceWithoutTax = price / (1 + (taxRate / 100));
            const priceWithTax = price;
            
            $('#priceWithoutTax').val(priceWithoutTax.toFixed(2));
            $('#priceWithTax').val(priceWithTax.toFixed(2));
        }
    }
}

function calculateProfitAndSalesPrice() {
    const purchasePrice = parseFloat($('#purchasePrice').val()) || 0;
    const profitMargin = parseFloat($('#profitMarginPercent').val()) || 0;
    
    if (purchasePrice > 0 && profitMargin > 0) {
        const profitAmount = purchasePrice * (profitMargin / 100);
        const salesPrice = purchasePrice + profitAmount;
        
        $('#salesPrice').val(salesPrice.toFixed(2));
    }
}

function editItem(itemId) {
    // Fetch item details via API
    fetch(`api/get-item.php?id=${itemId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                openEditModal(data.item, data.variants);
            } else {
                alert('Error loading item: ' + (data.message || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading item data');
        });
}

function openEditModal(item, variants) {
    openItemModal();
    
    // Update modal title
    document.getElementById('modalTitle').textContent = 'Edit Item';
    
    // Update form action
    $('input[name="action"]').val('update');
    $('#itemForm').prepend(`<input type="hidden" name="id" value="${item.ID}">`);
    
    // Populate form fields
    $('#itemName').val(item.ItemName);
    $('#itemNameTamil').val(item.ItemNameTamil);
    $('#brandID').val(item.BrandID);
    $('#categoryID').val(item.CategoryID);
    $('#unitID').val(item.UnitID);
    $('#sku').val(item.SKU);
    $('#hsn').val(item.HSN);
    $('#barcode').val(item.Barcode);
    $('#alertQuantity').val(item.AlertQuantity);
    $('#sellerPoints').val(item.SellerPoints);
    $('#description').val(item.Description);
    $('#discountType').val(item.DiscountType);
    $('#discount').val(item.Discount);
    $('#price').val(item.Price);
    $('#priceWithoutTax').val(item.PriceWithoutTax);
    $('#taxabilityType').val(item.TaxabilityType);
    $('#taxID').val(item.TaxID);
    $('#purchasePrice').val(item.PurchasePrice);
    $('#profitMarginPercent').val(item.ProfitMarginPercent);
    $('#salesPrice').val(item.SalesPrice);
    $('#shopRate').val(item.ShopRate);
    $('#wholesaleRate').val(item.WholesaleRate);
    $('#mrp').val(item.MRP);
    $('#locationID').val(item.LocationID);
    $('#rackID').val(item.RackID);
    $('#openingStock').val(item.OpeningStock);
    $('#status').val(item.Status);
    
    // Show image preview if exists
    if (item.ItemImage) {
        $('#previewImg').attr('src', `../uploads/items/${item.ItemImage}`);
        $('#imagePreview').show();
    }
}

function deleteItem(itemId, itemName) {
    if (confirm(`Are you sure you want to delete "${itemName}"?\n\nThis action cannot be undone and will also delete all variants associated with this item.`)) {
        window.location.href = `item-management.php?delete=${itemId}`;
    }
}

// Quick Add Modal for Master Data
function openQuickAddModal(masterType) {
    // Create modal HTML if it doesn't exist
    if ($('#quickAddModal').length === 0) {
        const modalHTML = `
            <div class="modal fade" id="quickAddModal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header bg-success text-white">
                            <h5 class="modal-title" id="quickAddModalTitle">Quick Add</h5>
                            <button type="button" class="close text-white" data-dismiss="modal">
                                <span>&times;</span>
                            </button>
                        </div>
                        <div class="modal-body" id="quickAddModalBody">
                            <!-- Dynamic form content -->
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-success" onclick="saveQuickAdd()">
                                <i class="fas fa-save"></i> Save
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;
        $('body').append(modalHTML);
    }

    const titleMap = {
        'brand': 'Add New Brand',
        'category': 'Add New Category',
        'unit': 'Add New Unit',
        'tax': 'Add New Tax',
        'location': 'Add New Location',
        'rack': 'Add New Rack'
    };

    $('#quickAddModalTitle').text(titleMap[masterType] || 'Quick Add');
    $('#quickAddModalBody').html(generateQuickAddForm(masterType));
    $('#quickAddModal').data('masterType', masterType);
    $('#quickAddModal').modal('show');
}

function generateQuickAddForm(masterType) {
    let formHTML = '';

    switch(masterType) {
        case 'unit':
            formHTML = `
                <div class="form-group">
                    <label>Unit Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="qa_unitName" required>
                </div>
                <div class="form-group">
                    <label>Unit Symbol <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="qa_unitSymbol" required>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea class="form-control" id="qa_description" rows="2"></textarea>
                </div>
            `;
            break;

        case 'category':
            formHTML = `
                <div class="form-group">
                    <label>Category Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="qa_categoryName" required>
                </div>
                <div class="form-group">
                    <label>Category Code</label>
                    <input type="text" class="form-control" id="qa_categoryCode">
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea class="form-control" id="qa_description" rows="2"></textarea>
                </div>
            `;
            break;

        case 'brand':
            formHTML = `
                <div class="form-group">
                    <label>Brand Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="qa_brandName" required>
                </div>
                <div class="form-group">
                    <label>Brand Code</label>
                    <input type="text" class="form-control" id="qa_brandCode">
                </div>
                <div class="form-group">
                    <label>Manufacturer</label>
                    <input type="text" class="form-control" id="qa_manufacturer">
                </div>
                <div class="form-group">
                    <label>Contact Info</label>
                    <input type="text" class="form-control" id="qa_contactInfo">
                </div>
            `;
            break;

        case 'tax':
            formHTML = `
                <div class="form-group">
                    <label>Tax Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="qa_taxName" required>
                </div>
                <div class="form-group">
                    <label>Tax Type <span class="text-danger">*</span></label>
                    <select class="form-control" id="qa_taxType" required>
                        <option value="">Select Tax 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" class="form-control" id="qa_taxRate" required>
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea class="form-control" id="qa_description" rows="2"></textarea>
                </div>
            `;
            break;

        case 'location':
            formHTML = `
                <div class="form-group">
                    <label>Location Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="qa_locationName" required>
                </div>
                <div class="form-group">
                    <label>Location Code</label>
                    <input type="text" class="form-control" id="qa_locationCode">
                </div>
                <div class="form-group">
                    <label>Location Type</label>
                    <select class="form-control" id="qa_locationType">
                        <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>
                <div class="form-group">
                    <label>Address</label>
                    <textarea class="form-control" id="qa_address" rows="2"></textarea>
                </div>
            `;
            break;

        case 'rack':
            formHTML = `
                <div class="form-group">
                    <label>Rack Name <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="qa_rackName" required>
                </div>
                <div class="form-group">
                    <label>Rack Code</label>
                    <input type="text" class="form-control" id="qa_rackCode">
                </div>
                <div class="form-group">
                    <label>Location</label>
                    <select class="form-control" id="qa_locationID">
                        <option value="">Select Location</option>
                        ${masterData.locations.map(loc => `<option value="${loc.ID}">${loc.LocationName}</option>`).join('')}
                    </select>
                </div>
                <div class="form-group">
                    <label>Capacity</label>
                    <input type="number" step="0.01" class="form-control" id="qa_capacity">
                </div>
            `;
            break;
    }

    return formHTML;
}

function saveQuickAdd() {
    const masterType = $('#quickAddModal').data('masterType');
    
    // Collect form data
    const formData = new FormData();
    formData.append('action', 'quick_add');
    formData.append('masterType', masterType);
    formData.append('status', 'Active');
    
    // Get field values based on master type
    let isValid = true;
    $('#quickAddModalBody input, #quickAddModalBody select, #quickAddModalBody textarea').each(function() {
        const field = $(this);
        const fieldId = field.attr('id');
        const fieldName = fieldId.replace('qa_', '');
        const fieldValue = field.val();
        
        // Check required fields
        if (field.prop('required') && !fieldValue) {
            isValid = false;
            field.addClass('is-invalid');
        } else {
            field.removeClass('is-invalid');
        }
        
        formData.append(fieldName, fieldValue);
    });
    
    if (!isValid) {
        alert('Please fill in all required fields');
        return;
    }
    
    // Show loading state
    const saveBtn = $('#quickAddModal .btn-success');
    const originalText = saveBtn.html();
    saveBtn.html('<i class="fas fa-spinner fa-spin"></i> Saving...').prop('disabled', true);
    
    // Send AJAX request
    $.ajax({
        url: 'api/quick-add-master.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            if (response.success) {
                // Refresh the dropdown
                refreshMasterDropdown(masterType, response.data);
                
                // Close modal
                $('#quickAddModal').modal('hide');
                
                // Show success message
                showNotification('success', response.message || `${masterType} added successfully!`);
            } else {
                alert('Error: ' + (response.message || 'Unknown error occurred'));
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', error);
            alert('Error saving data. Please try again.');
        },
        complete: function() {
            saveBtn.html(originalText).prop('disabled', false);
        }
    });
}

function refreshMasterDropdown(masterType, newData) {
    const selectMap = {
        'unit': '#unitID',
        'category': '#categoryID',
        'brand': '#brandID',
        'tax': '#taxID',
        'location': '#locationID',
        'rack': '#rackID'
    };
    
    const selectId = selectMap[masterType];
    if (!selectId) return;
    
    // Add new option to dropdown
    const $select = $(selectId);
    let optionText = '';
    let optionValue = newData.ID;
    
    switch(masterType) {
        case 'unit':
            optionText = newData.UnitName;
            masterData.units.push(newData);
            break;
        case 'category':
            optionText = newData.CategoryName;
            masterData.categories.push(newData);
            break;
        case 'brand':
            optionText = newData.BrandName;
            masterData.brands.push(newData);
            break;
        case 'tax':
            optionText = `${newData.TaxName} (${newData.TaxRate}%)`;
            masterData.taxes.push(newData);
            break;
        case 'location':
            optionText = newData.LocationName;
            masterData.locations.push(newData);
            break;
        case 'rack':
            optionText = newData.RackName;
            masterData.racks.push(newData);
            break;
    }
    
    // Add and select the new option
    $select.append(`<option value="${optionValue}">${optionText}</option>`);
    $select.val(optionValue);
}

function showNotification(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    const notification = `
        <div class="alert ${alertClass} alert-dismissible fade show notification-toast" role="alert" style="position: fixed; top: 80px; right: 20px; z-index: 9999; min-width: 300px;">
            <i class="fas ${icon} mr-2"></i>${message}
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    `;
    
    $('body').append(notification);
    
    setTimeout(function() {
        $('.notification-toast').fadeOut(300, function() {
            $(this).remove();
        });
    }, 3000);
}
