// Stock Control Module

let currentEditingStock = null;

const stockCategories = ['therapy gadget', 'consumable'];

function loadStockData() {
    // First, add the stock section to the HTML if it doesn't exist
    addStockSection();
    
    const stockTableBody = document.querySelector('#stock-table tbody');
    const stock = window.app.getData('stock');
    
    // Sort stock by date (most recent first)
    const sortedStock = stock.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    stockTableBody.innerHTML = sortedStock.map(item => `
        <tr>
            <td>${window.app.formatDate(item.date)}</td>
            <td>${item.itemName}</td>
            <td>${item.category}</td>
            <td>${item.quantityReceived || 0}</td>
            <td>${item.receivedBy || '-'}</td>
            <td>${item.quantityIssued || 0}</td>
            <td>${item.issuedTo || '-'}</td>
            <td>${item.balance}</td>
            <td>${item.signature ? '<i class="fas fa-check-circle text-success"></i>' : '<i class="fas fa-times-circle text-danger"></i>'}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editStock(${item.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteStock(${item.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');

    // Setup category filter
    const categoryFilter = document.getElementById('stock-category-filter');
    if (categoryFilter) {
        categoryFilter.addEventListener('change', filterStockByCategory);
    }

    // Load stock summary
    loadStockSummary();
}

function addStockSection() {
    const stockSection = document.getElementById('stock');
    if (stockSection && !stockSection.querySelector('#stock-table')) {
        stockSection.innerHTML = `
            <div class="section-header">
                <h2>Stock Control</h2>
                <div class="header-actions">
                    <button class="btn btn-primary" onclick="showStockModal()">
                        <i class="fas fa-plus"></i> Add Stock Entry
                    </button>
                    <button class="btn btn-success" onclick="showReceiveStockModal()">
                        <i class="fas fa-truck"></i> Receive Stock
                    </button>
                    <button class="btn btn-warning" onclick="showIssueStockModal()">
                        <i class="fas fa-hand-holding"></i> Issue Stock
                    </button>
                </div>
            </div>
            
            <div class="filters">
                <select id="stock-category-filter">
                    <option value="">All Categories</option>
                    <option value="therapy gadget">Therapy Gadget</option>
                    <option value="consumable">Consumable</option>
                </select>
                <input type="text" id="stock-search" placeholder="Search items..." class="search-input">
                <button class="btn btn-secondary" onclick="exportStock()">
                    <i class="fas fa-download"></i> Export Stock
                </button>
            </div>

            <div class="table-container">
                <table id="stock-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Item Name</th>
                            <th>Category</th>
                            <th>Qty Received</th>
                            <th>Received By</th>
                            <th>Qty Issued</th>
                            <th>Issued To</th>
                            <th>Balance</th>
                            <th>Signature</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Stock data will be populated here -->
                    </tbody>
                </table>
            </div>

            <div id="stock-summary" class="stock-summary">
                <h3>Stock Summary</h3>
                <div class="summary-grid">
                    <div class="summary-card">
                        <h4>Total Items</h4>
                        <div class="summary-amount" id="total-items">0</div>
                    </div>
                    <div class="summary-card">
                        <h4>Low Stock Items</h4>
                        <div class="summary-amount" id="low-stock-items">0</div>
                    </div>
                    <div class="summary-card">
                        <h4>Out of Stock</h4>
                        <div class="summary-amount" id="out-of-stock-items">0</div>
                    </div>
                </div>
                <div class="stock-alerts" id="stock-alerts">
                    <!-- Stock alerts will be populated here -->
                </div>
            </div>
        `;
    }
}

function filterStockByCategory() {
    applyStockFilters();
}

function applyStockFilters() {
    const categoryFilter = document.getElementById('stock-category-filter').value;
    const searchFilter = document.getElementById('stock-search').value.toLowerCase();
    const stock = window.app.getData('stock');
    
    let filteredStock = stock;
    
    // Apply category filter
    if (categoryFilter) {
        filteredStock = filteredStock.filter(item => item.category === categoryFilter);
    }
    
    // Apply search filter
    if (searchFilter) {
        filteredStock = filteredStock.filter(item => 
            item.itemName.toLowerCase().includes(searchFilter) ||
            item.receivedBy?.toLowerCase().includes(searchFilter) ||
            item.issuedTo?.toLowerCase().includes(searchFilter)
        );
    }
    
    // Update table
    const stockTableBody = document.querySelector('#stock-table tbody');
    const sortedStock = filteredStock.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    stockTableBody.innerHTML = sortedStock.map(item => `
        <tr>
            <td>${window.app.formatDate(item.date)}</td>
            <td>${item.itemName}</td>
            <td>${item.category}</td>
            <td>${item.quantityReceived || 0}</td>
            <td>${item.receivedBy || '-'}</td>
            <td>${item.quantityIssued || 0}</td>
            <td>${item.issuedTo || '-'}</td>
            <td>${item.balance}</td>
            <td>${item.signature ? '<i class="fas fa-check-circle text-success"></i>' : '<i class="fas fa-times-circle text-danger"></i>'}</td>
            <td>
                <button class="btn btn-sm btn-warning" onclick="editStock(${item.id})">
                    <i class="fas fa-edit"></i> Edit
                </button>
                <button class="btn btn-sm btn-danger" onclick="deleteStock(${item.id})">
                    <i class="fas fa-trash"></i> Delete
                </button>
            </td>
        </tr>
    `).join('');
}

function showStockModal(stockId = null) {
    const stock = stockId ? window.app.getData('stock').find(s => s.id === stockId) : null;
    const isEdit = !!stock;
    
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>${isEdit ? 'Edit Stock Entry' : 'Add New Stock Entry'}</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="stock-form">
                    <div class="form-group">
                        <label for="stock-date">Date *</label>
                        <input type="date" id="stock-date" name="date" required 
                               value="${stock ? stock.date : new Date().toISOString().split('T')[0]}">
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-item-name">Item Name *</label>
                        <input type="text" id="stock-item-name" name="itemName" required 
                               value="${stock ? stock.itemName : ''}" 
                               placeholder="Enter item name"
                               list="existing-items">
                        <datalist id="existing-items">
                            ${getExistingItemNames()}
                        </datalist>
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-category">Category *</label>
                        <select id="stock-category" name="category" required>
                            <option value="">Select Category</option>
                            <option value="therapy gadget" ${stock && stock.category === 'therapy gadget' ? 'selected' : ''}>Therapy Gadget</option>
                            <option value="consumable" ${stock && stock.category === 'consumable' ? 'selected' : ''}>Consumable</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-qty-received">Quantity Received</label>
                        <input type="number" id="stock-qty-received" name="quantityReceived" min="0"
                               value="${stock ? stock.quantityReceived || '' : ''}" 
                               placeholder="Enter quantity received">
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-received-by">Received By</label>
                        <input type="text" id="stock-received-by" name="receivedBy" 
                               value="${stock ? stock.receivedBy || '' : ''}" 
                               placeholder="Person who received the stock">
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-qty-issued">Quantity Issued</label>
                        <input type="number" id="stock-qty-issued" name="quantityIssued" min="0"
                               value="${stock ? stock.quantityIssued || '' : ''}" 
                               placeholder="Enter quantity issued">
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-issued-to">Issued To</label>
                        <input type="text" id="stock-issued-to" name="issuedTo" 
                               value="${stock ? stock.issuedTo || '' : ''}" 
                               placeholder="Person who received the issue">
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-balance">Current Balance *</label>
                        <input type="number" id="stock-balance" name="balance" required min="0"
                               value="${stock ? stock.balance : ''}" 
                               placeholder="Current stock balance">
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-min-level">Minimum Level</label>
                        <input type="number" id="stock-min-level" name="minLevel" min="0"
                               value="${stock ? stock.minLevel || '' : ''}" 
                               placeholder="Minimum stock level for alerts">
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-location">Storage Location</label>
                        <input type="text" id="stock-location" name="location" 
                               value="${stock ? stock.location || '' : ''}" 
                               placeholder="Where the item is stored">
                    </div>
                    
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="stock-signature" name="signature" 
                                   ${stock && stock.signature ? 'checked' : ''}>
                            Signature Verified
                        </label>
                    </div>
                    
                    <div class="form-group">
                        <label for="stock-notes">Notes</label>
                        <textarea id="stock-notes" name="notes" rows="3" 
                                  placeholder="Additional notes about the stock entry">${stock ? stock.notes || '' : ''}</textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveStock(${stockId})">
                    <i class="fas fa-save"></i> ${isEdit ? 'Update' : 'Add'} Stock
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
    currentEditingStock = stockId;
    
    // Setup auto-calculation for balance
    setupStockCalculations();
    
    // Setup search functionality
    setupStockSearch();
}

function getExistingItemNames() {
    const stock = window.app.getData('stock');
    const uniqueItems = [...new Set(stock.map(item => item.itemName))];
    return uniqueItems.map(name => `<option value="${name}">`).join('');
}

function setupStockCalculations() {
    const receivedInput = document.getElementById('stock-qty-received');
    const issuedInput = document.getElementById('stock-qty-issued');
    const balanceInput = document.getElementById('stock-balance');
    const itemNameInput = document.getElementById('stock-item-name');
    
    function updateBalance() {
        const itemName = itemNameInput.value;
        const received = parseInt(receivedInput.value || 0);
        const issued = parseInt(issuedInput.value || 0);
        
        // Get previous balance for this item
        const stock = window.app.getData('stock');
        const existingItems = stock.filter(item => item.itemName === itemName);
        const previousBalance = existingItems.length > 0 ? 
            Math.max(...existingItems.map(item => item.balance || 0)) : 0;
        
        const newBalance = previousBalance + received - issued;
        balanceInput.value = Math.max(0, newBalance);
    }
    
    receivedInput.addEventListener('input', updateBalance);
    issuedInput.addEventListener('input', updateBalance);
    itemNameInput.addEventListener('input', updateBalance);
}

function setupStockSearch() {
    const searchInput = document.getElementById('stock-search');
    if (searchInput) {
        searchInput.addEventListener('input', applyStockFilters);
    }
}

function showReceiveStockModal() {
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>Receive Stock</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="receive-stock-form">
                    <div class="form-group">
                        <label for="receive-date">Date *</label>
                        <input type="date" id="receive-date" name="date" required 
                               value="${new Date().toISOString().split('T')[0]}">
                    </div>
                    
                    <div class="form-group">
                        <label for="receive-item-name">Item Name *</label>
                        <input type="text" id="receive-item-name" name="itemName" required 
                               placeholder="Enter item name" list="existing-items">
                        <datalist id="existing-items">
                            ${getExistingItemNames()}
                        </datalist>
                    </div>
                    
                    <div class="form-group">
                        <label for="receive-category">Category *</label>
                        <select id="receive-category" name="category" required>
                            <option value="">Select Category</option>
                            <option value="therapy gadget">Therapy Gadget</option>
                            <option value="consumable">Consumable</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="receive-quantity">Quantity Received *</label>
                        <input type="number" id="receive-quantity" name="quantityReceived" required min="1"
                               placeholder="Enter quantity received">
                    </div>
                    
                    <div class="form-group">
                        <label for="receive-received-by">Received By *</label>
                        <input type="text" id="receive-received-by" name="receivedBy" required
                               placeholder="Person who received the stock">
                    </div>
                    
                    <div class="form-group">
                        <label for="receive-supplier">Supplier</label>
                        <input type="text" id="receive-supplier" name="supplier" 
                               placeholder="Supplier name">
                    </div>
                    
                    <div class="form-group">
                        <label for="receive-notes">Notes</label>
                        <textarea id="receive-notes" name="notes" rows="3" 
                                  placeholder="Additional notes about the delivery"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-success" onclick="saveReceiveStock()">
                    <i class="fas fa-truck"></i> Receive Stock
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
}

function showIssueStockModal() {
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>Issue Stock</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="issue-stock-form">
                    <div class="form-group">
                        <label for="issue-date">Date *</label>
                        <input type="date" id="issue-date" name="date" required 
                               value="${new Date().toISOString().split('T')[0]}">
                    </div>
                    
                    <div class="form-group">
                        <label for="issue-item-name">Item Name *</label>
                        <select id="issue-item-name" name="itemName" required>
                            <option value="">Select Item</option>
                            ${getAvailableItemsForIssue()}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="issue-available">Available Quantity</label>
                        <input type="number" id="issue-available" name="availableQty" readonly 
                               placeholder="Available quantity will be shown here">
                    </div>
                    
                    <div class="form-group">
                        <label for="issue-quantity">Quantity to Issue *</label>
                        <input type="number" id="issue-quantity" name="quantityIssued" required min="1"
                               placeholder="Enter quantity to issue">
                    </div>
                    
                    <div class="form-group">
                        <label for="issue-issued-to">Issued To *</label>
                        <input type="text" id="issue-issued-to" name="issuedTo" required
                               placeholder="Person receiving the stock">
                    </div>
                    
                    <div class="form-group">
                        <label for="issue-purpose">Purpose</label>
                        <input type="text" id="issue-purpose" name="purpose" 
                               placeholder="Purpose of issue (e.g., Patient therapy, Maintenance)">
                    </div>
                    
                    <div class="form-group">
                        <label for="issue-notes">Notes</label>
                        <textarea id="issue-notes" name="notes" rows="3" 
                                  placeholder="Additional notes about the issue"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-warning" onclick="saveIssueStock()">
                    <i class="fas fa-hand-holding"></i> Issue Stock
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
    
    // Setup item selection handler
    document.getElementById('issue-item-name').addEventListener('change', function() {
        const itemName = this.value;
        if (itemName) {
            const stock = window.app.getData('stock');
            const itemEntries = stock.filter(item => item.itemName === itemName);
            const currentBalance = itemEntries.length > 0 ? 
                Math.max(...itemEntries.map(item => item.balance || 0)) : 0;
            document.getElementById('issue-available').value = currentBalance;
            document.getElementById('issue-quantity').max = currentBalance;
        }
    });
}

function getAvailableItemsForIssue() {
    const stock = window.app.getData('stock');
    const itemBalances = {};
    
    // Calculate current balance for each item
    stock.forEach(item => {
        if (!itemBalances[item.itemName]) {
            itemBalances[item.itemName] = { balance: 0, category: item.category };
        }
        itemBalances[item.itemName].balance = Math.max(itemBalances[item.itemName].balance, item.balance || 0);
    });
    
    // Return only items with positive balance
    return Object.entries(itemBalances)
        .filter(([name, data]) => data.balance > 0)
        .map(([name, data]) => `<option value="${name}">${name} (${data.balance} available)</option>`)
        .join('');
}

function saveStock(stockId) {
    const form = document.getElementById('stock-form');
    const formData = new FormData(form);
    
    // Validate required fields
    const requiredFields = ['date', 'itemName', 'category', 'balance'];
    for (const field of requiredFields) {
        if (!formData.get(field)) {
            window.app.showNotification(`Please fill in the ${field.replace(/([A-Z])/g, ' $1').toLowerCase()} field`, 'error');
            return;
        }
    }
    
    const stockData = {
        id: stockId || window.app.generateId('stock'),
        date: formData.get('date'),
        itemName: formData.get('itemName'),
        category: formData.get('category'),
        quantityReceived: parseInt(formData.get('quantityReceived') || 0),
        receivedBy: formData.get('receivedBy') || '',
        quantityIssued: parseInt(formData.get('quantityIssued') || 0),
        issuedTo: formData.get('issuedTo') || '',
        balance: parseInt(formData.get('balance')),
        minLevel: parseInt(formData.get('minLevel') || 0),
        location: formData.get('location') || '',
        signature: formData.get('signature') === 'on',
        notes: formData.get('notes') || '',
        createdAt: stockId ? undefined : new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    
    let stock = window.app.getData('stock');
    
    if (stockId) {
        // Update existing stock
        const index = stock.findIndex(s => s.id === stockId);
        if (index !== -1) {
            stock[index] = { ...stock[index], ...stockData };
        }
    } else {
        // Add new stock
        stock.push(stockData);
    }
    
    window.app.saveData('stock', stock);
    window.app.closeModal();
    loadStockData();
    
    window.app.showNotification(
        `Stock ${stockId ? 'updated' : 'added'} successfully!`,
        'success'
    );
}

function saveReceiveStock() {
    const form = document.getElementById('receive-stock-form');
    const formData = new FormData(form);
    
    // Validate required fields
    const requiredFields = ['date', 'itemName', 'category', 'quantityReceived', 'receivedBy'];
    for (const field of requiredFields) {
        if (!formData.get(field)) {
            window.app.showNotification(`Please fill in the ${field.replace(/([A-Z])/g, ' $1').toLowerCase()} field`, 'error');
            return;
        }
    }
    
    const itemName = formData.get('itemName');
    const quantityReceived = parseInt(formData.get('quantityReceived'));
    
    // Get current balance for this item
    const stock = window.app.getData('stock');
    const existingItems = stock.filter(item => item.itemName === itemName);
    const currentBalance = existingItems.length > 0 ? 
        Math.max(...existingItems.map(item => item.balance || 0)) : 0;
    
    const stockData = {
        id: window.app.generateId('stock'),
        date: formData.get('date'),
        itemName: itemName,
        category: formData.get('category'),
        quantityReceived: quantityReceived,
        receivedBy: formData.get('receivedBy'),
        quantityIssued: 0,
        issuedTo: '',
        balance: currentBalance + quantityReceived,
        signature: true,
        notes: formData.get('notes') || `Stock received from ${formData.get('supplier') || 'supplier'}`,
        supplier: formData.get('supplier') || '',
        createdAt: new Date().toISOString()
    };
    
    stock.push(stockData);
    window.app.saveData('stock', stock);
    window.app.closeModal();
    loadStockData();
    
    window.app.showNotification('Stock received successfully!', 'success');
}

function saveIssueStock() {
    const form = document.getElementById('issue-stock-form');
    const formData = new FormData(form);
    
    // Validate required fields
    const requiredFields = ['date', 'itemName', 'quantityIssued', 'issuedTo'];
    for (const field of requiredFields) {
        if (!formData.get(field)) {
            window.app.showNotification(`Please fill in the ${field.replace(/([A-Z])/g, ' $1').toLowerCase()} field`, 'error');
            return;
        }
    }
    
    const itemName = formData.get('itemName');
    const quantityIssued = parseInt(formData.get('quantityIssued'));
    const availableQty = parseInt(document.getElementById('issue-available').value);
    
    if (quantityIssued > availableQty) {
        window.app.showNotification('Quantity to issue cannot exceed available quantity', 'error');
        return;
    }
    
    // Get current balance and category for this item
    const stock = window.app.getData('stock');
    const existingItems = stock.filter(item => item.itemName === itemName);
    const currentBalance = existingItems.length > 0 ? 
        Math.max(...existingItems.map(item => item.balance || 0)) : 0;
    const category = existingItems.length > 0 ? existingItems[0].category : 'consumable';
    
    const stockData = {
        id: window.app.generateId('stock'),
        date: formData.get('date'),
        itemName: itemName,
        category: category,
        quantityReceived: 0,
        receivedBy: '',
        quantityIssued: quantityIssued,
        issuedTo: formData.get('issuedTo'),
        balance: currentBalance - quantityIssued,
        signature: true,
        notes: formData.get('notes') || `Stock issued for ${formData.get('purpose') || 'use'}`,
        purpose: formData.get('purpose') || '',
        createdAt: new Date().toISOString()
    };
    
    stock.push(stockData);
    window.app.saveData('stock', stock);
    window.app.closeModal();
    loadStockData();
    
    window.app.showNotification('Stock issued successfully!', 'success');
}

function editStock(stockId) {
    showStockModal(stockId);
}

function deleteStock(stockId) {
    const stockItem = window.app.getData('stock').find(s => s.id === stockId);
    if (confirm(`Are you sure you want to delete this stock entry for ${stockItem?.itemName}? This action cannot be undone.`)) {
        let stock = window.app.getData('stock');
        stock = stock.filter(s => s.id !== stockId);
        window.app.saveData('stock', stock);
        loadStockData();
        window.app.showNotification('Stock entry deleted successfully!', 'success');
    }
}

function loadStockSummary() {
    const stock = window.app.getData('stock');
    
    // Get unique items with their current balances
    const itemBalances = {};
    stock.forEach(item => {
        if (!itemBalances[item.itemName]) {
            itemBalances[item.itemName] = { balance: 0, minLevel: 0 };
        }
        itemBalances[item.itemName].balance = Math.max(itemBalances[item.itemName].balance, item.balance || 0);
        itemBalances[item.itemName].minLevel = item.minLevel || 0;
    });
    
    const totalItems = Object.keys(itemBalances).length;
    const lowStockItems = Object.values(itemBalances).filter(item => 
        item.balance > 0 && item.balance <= item.minLevel && item.minLevel > 0
    ).length;
    const outOfStockItems = Object.values(itemBalances).filter(item => item.balance === 0).length;
    
    document.getElementById('total-items').textContent = totalItems;
    document.getElementById('low-stock-items').textContent = lowStockItems;
    document.getElementById('out-of-stock-items').textContent = outOfStockItems;
    
    // Generate stock alerts
    const alertsContainer = document.getElementById('stock-alerts');
    const alerts = [];
    
    Object.entries(itemBalances).forEach(([itemName, data]) => {
        if (data.balance === 0) {
            alerts.push({ type: 'danger', message: `${itemName} is out of stock` });
        } else if (data.balance <= data.minLevel && data.minLevel > 0) {
            alerts.push({ type: 'warning', message: `${itemName} is running low (${data.balance} remaining)` });
        }
    });
    
    if (alerts.length === 0) {
        alertsContainer.innerHTML = '<div class="alert-success">All items are adequately stocked</div>';
    } else {
        alertsContainer.innerHTML = `
            <h4>Stock Alerts</h4>
            ${alerts.map(alert => `
                <div class="alert-${alert.type}">
                    <i class="fas fa-${alert.type === 'danger' ? 'exclamation-triangle' : 'exclamation-circle'}"></i>
                    ${alert.message}
                </div>
            `).join('')}
        `;
    }
}

function exportStock() {
    const stock = window.app.getData('stock');
    
    if (stock.length === 0) {
        window.app.showNotification('No stock entries to export', 'error');
        return;
    }
    
    const exportData = stock.map(item => ({
        'Date': item.date,
        'Item Name': item.itemName,
        'Category': item.category,
        'Quantity Received': item.quantityReceived || 0,
        'Received By': item.receivedBy || '',
        'Quantity Issued': item.quantityIssued || 0,
        'Issued To': item.issuedTo || '',
        'Balance': item.balance,
        'Minimum Level': item.minLevel || '',
        'Location': item.location || '',
        'Signature': item.signature ? 'Yes' : 'No',
        'Notes': item.notes || ''
    }));
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(exportData, `stock-${currentDate}.csv`);
    window.app.showNotification('Stock exported successfully!', 'success');
}

// Add CSS for stock styles
const stockStyles = `
    <style>
        .stock-summary {
            background: var(--white);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            margin-top: 2rem;
        }
        
        .stock-summary h3 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
        }
        
        .header-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        .search-input {
            padding: 0.75rem;
            border: 2px solid var(--medium-gray);
            border-radius: var(--border-radius);
            font-size: 1rem;
            min-width: 200px;
        }
        
        .search-input:focus {
            outline: none;
            border-color: var(--primary-teal);
        }
        
        .stock-alerts {
            margin-top: 1rem;
        }
        
        .stock-alerts h4 {
            color: var(--primary-teal);
            margin-bottom: 0.75rem;
        }
        
        .alert-success, .alert-warning, .alert-danger {
            padding: 0.75rem 1rem;
            border-radius: var(--border-radius);
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .alert-success {
            background: rgba(76, 175, 80, 0.1);
            color: var(--success);
            border-left: 4px solid var(--success);
        }
        
        .alert-warning {
            background: rgba(255, 152, 0, 0.1);
            color: var(--warning);
            border-left: 4px solid var(--warning);
        }
        
        .alert-danger {
            background: rgba(244, 67, 54, 0.1);
            color: var(--error);
            border-left: 4px solid var(--error);
        }
        
        @media (max-width: 768px) {
            .header-actions {
                flex-direction: column;
            }
            
            .filters {
                flex-direction: column;
                gap: 0.5rem;
            }
        }
    </style>
`;

document.head.insertAdjacentHTML('beforeend', stockStyles);
