@extends('layouts.admin')

@section('title', 'Inventory')

@section('page-title', 'Inventory')

@section('breadcrumbs')
    <span class="text-primary font-medium">Inventory</span>
@endsection

@section('content')
<div class="max-w-[1400px] mx-auto">
    <!-- Header Section -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-900 text-gray-900">Inventory Management</h1>
        <div class="flex items-center gap-3">
            <button onclick="openInventoryModal()" class="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg text-sm font-medium shadow-lg shadow-primary/30 hover:bg-blue-600 transition-colors">
                <span class="material-symbols-outlined text-lg">add</span>
                <span>Add Item</span>
            </button>
            <select id="inventoryPerPageSelect" class="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white text-gray-700 focus:outline-none focus:ring-1 focus:ring-primary">
                <option value="10">10 / page</option>
                <option value="25">25 / page</option>
                <option value="50">50 / page</option>
                <option value="100">100 / page</option>
            </select>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Total Items</p>
                    <p class="text-2xl font-bold text-gray-900 text-gray-900 mt-1" id="totalInventoryItems">{{ $totalItems ?? 0 }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-blue-600">inventory_2</span>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Low Stock</p>
                    <p class="text-2xl font-bold text-yellow-600 mt-1">{{ $lowStock ?? 0 }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-yellow-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-yellow-600">warning</span>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Out of Stock</p>
                    <p class="text-2xl font-bold text-red-600 mt-1">{{ $outOfStock ?? 0 }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-red-600">remove_shopping_cart</span>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Total Value</p>
                    <p class="text-2xl font-bold text-green-600 mt-1">{{ number_format($totalValue ?? 0, 2) }}</p>
                </div>
                <div class="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-green-600">attach_money</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Search Bar -->
    <div class="mb-4">
        <div class="relative max-w-md">
            <span class="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">search</span>
            <input type="text" id="inventorySearchInput" placeholder="Search inventory..." class="w-full h-10 pl-10 pr-4 rounded-lg border border-gray-200 bg-white text-gray-900 text-gray-900 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-primary">
        </div>
    </div>

    <!-- Inventory Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">#</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">PRODUCT</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">CODE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">UNIT</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">PURCHASE PRICE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">SELLING PRICE</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">QUANTITY</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500">STATUS</th>
                        <th class="py-4 px-6 text-xs font-semibold uppercase tracking-wider text-gray-500 text-right">ACTIONS</th>
                    </tr>
                </thead>
                <tbody id="inventoryTableBody" class="divide-y divide-gray-100">
                    @forelse($inventoryItems ?? [] as $index => $item)
                    <tr class="hover:bg-gray-50800/50 transition-colors">
                        <td class="py-4 px-6 text-sm text-gray-600">{{ $index + 1 }}</td>
                        <td class="py-4 px-6">
                            <div class="flex items-center gap-3">
                                @if($item->product->image ?? null)
                                <img src="{{ asset('storage/' . $item->product->image) }}" alt="" class="w-10 h-10 rounded-lg object-cover">
                                @else
                                <div class="w-10 h-10 rounded-lg bg-gray-200 flex items-center justify-center">
                                    <span class="material-symbols-outlined text-gray-400">inventory_2</span>
                                </div>
                                @endif
                                <span class="text-sm font-medium text-gray-900 text-gray-900">{{ $item->product->name ?? 'Product Name' }}</span>
                            </div>
                        </td>
                        <td class="py-4 px-6 text-sm text-gray-600 font-mono">{{ $item->code ?? '-' }}</td>
                        <td class="py-4 px-6 text-sm text-gray-600">{{ $item->unit ?? '-' }}</td>
                        <td class="py-4 px-6 text-sm text-gray-600">{{ number_format($item->purchase_price ?? 0, 2) }}</td>
                        <td class="py-4 px-6 text-sm text-gray-600">{{ number_format($item->selling_price ?? 0, 2) }}</td>
                        <td class="py-4 px-6 text-sm font-medium text-gray-900 text-gray-900">{{ $item->quantity ?? 0 }}</td>
                        <td class="py-4 px-6">
                            @if(($item->product->stock ?? 0) <= 0)
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">Out of Stock</span>
                            @elseif(($item->product->stock ?? 0) <= ($item->product->alert_quantity ?? 10))
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">Low Stock</span>
                            @else
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">In Stock</span>
                            @endif
                        </td>
                        <td class="py-4 px-6 text-right">
                            <div class="flex items-center justify-end gap-2">
                                <button onclick="editItem({{ $item->id ?? 0 }})" class="p-2 text-gray-500 hover:text-primary hover:bg-gray-100700 rounded-lg transition-colors">
                                    <span class="material-symbols-outlined text-lg">edit</span>
                                </button>
                                <button onclick="deleteItem({{ $item->id ?? 0 }})" class="p-2 text-gray-500 hover:text-red-500 hover:bg-gray-100700 rounded-lg transition-colors">
                                    <span class="material-symbols-outlined text-lg">delete</span>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="py-12 px-6 text-center text-gray-500">
                            <span class="material-symbols-outlined text-4xl mb-2 block">inventory_2</span>
                            <p>No inventory items found</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if(isset($inventoryItems) && method_exists($inventoryItems, 'hasPages') && $inventoryItems->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $inventoryItems->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Add Inventory Item Modal -->
<div id="inventoryModal" data-admin-modal class="fixed inset-0 z-50 hidden">
    <div class="absolute inset-0 bg-black/50 backdrop-blur-sm" onclick="closeInventoryModal()"></div>
    <div class="absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-2xl transform transition-transform duration-300">
        <div class="flex flex-col h-full">
            <!-- Header -->
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-200">
                <h2 class="text-lg font-bold text-gray-900 text-gray-900" id="inventoryModalTitle">Add Inventory Item</h2>
                <button onclick="closeInventoryModal()" class="p-2 text-gray-500 hover:text-gray-700-300 hover:bg-gray-100700 rounded-lg transition-colors">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>

            <!-- Form -->
            <form id="inventoryForm" method="POST" class="flex-1 overflow-y-auto">
                @csrf
                <input type="hidden" id="inventoryId" name="inventory_id" value="">
                <div class="p-6 space-y-6">
                    <!-- Product/Service -->
                    <div>
                        <label for="inventoryProduct" class="block text-sm font-medium text-gray-700 mb-2">
                            Product/Service <span class="text-red-500">*</span>
                        </label>
                        <select id="inventoryProduct" name="product_id" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="">Type to search...</option>
                        </select>
                    </div>

                    <!-- Code -->
                    <div>
                        <label for="inventoryCode" class="block text-sm font-medium text-gray-700 mb-2">Code</label>
                        <div class="flex gap-2">
                            <input type="text" id="inventoryCode" name="code" class="flex-1 h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Auto-generated or enter manually">
                            <button type="button" onclick="generateInventoryCode()" class="px-4 h-11 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm font-medium flex items-center gap-2 whitespace-nowrap" title="Generate Code">
                                <span class="material-symbols-outlined text-lg">refresh</span>
                                <span>Generate</span>
                            </button>
                        </div>
                    </div>

                    <!-- Unit -->
                    <div>
                        <label for="inventoryUnit" class="block text-sm font-medium text-gray-700 mb-2">Unit</label>
                        <input type="text" id="inventoryUnit" name="unit" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Auto-filled from product or enter manually">
                    </div>

                    <!-- Purchase Price -->
                    <div>
                        <label for="inventoryPurchasePrice" class="block text-sm font-medium text-gray-700 mb-2">Purchase Price</label>
                        <input type="number" id="inventoryPurchasePrice" name="purchase_price" step="0.01" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="0.00">
                    </div>

                    <!-- Selling Price -->
                    <div>
                        <label for="inventorySellingPrice" class="block text-sm font-medium text-gray-700 mb-2">Selling Price</label>
                        <input type="number" id="inventorySellingPrice" name="selling_price" step="0.01" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="0.00">
                    </div>

                    <!-- Type -->
                    <div>
                        <label for="inventoryType" class="block text-sm font-medium text-gray-700 mb-2">
                            Type <span class="text-red-500">*</span>
                        </label>
                        <select id="inventoryType" name="type" required class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow">
                            <option value="stock_in">Stock In</option>
                            <option value="stock_out">Stock Out</option>
                        </select>
                    </div>

                    <!-- Quantity -->
                    <div>
                        <label for="inventoryQuantity" class="block text-sm font-medium text-gray-700 mb-2">
                            Quantity <span class="text-red-500">*</span>
                        </label>
                        <input type="number" id="inventoryQuantity" name="quantity" required min="1" class="w-full h-11 px-4 rounded-lg border border-gray-300 bg-white text-gray-900 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-shadow" placeholder="Enter quantity">
                    </div>
                </div>
            </form>

            <!-- Footer -->
            <div class="px-6 py-4 border-t border-gray-200 flex items-center justify-end gap-3">
                <button type="button" onclick="closeInventoryModal()" class="px-5 py-2.5 rounded-lg border border-gray-300 text-gray-700 font-medium hover:bg-gray-50800 transition-colors">
                    Cancel
                </button>
                <button type="submit" form="inventoryForm" class="px-5 py-2.5 rounded-lg bg-primary text-white font-medium hover:bg-blue-600 shadow-sm transition-colors flex items-center gap-2">
                    <span class="material-symbols-outlined text-lg">save</span>
                    Save Item
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Success Notification Modal -->
<div id="successNotification" class="fixed inset-0 z-[60] hidden flex items-center justify-center pointer-events-none">
    <div class="absolute inset-0 bg-black/30 backdrop-blur-sm pointer-events-auto" onclick="closeSuccessNotification()"></div>
    <div class="relative bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0 pointer-events-auto" id="successNotificationContent">
        <div class="p-6">
            <div class="flex items-start gap-4">
                <!-- Success Icon -->
                <div class="flex-shrink-0 w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
                    <span class="material-symbols-outlined text-green-600 text-2xl">check_circle</span>
                </div>
                
                <!-- Content -->
                <div class="flex-1">
                    <h3 class="text-lg font-semibold text-gray-900 mb-1" id="successNotificationTitle">Success!</h3>
                    <p class="text-sm text-gray-600" id="successNotificationMessage">Operation completed successfully.</p>
                </div>
                
                <!-- Close Button -->
                <button onclick="closeSuccessNotification()" class="flex-shrink-0 p-1 text-gray-400 hover:text-gray-600 rounded-lg transition-colors">
                    <span class="material-symbols-outlined text-lg">close</span>
                </button>
            </div>
        </div>
        
        <!-- Progress Bar -->
        <div class="h-1 bg-gray-100 rounded-b-2xl overflow-hidden">
            <div class="h-full bg-green-500 rounded-b-2xl transition-all duration-300" id="successNotificationProgress"></div>
        </div>
    </div>
</div>

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .select2-container--default .select2-selection--single {
        height: 44px;
        border: 1px solid #d1d5db;
        border-radius: 0.5rem;
    }
    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 44px;
        padding-left: 16px;
    }
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 42px;
    }
</style>
@endpush

@push('scripts')
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    const baseUrl = '{{ route("admin.inventory.index") }}';
    const productsUrl = '{{ route("admin.inventory.products") }}';
    let currentPage = 1;
    let currentSearch = '';
    let currentPerPage = 10;

    // Debug function to test products endpoint
    function testProductsEndpoint() {
        console.log('Testing products endpoint:', productsUrl);
        fetch(productsUrl + '?search=', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => {
            console.log('Response status:', response.status);
            console.log('Response headers:', response.headers);
            return response.json();
        })
        .then(data => {
            console.log('Products data:', data);
            if (data.success) {
                console.log('✓ Products endpoint working! Found', data.products.length, 'products');
            } else {
                console.error('✗ Products endpoint returned error:', data.message);
            }
        })
        .catch(error => {
            console.error('✗ Error testing products endpoint:', error);
        });
    }
    
    // Test endpoint on page load (can be removed in production)
        $(document).ready(function() {
        // Uncomment to test endpoint
        // testProductsEndpoint();
    });

    // Function to initialize Select2 (defined before use)
    function initializeProductSelect2() {
        // Remove existing Select2 instance if it exists
        if ($('#inventoryProduct').hasClass('select2-hidden-accessible')) {
            $('#inventoryProduct').select2('destroy');
        }
        
        // First, load initial products to populate the dropdown
        loadInitialProducts();
        
            $('#inventoryProduct').select2({
                placeholder: 'Type to search...',
                allowClear: true,
            width: '100%',
                ajax: {
                    url: '{{ route("admin.inventory.products") }}',
                type: 'GET',
                    dataType: 'json',
                    delay: 250,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                    data: function(params) {
                    console.log('Select2 AJAX request:', params);
                        return {
                            search: params.term || '',
                            page: params.page || 1
                        };
                    },
                processResults: function(data, params) {
                        console.log('Products response:', data);
                    
                    if (data && data.success && Array.isArray(data.products)) {
                            return {
                                results: data.products.map(function(product) {
                                    return {
                                        id: product.id,
                                    text: product.text || (product.name + ' (' + (product.code || 'N/A') + ')'),
                                        product: product
                                    };
                                }),
                                pagination: {
                                more: (params.page || 1) * 50 < (data.total || data.products.length)
                            }
                        };
                    }
                    
                    console.warn('Invalid response format:', data);
                    return {
                        results: [],
                        pagination: {
                            more: false
                        }
                        };
                    },
                    error: function(xhr, status, error) {
                    console.error('Error fetching products:', {
                        status: status,
                        error: error,
                        response: xhr.responseText,
                        statusCode: xhr.status,
                        url: '{{ route("admin.inventory.products") }}'
                    });
                    
                    // Show user-friendly error
                    if (xhr.status === 404) {
                        console.error('Route not found. Check route: admin.inventory.products');
                    } else if (xhr.status === 500) {
                        console.error('Server error. Check server logs.');
                    } else if (xhr.status === 0) {
                        console.error('Network error. Check if server is running.');
                    }
                },
                cache: false
            },
            minimumInputLength: 0,
            language: {
                inputTooShort: function() {
                    return 'Type to search...';
                },
                noResults: function() {
                    return 'No products found';
                },
                searching: function() {
                    return 'Searching...';
                },
                loadingMore: function() {
                    return 'Loading more results...';
                }
            }
        });
        
        // Trigger search on open to load initial products
        $('#inventoryProduct').off('select2:open').on('select2:open', function() {
            var $select = $(this);
            var $search = $('.select2-search__field');
            
            // Wait for Select2 dropdown to fully render
            setTimeout(function() {
                if ($search.length) {
                    // Focus the search field
                    $search.focus();
                    
                    // Trigger input event - this should trigger AJAX with minimumInputLength: 0
                    $search.trigger('input');
                    
                    // Also trigger keyup as additional fallback
                    setTimeout(function() {
                        $search.trigger('keyup');
                    }, 100);
                } else {
                    // If search field not found, manually trigger AJAX
                    console.log('Search field not found, manually triggering AJAX');
                    $select.select2('open');
                }
            }, 200);
            });

        // Auto-fill product details when product is selected
        $('#inventoryProduct').off('select2:select').on('select2:select', function(e) {
            const data = e.params.data;
            console.log('Product selected:', data);
            console.log('Product data:', data.product);
            
            if (data && data.product) {
                // Set code
                if (data.product.code) {
                    $('#inventoryCode').val(data.product.code);
                }
                
                // Set unit - check both unit and unit.short_name
                const unitValue = data.product.unit || (data.product.unit_name || '');
                if (unitValue) {
                    $('#inventoryUnit').val(unitValue);
                    console.log('Unit set to:', unitValue);
                } else {
                    console.warn('Unit not found in product data');
                }
                
                // Set prices
                if (data.product.purchase_price !== undefined && data.product.purchase_price !== null) {
                    $('#inventoryPurchasePrice').val(data.product.purchase_price);
                }
                
                if (data.product.selling_price !== undefined && data.product.selling_price !== null) {
                    $('#inventorySellingPrice').val(data.product.selling_price);
                }
            } else {
                console.error('Product data not found in selection');
            }
        });
    }
    
    // Function to load initial products
    function loadInitialProducts() {
        fetch('{{ route("admin.inventory.products") }}?search=', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => {
            console.log('Initial products fetch response status:', response.status);
            if (!response.ok) {
                throw new Error('HTTP error! status: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('Initial products loaded:', data);
            if (data && data.success && Array.isArray(data.products) && data.products.length > 0) {
                // Pre-populate Select2 with initial products
                const options = data.products.map(function(product) {
                    return new Option(
                        product.text || (product.name + ' (' + (product.code || 'N/A') + ')'),
                        product.id,
                        false,
                        false
                    );
                });
                $('#inventoryProduct').append(options);
            }
        })
        .catch(error => {
            console.error('Error loading initial products:', error);
        });
    }

    // Initialize Select2 for product dropdown
    $(document).ready(function() {
        // Initialize Select2 on page load
        initializeProductSelect2();

        // Load inventory items on page load
        loadInventoryItems();
        
        // Setup search input with debounce
        let searchTimeout;
        const searchInput = document.getElementById('inventorySearchInput');
        if (searchInput) {
            searchInput.addEventListener('input', function(e) {
                clearTimeout(searchTimeout);
                const searchValue = e.target.value.trim();
                
                searchTimeout = setTimeout(function() {
                    currentSearch = searchValue;
                    currentPage = 1; // Reset to first page on new search
                    loadInventoryItems();
                }, 500); // Wait 500ms after user stops typing
            });
        }
        
        // Setup per-page select
        const perPageSelect = document.getElementById('inventoryPerPageSelect');
        if (perPageSelect) {
            // Set current value
            perPageSelect.value = currentPerPage;
            
            perPageSelect.addEventListener('change', function(e) {
                currentPerPage = parseInt(e.target.value);
                currentPage = 1; // Reset to first page when changing per page
                loadInventoryItems();
            });
        }
    });

    // Load inventory items
    function loadInventoryItems() {
        const tbody = document.getElementById('inventoryTableBody');
        tbody.innerHTML = '<tr><td colspan="9" class="py-12 px-6 text-center text-gray-500"><span class="material-symbols-outlined text-4xl mb-2 block animate-spin">hourglass_empty</span><p>Loading...</p></td></tr>';

        fetch(`${baseUrl}?ajax=1&page=${currentPage}&per_page=${currentPerPage}&search=${encodeURIComponent(currentSearch)}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderInventoryTable(data.data, data.pagination);
                
                // Update total items from stats if available
                if (data.stats && data.stats.total_items !== undefined) {
                    const totalItemsEl = document.getElementById('totalInventoryItems');
                    if (totalItemsEl) {
                        totalItemsEl.textContent = data.stats.total_items;
                    }
                }
            } else {
                tbody.innerHTML = '<tr><td colspan="9" class="py-12 px-6 text-center text-gray-500"><span class="material-symbols-outlined text-4xl mb-2 block">inventory_2</span><p>Error loading inventory items</p></td></tr>';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            tbody.innerHTML = '<tr><td colspan="9" class="py-12 px-6 text-center text-gray-500"><span class="material-symbols-outlined text-4xl mb-2 block">inventory_2</span><p>Error loading inventory items</p></td></tr>';
        });
    }

    // Render inventory table
    function renderInventoryTable(items, pagination) {
        const tbody = document.getElementById('inventoryTableBody');
        
        // Update total items stat
        const totalItemsEl = document.getElementById('totalInventoryItems');
        if (totalItemsEl && pagination) {
            totalItemsEl.textContent = pagination.total || 0;
        }
        
        if (items.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" class="py-12 px-6 text-center text-gray-500"><span class="material-symbols-outlined text-4xl mb-2 block">inventory_2</span><p>No inventory items found</p></td></tr>';
            return;
        }

        let html = '';
        const startIndex = (pagination.current_page - 1) * pagination.per_page;
        
        items.forEach((item, index) => {
            const product = item.product || {};
            const productImage = product.image ? `{{ asset('storage/') }}/${product.image}` : '';
            const stock = product.stock || 0;
            const alertQuantity = product.alert_quantity || 10;
            
            let statusBadge = '';
            if (stock <= 0) {
                statusBadge = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">Out of Stock</span>';
            } else if (stock <= alertQuantity) {
                statusBadge = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">Low Stock</span>';
            } else {
                statusBadge = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">In Stock</span>';
            }

            html += `
                <tr class="hover:bg-gray-50/50 transition-colors">
                    <td class="py-4 px-6 text-sm text-gray-600">${startIndex + index + 1}</td>
                    <td class="py-4 px-6">
                        <div class="flex items-center gap-3">
                            ${productImage ? 
                                `<img src="${productImage}" alt="" class="w-10 h-10 rounded-lg object-cover">` :
                                `<div class="w-10 h-10 rounded-lg bg-gray-200 flex items-center justify-center">
                                    <span class="material-symbols-outlined text-gray-400">inventory_2</span>
                                </div>`
                            }
                            <span class="text-sm font-medium text-gray-900">${product.name || 'Product Name'}</span>
                        </div>
                    </td>
                    <td class="py-4 px-6 text-sm text-gray-600 font-mono">${item.code || '-'}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">${item.unit || '-'}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">${parseFloat(item.purchase_price || 0).toFixed(2)}</td>
                    <td class="py-4 px-6 text-sm text-gray-600">${parseFloat(item.selling_price || 0).toFixed(2)}</td>
                    <td class="py-4 px-6 text-sm font-medium text-gray-900">${item.quantity || 0}</td>
                    <td class="py-4 px-6">${statusBadge}</td>
                    <td class="py-4 px-6 text-right">
                        <div class="flex items-center justify-end gap-2">
                            <button onclick="editItem(${item.id})" class="p-2 text-gray-500 hover:text-primary hover:bg-gray-100 rounded-lg transition-colors">
                                <span class="material-symbols-outlined text-lg">edit</span>
                            </button>
                            <button onclick="deleteItem(${item.id})" class="p-2 text-gray-500 hover:text-red-500 hover:bg-gray-100 rounded-lg transition-colors">
                                <span class="material-symbols-outlined text-lg">delete</span>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
    }

    function openInventoryModal() {
        document.getElementById('inventoryModal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
        
        // Set form title to "Add"
        document.getElementById('inventoryModalTitle').textContent = 'Add Inventory Item';
        
        // Reset form
        document.getElementById('inventoryForm').reset();
        
        // Clear inventory ID (for new items)
        document.getElementById('inventoryId').value = '';
        
        // Reset Select2
        $('#inventoryProduct').val(null).trigger('change');
        
        // Clear all fields
        $('#inventoryCode').val('');
        $('#inventoryUnit').val('');
        $('#inventoryPurchasePrice').val('');
        $('#inventorySellingPrice').val('');
        $('#inventoryType').val('stock_in');
        $('#inventoryQuantity').val('');
        
        // Reinitialize Select2 if needed
        setTimeout(function() {
            if (!$('#inventoryProduct').hasClass('select2-hidden-accessible')) {
                initializeProductSelect2();
            }
        }, 100);
    }
    
    function generateInventoryCode() {
        // Generate a random code with prefix INV
        const prefix = 'INV';
        const timestamp = Date.now().toString(36).toUpperCase();
        const random = Math.random().toString(36).substring(2, 6).toUpperCase();
        const code = prefix + '-' + timestamp.substring(timestamp.length - 6) + '-' + random;
        document.getElementById('inventoryCode').value = code;
    }
    
    // Success Notification Functions
    function showSuccessNotification(title, message) {
        const notification = document.getElementById('successNotification');
        const content = document.getElementById('successNotificationContent');
        const titleEl = document.getElementById('successNotificationTitle');
        const messageEl = document.getElementById('successNotificationMessage');
        const progress = document.getElementById('successNotificationProgress');
        const iconContainer = content.querySelector('.bg-green-100, .bg-red-100');
        const icon = iconContainer.querySelector('.material-symbols-outlined');
        
        // Reset to success style
        iconContainer.classList.remove('bg-red-100');
        iconContainer.classList.add('bg-green-100');
        icon.classList.remove('text-red-600');
        icon.classList.add('text-green-600');
        icon.textContent = 'check_circle';
        progress.classList.remove('bg-red-500');
        progress.classList.add('bg-green-500');
        
        // Set content
        titleEl.textContent = title;
        messageEl.textContent = message;
        
        // Reset progress
        progress.style.width = '0%';
        
        // Show notification
        notification.classList.remove('hidden');
        
        // Animate in
        setTimeout(() => {
            content.classList.remove('scale-95', 'opacity-0');
            content.classList.add('scale-100', 'opacity-100');
        }, 10);
        
        // Animate progress bar
        setTimeout(() => {
            progress.style.width = '100%';
        }, 50);
        
        // Auto close after 4 seconds
        setTimeout(() => {
            closeSuccessNotification();
        }, 4000);
    }
    
    function closeSuccessNotification() {
        const notification = document.getElementById('successNotification');
        const content = document.getElementById('successNotificationContent');
        const progress = document.getElementById('successNotificationProgress');
        
        // Animate out
        content.classList.remove('scale-100', 'opacity-100');
        content.classList.add('scale-95', 'opacity-0');
        progress.style.width = '0%';
        
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 300);
    }
    
    // Error Notification Functions
    function showErrorNotification(title, message) {
        const notification = document.getElementById('successNotification');
        const content = document.getElementById('successNotificationContent');
        const titleEl = document.getElementById('successNotificationTitle');
        const messageEl = document.getElementById('successNotificationMessage');
        const progress = document.getElementById('successNotificationProgress');
        const iconContainer = content.querySelector('.bg-green-100, .bg-red-100');
        const icon = iconContainer.querySelector('.material-symbols-outlined');
        
        // Change to error style
        iconContainer.classList.remove('bg-green-100');
        iconContainer.classList.add('bg-red-100');
        icon.classList.remove('text-green-600');
        icon.classList.add('text-red-600');
        icon.textContent = 'error';
        progress.classList.remove('bg-green-500');
        progress.classList.add('bg-red-500');
        
        // Set content
        titleEl.textContent = title;
        messageEl.textContent = message;
        
        // Reset progress
        progress.style.width = '0%';
        
        // Show notification
        notification.classList.remove('hidden');
        
        // Animate in
        setTimeout(() => {
            content.classList.remove('scale-95', 'opacity-0');
            content.classList.add('scale-100', 'opacity-100');
        }, 10);
        
        // Animate progress bar
        setTimeout(() => {
            progress.style.width = '100%';
        }, 50);
        
        // Auto close after 5 seconds (longer for errors)
        setTimeout(() => {
            closeErrorNotification();
        }, 5000);
    }
    
    function closeErrorNotification() {
        const notification = document.getElementById('successNotification');
        const content = document.getElementById('successNotificationContent');
        const progress = document.getElementById('successNotificationProgress');
        const iconContainer = content.querySelector('.bg-red-100, .bg-green-100');
        const icon = iconContainer.querySelector('.material-symbols-outlined');
        
        // Reset to success style
        iconContainer.classList.remove('bg-red-100');
        iconContainer.classList.add('bg-green-100');
        icon.classList.remove('text-red-600');
        icon.classList.add('text-green-600');
        icon.textContent = 'check_circle';
        progress.classList.remove('bg-red-500');
        progress.classList.add('bg-green-500');
        
        // Animate out
        content.classList.remove('scale-100', 'opacity-100');
        content.classList.add('scale-95', 'opacity-0');
        progress.style.width = '0%';
        
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 300);
    }

    function closeInventoryModal() {
        document.getElementById('inventoryModal').classList.add('hidden');
        document.body.style.overflow = '';
        document.getElementById('inventoryForm').reset();
        $('#inventoryProduct').val(null).trigger('change');
    }

    // Form submission
    document.getElementById('inventoryForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const form = this;
        const submitBtn = form.querySelector('button[type="submit"]') || document.querySelector('button[form="inventoryForm"]');
        const originalHTML = submitBtn.innerHTML;
        
        // Validation
        const productId = document.getElementById('inventoryProduct').value;
        const quantity = document.getElementById('inventoryQuantity').value;
        const type = document.getElementById('inventoryType').value;
        
        if (!productId) {
            showErrorNotification('Validation Error', 'Please select a product/service');
            return;
        }
        
        if (!quantity || quantity < 1) {
            showErrorNotification('Validation Error', 'Please enter a valid quantity');
            return;
        }
        
        // Show loading state
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="material-symbols-outlined text-lg animate-spin">hourglass_empty</span> Saving...';
        
        const formData = new FormData(form);
        const inventoryId = document.getElementById('inventoryId').value;
        
        // Determine if this is an update or create
        const isUpdate = inventoryId && inventoryId !== '';
        const url = isUpdate 
            ? `{{ route("admin.inventory.index") }}/${inventoryId}`
            : '{{ route("admin.inventory.store") }}';
        const method = isUpdate ? 'PUT' : 'POST';
        
        // Add _method for PUT request
        if (isUpdate) {
            formData.append('_method', 'PUT');
        }
        
        fetch(url, {
            method: method,
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                closeInventoryModal();
                loadInventoryItems();
                showSuccessNotification(
                    isUpdate ? 'Inventory Updated' : 'Inventory Added',
                    isUpdate ? 'Inventory item has been updated successfully!' : 'Inventory item has been added successfully!'
                );
            } else {
                throw new Error(data.message || (isUpdate ? 'Failed to update inventory item' : 'Failed to add inventory item'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showErrorNotification('Error', error.message);
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalHTML;
        });
    });

    function editItem(id) {
        console.log('Edit item:', id);
        
        // Open modal first
        document.getElementById('inventoryModal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
        
        // Set form title
        document.getElementById('inventoryModalTitle').textContent = 'Edit Inventory Item';
        
        // Show loading state
        const submitBtn = document.querySelector('button[form="inventoryForm"]');
        const originalHTML = submitBtn.innerHTML;
        submitBtn.disabled = true;
        submitBtn.innerHTML = '<span class="material-symbols-outlined text-lg animate-spin">hourglass_empty</span> Loading...';
        
        // Fetch inventory item data
        fetch(`${baseUrl}/${id}`, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.inventory) {
                const item = data.inventory;
                const product = item.product || {};
                
                // Set inventory ID for update
                document.getElementById('inventoryId').value = item.id;
                
                // Populate form fields
                $('#inventoryCode').val(item.code || '');
                $('#inventoryUnit').val(item.unit || '');
                $('#inventoryPurchasePrice').val(item.purchase_price || '');
                $('#inventorySellingPrice').val(item.selling_price || '');
                $('#inventoryType').val(item.type || 'stock_in');
                $('#inventoryQuantity').val(item.quantity || '');
                
                // Set product in Select2
                if (item.product_id && product.name) {
                    // Clear existing options
                    $('#inventoryProduct').empty();
                    
                    // Add the product option
                    const option = new Option(
                        product.name + ' (' + (product.code || 'N/A') + ')',
                        item.product_id,
                        true,
                        true
                    );
                    $('#inventoryProduct').append(option).trigger('change');
                }
            } else {
                throw new Error(data.message || 'Failed to load inventory item');
            }
        })
        .catch(error => {
            console.error('Error loading inventory item:', error);
            showErrorNotification('Load Error', 'Error loading inventory item: ' + error.message);
            closeInventoryModal();
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalHTML;
        });
    }

    function deleteItem(id) {
        if (!confirm('Are you sure you want to delete this inventory item? This will revert the stock changes. This action cannot be undone.')) {
            return;
        }

        // Create form data for DELETE request with _method
        const formData = new FormData();
        formData.append('_method', 'DELETE');
        formData.append('_token', '{{ csrf_token() }}');

        fetch(`${baseUrl}/${id}`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadInventoryItems();
                showSuccessNotification(
                    'Inventory Deleted',
                    'Inventory item has been deleted successfully!'
                );
            } else {
                throw new Error(data.message || 'Failed to delete inventory item');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showErrorNotification('Delete Error', error.message);
        });
    }
</script>
@endpush
@endsection




