/**
 * Stock Report - Excel-like Editable Grid
 * Handles inline editing and AJAX updates
 */

let stockTable;
let originalCellValue = null;
let isEditing = false;

$(document).ready(function() {
    // Initialize DataTable
    initializeDataTable();
    
    // Attach editable cell handlers (using event delegation)
    attachEditableCellHandlers();
    
    // Load stock data
    loadStockData();
    
    // Event Handlers
    setupEventHandlers();
});

/**
 * Initialize DataTable with configurations
 */
function initializeDataTable() {
    stockTable = $('#stockTable').DataTable({
        "pageLength": 25,
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "order": [[1, "asc"]], // Sort by Item Name
        "responsive": true,
        "autoWidth": false,
        "language": {
            "search": "Search Stock:",
            "lengthMenu": "Show _MENU_ items",
            "info": "Showing _START_ to _END_ of _TOTAL_ items",
            "infoEmpty": "No items found",
            "infoFiltered": "(filtered from _TOTAL_ total items)",
            "zeroRecords": "No matching items found",
            "emptyTable": "No stock data available"
        },
        "columnDefs": [
            { "className": "text-center", "targets": [0, 2, 3, 4, 8, 9, 18, 19] },
            { "className": "text-right", "targets": [10, 11, 12, 13, 14, 15, 16, 17] }
        ]
    });
}

/**
 * Load stock data from API
 */
function loadStockData(filters = {}) {
    showLoading();
    
    // Build query parameters
    let params = new URLSearchParams(filters);
    
    $.ajax({
        url: 'api/get-stock-report.php?' + params.toString(),
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            hideLoading();
            
            if (response.success) {
                populateTable(response.items);
                updateTotals(response.totals);
                
                if (response.items.length === 0) {
                    showAlert('info', 'No items found matching the filters.');
                }
            } else {
                showAlert('danger', 'Error: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            hideLoading();
            showAlert('danger', 'Failed to load stock data: ' + error);
        }
    });
}

/**
 * Populate table with stock data
 */
function populateTable(items) {
    stockTable.clear();
    
    items.forEach(function(item) {
        let stockStatusClass = getStockStatusClass(item.stockStatus);
        let statusBadgeClass = item.status.toLowerCase();
        
        let row = [
            item.itemCode,
            `<span class="editable-cell editable-text" data-field="ItemName" data-item-id="${item.id}" data-tooltip="Click to edit">${item.itemName}</span>`,
            item.category,
            item.brand,
            `${item.unit} <small>(${item.unitSymbol})</small>`,
            `<span class="editable-cell editable-text" data-field="SKU" data-item-id="${item.id}" data-tooltip="Click to edit">${item.sku || 'N/A'}</span>`,
            `<span class="editable-cell editable-text" data-field="Barcode" data-item-id="${item.id}" data-tooltip="Click to edit">${item.barcode || 'N/A'}</span>`,
            `<span class="editable-cell editable-text" data-field="HSN" data-item-id="${item.id}" data-tooltip="Click to edit">${item.hsn || 'N/A'}</span>`,
            item.location,
            item.rack,
            `<span class="editable-cell" data-field="CurrentStock" data-item-id="${item.id}" data-tooltip="Click to edit">${item.currentStock}</span>`,
            `<span class="editable-cell" data-field="AlertQuantity" data-item-id="${item.id}" data-tooltip="Click to edit">${item.alertQuantity}</span>`,
            `<span class="editable-cell" data-field="PurchasePrice" data-item-id="${item.id}" data-tooltip="Click to edit">₹${item.purchasePrice}</span>`,
            `<span class="editable-cell" data-field="SalesPrice" data-item-id="${item.id}" data-tooltip="Click to edit">₹${item.salesPrice}</span>`,
            `<span class="editable-cell" data-field="ShopRate" data-item-id="${item.id}" data-tooltip="Click to edit">₹${item.shopRate}</span>`,
            `<span class="editable-cell" data-field="WholesaleRate" data-item-id="${item.id}" data-tooltip="Click to edit">₹${item.wholesaleRate}</span>`,
            `<span class="editable-cell" data-field="MRP" data-item-id="${item.id}" data-tooltip="Click to edit">₹${item.mrp}</span>`,
            `₹${item.stockValue}`,
            `<span class="stock-status ${stockStatusClass}">${item.stockStatus}</span>`,
            `<div class="action-btns">
                <button class="btn btn-info btn-sm view-details" data-id="${item.id}" title="View Details">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-danger btn-sm delete-item" data-id="${item.id}" data-name="${item.itemName}" title="Delete Item">
                    <i class="fas fa-trash"></i>
                </button>
            </div>`
        ];
        
        stockTable.row.add(row);
    });
    
    stockTable.draw();
}

/**
 * Attach click handlers to editable cells
 */
function attachEditableCellHandlers() {
    // Use event delegation for better performance
    $('#stockTable tbody').off('click', '.editable-cell').on('click', '.editable-cell', function(e) {
        if (isEditing) return; // Prevent multiple edits at once
        
        let $cell = $(this);
        let field = $cell.data('field');
        let itemId = $cell.data('item-id');
        let currentValue = $cell.text().replace('₹', '').replace(/,/g, '').trim();
        
        makeEditable($cell, field, itemId, currentValue);
    });
}

/**
 * Make a cell editable
 */
function makeEditable($cell, field, itemId, currentValue) {
    isEditing = true;
    originalCellValue = currentValue;
    
    // Determine if field is text or numeric
    let isTextField = $cell.hasClass('editable-text');
    let fieldType = isTextField ? 'text' : 'number';
    
    // Create input element
    let inputConfig = {
        type: fieldType,
        value: currentValue,
        class: 'form-control form-control-sm'
    };
    
    // Add numeric attributes for number fields
    if (!isTextField) {
        inputConfig.step = '0.01';
        inputConfig.min = '0';
    }
    
    let $input = $('<input>', inputConfig);
    
    // Replace cell content with input
    $cell.addClass('editing').html($input);
    $input.focus().select();
    
    // Save on Enter or blur
    $input.on('keydown', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveEdit($cell, field, itemId, $input.val(), isTextField);
        } else if (e.key === 'Escape') {
            cancelEdit($cell, isTextField);
        }
    });
    
    $input.on('blur', function() {
        if (isEditing) {
            let newValue = $input.val();
            if (newValue !== originalCellValue) {
                saveEdit($cell, field, itemId, newValue, isTextField);
            } else {
                cancelEdit($cell, isTextField);
            }
        }
    });
}

/**
 * Save edited value to database
 */
function saveEdit($cell, field, itemId, newValue, isTextField) {
    // Validate input
    if (isTextField) {
        // Text field validation
        if (newValue.trim() === '') {
            showAlert('warning', 'Value cannot be empty.');
            cancelEdit($cell, isTextField);
            return;
        }
        newValue = newValue.trim();
    } else {
        // Numeric field validation
        if (newValue === '' || isNaN(newValue) || parseFloat(newValue) < 0) {
            showAlert('warning', 'Please enter a valid positive number.');
            cancelEdit($cell, isTextField);
            return;
        }
        newValue = parseFloat(newValue);
    }
    
    // Show loading in cell
    $cell.html('<i class="fas fa-spinner fa-spin"></i>');
    
    // Send AJAX request
    $.ajax({
        url: 'api/update-stock.php',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            itemId: itemId,
            field: field,
            value: newValue
        }),
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Update cell with new value
                let displayValue = isTextField ? newValue : newValue.toFixed(2);
                if (!isTextField && field.includes('Price')) {
                    displayValue = '₹' + displayValue;
                }
                
                $cell.removeClass('editing').html(displayValue).addClass('cell-changed');
                
                // Remove animation class after animation completes
                setTimeout(() => $cell.removeClass('cell-changed'), 1000);
                
                // Update totals if numeric field
                if (!isTextField) {
                    recalculateTotals();
                }
                
                showAlert('success', `${field} updated successfully`);
                
                isEditing = false;
            } else {
                showAlert('danger', 'Error: ' + response.message);
                cancelEdit($cell, isTextField);
            }
        },
        error: function(xhr, status, error) {
            showAlert('danger', 'Failed to update: ' + error);
            cancelEdit($cell, isTextField);
        }
    });
}

/**
 * Cancel editing
 */
function cancelEdit($cell, isTextField) {
    let displayValue = originalCellValue;
    if (!isTextField && $cell.data('field').includes('Price')) {
        displayValue = '₹' + originalCellValue;
    }
    
    $cell.removeClass('editing').html(displayValue);
    isEditing = false;
    originalCellValue = null;
}

/**
 * Recalculate totals from current table data
 */
function recalculateTotals() {
    let totalStock = 0;
    let totalValue = 0;
    
    stockTable.rows().every(function() {
        let data = this.data();
        if (data && data.length > 0) {
            // Extract numeric values
            let stock = parseFloat($(data[7]).text().replace(/,/g, ''));
            let purchasePrice = parseFloat($(data[9]).text().replace('₹', '').replace(/,/g, ''));
            
            if (!isNaN(stock)) totalStock += stock;
            if (!isNaN(stock) && !isNaN(purchasePrice)) {
                totalValue += stock * purchasePrice;
            }
        }
    });
    
    updateTotals({
        totalStock: totalStock.toFixed(2),
        totalValue: totalValue.toFixed(2)
    });
}

/**
 * Update footer totals
 */
function updateTotals(totals) {
    $('#totalStock').text(parseFloat(totals.totalStock).toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }));
    
    $('#totalValue').text('₹' + parseFloat(totals.totalValue).toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }));
}

/**
 * Get stock status CSS class
 */
function getStockStatusClass(status) {
    switch(status) {
        case 'In Stock':
            return 'in-stock';
        case 'Low Stock':
            return 'low-stock';
        case 'Out of Stock':
            return 'out-of-stock';
        default:
            return '';
    }
}

/**
 * Setup event handlers
 */
function setupEventHandlers() {
    // Refresh button
    $('#refreshBtn').on('click', function() {
        applyFilters();
    });
    
    // Export to Excel
    $('#exportExcel').on('click', function() {
        exportToExcel();
    });
    
    // Filter changes
    $('#searchInput, #categoryFilter, #brandFilter, #locationFilter, #stockStatusFilter').on('change', function() {
        applyFilters();
    });
    
    // Clear filters
    $('#clearFilters').on('click', function() {
        $('#searchInput').val('');
        $('#categoryFilter').val('');
        $('#brandFilter').val('');
        $('#locationFilter').val('');
        $('#stockStatusFilter').val('');
        applyFilters();
    });
    
    // View details button (delegated event)
    $(document).on('click', '.view-details', function() {
        let itemId = $(this).data('id');
        window.location.href = 'add-item.php?id=' + itemId;
    });
    
    // Delete item button (delegated event)
    $(document).on('click', '.delete-item', function() {
        let itemId = $(this).data('id');
        let itemName = $(this).data('name');
        deleteItem(itemId, itemName);
    });
}

/**
 * Delete an item with confirmation
 */
function deleteItem(itemId, itemName) {
    if (confirm(`Are you sure you want to delete "${itemName}"?\n\nThis action cannot be undone!`)) {
        showLoading();
        
        $.ajax({
            url: 'api/delete-item.php',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                itemId: itemId
            }),
            dataType: 'json',
            success: function(response) {
                hideLoading();
                
                if (response.success) {
                    showAlert('success', `"${itemName}" deleted successfully`);
                    // Reload the data
                    applyFilters();
                } else {
                    showAlert('danger', 'Error: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                hideLoading();
                showAlert('danger', 'Failed to delete item: ' + error);
            }
        });
    }
}

/**
 * Apply filters and reload data
 */
function applyFilters() {
    let filters = {
        search: $('#searchInput').val(),
        category: $('#categoryFilter').val(),
        brand: $('#brandFilter').val(),
        location: $('#locationFilter').val(),
        stockStatus: $('#stockStatusFilter').val()
    };
    
    loadStockData(filters);
}

/**
 * Export table to Excel
 */
function exportToExcel() {
    // Get table data
    let data = [];
    
    // Headers
    let headers = [];
    $('#stockTable thead th').each(function(index) {
        if (index < 14) { // Exclude Actions column
            headers.push($(this).text().replace(' ✎', '').trim());
        }
    });
    data.push(headers);
    
    // Rows
    stockTable.rows().every(function() {
        let rowData = this.data();
        let row = [];
        
        for (let i = 0; i < 14; i++) {
            let cellValue = rowData[i];
            
            // Clean HTML tags and extract text
            let $temp = $('<div>').html(cellValue);
            let text = $temp.text().trim().replace(/\s+/g, ' ');
            
            // Remove currency symbols for numeric columns
            if (i >= 9 && i <= 12) {
                text = text.replace('₹', '').trim();
            }
            
            row.push(text);
        }
        
        data.push(row);
    });
    
    // Create CSV
    let csv = data.map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');
    
    // Download
    let blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    let link = document.createElement('a');
    let url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', 'stock_report_' + new Date().toISOString().slice(0, 10) + '.csv');
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    showAlert('success', 'Stock report exported successfully!');
}

/**
 * Show alert message
 */
function showAlert(type, message) {
    let alertClass = 'alert-' + type;
    let iconClass = '';
    
    switch(type) {
        case 'success':
            iconClass = 'fa-check-circle';
            break;
        case 'danger':
            iconClass = 'fa-exclamation-circle';
            break;
        case 'warning':
            iconClass = 'fa-exclamation-triangle';
            break;
        case 'info':
            iconClass = 'fa-info-circle';
            break;
    }
    
    let alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show alert-floating" role="alert">
            <i class="fas ${iconClass} mr-2"></i>${message}
            <button type="button" class="close" data-dismiss="alert">
                <span>&times;</span>
            </button>
        </div>
    `;
    
    $('#alertContainer').append(alertHtml);
    
    // Auto-dismiss after 5 seconds
    setTimeout(function() {
        $('#alertContainer .alert').first().fadeOut(function() {
            $(this).remove();
        });
    }, 5000);
}

/**
 * Show loading overlay
 */
function showLoading() {
    if ($('.loading-overlay').length === 0) {
        $('body').append(`
            <div class="loading-overlay">
                <div class="loading-spinner"></div>
            </div>
        `);
    }
}

/**
 * Hide loading overlay
 */
function hideLoading() {
    $('.loading-overlay').fadeOut(300, function() {
        $(this).remove();
    });
}
