@extends('layouts.admin-simple')

@section('title', 'Physical Count & Cycle Counting')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Inventory</li>
    <li class="breadcrumb-item active">Physical Count</li>
@endsection

@section('page-title')
    <div class="d-flex justify-content-between align-items-center w-100">
        <div class="page-title-left">
            <h3 class="mb-1">Physical Count & Cycle Counting</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Perform physical inventory counts and reconcile with system records</p>
        </div>
        @can('warehouse.inventory.manage')
        <div class="page-actions-right d-flex align-items-center">
            <button type="button" onclick="exportCountData()" class="btn btn-sm btn-success mr-2" title="Export count data to Excel file">
                <i class="material-icons mr-1" style="font-size: 16px;">upload_file</i>
                Import
            </button>

            <button type="button" onclick="exportCountData()" class="btn btn-sm btn-info mr-2" title="Export count data to Excel file">
                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                Export
            </button>

            <button type="button" onclick="showStartCountModal()" class="btn btn-sm btn-primary" title="Start a new physical count session">
                <i class="material-icons mr-1" style="font-size: 16px;">add</i>
                Start New Count
            </button>
        </div>
        @endcan
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Total Items"
                :value="$items->count() ?? 0"
                icon="inventory"
                color="primary"
                subtitle="Items available for counting"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Counted Items"
                value="0"
                icon="assignment_turned_in"
                color="success"
                subtitle="Items already counted"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Matched"
                value="0"
                icon="check_circle"
                color="info"
                subtitle="Perfect matches with system"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Discrepancies"
                value="0"
                icon="warning"
                color="warning"
                subtitle="Items requiring adjustment"
            />
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">filter_list</i>
                Count Filters
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-xl-2 col-md-6 mb-3">
                    <label class="form-label">Category</label>
                    <select id="filter-category" class="form-control" data-placeholder="All Categories">
                        <option value=""></option>
                        @foreach(\App\Models\Warehouse\ItemCategory::orderBy('category_name')->get() as $category)
                            <option value="{{ $category->id }}">{{ $category->category_name }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-xl-2 col-md-6 mb-3">
                    <label class="form-label">Division</label>
                    <select id="filter-division" class="form-control" data-placeholder="All Divisions">
                        <option value=""></option>
                        @foreach(\App\Models\Warehouse\ProjectDivision::where('status', 'active')->orderBy('division_name')->get() as $division)
                            <option value="{{ $division->id }}">{{ $division->division_name }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="col-xl-2 col-md-6 mb-3">
                    <label class="form-label">Count Status</label>
                    <select id="filter-status" class="form-control" data-placeholder="All Statuses">
                        <option value=""></option>
                        <option value="pending">Pending</option>
                        <option value="counted">Counted</option>
                        <option value="matched">Matched</option>
                        <option value="discrepancy">Discrepancy</option>
                    </select>
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <label class="form-label">Item Search</label>
                    <input type="text" id="filter-search" class="form-control" placeholder="Search by item name or code">
                </div>

                <div class="col-xl-3 col-md-6 mb-3">
                    <label class="form-label">Variance Range</label>
                    <div class="d-flex">
                        <input type="number" id="filter-variance-min" placeholder="Min" class="form-control mr-2">
                        <input type="number" id="filter-variance-max" placeholder="Max" class="form-control">
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
                <button type="button" onclick="applyFilters()" class="btn btn-primary">
                    <i class="material-icons mr-1" style="font-size: 18px; vertical-align: middle;">filter_list</i>
                    Apply Filters
                </button>

                <button type="button" onclick="clearFilters()" class="btn btn-outline-secondary">
                    <i class="material-icons mr-1" style="font-size: 18px; vertical-align: middle;">clear</i>
                    Clear Filters
                </button>
            </div>
        </div>
    </div>

    <!-- Physical Count Table -->
    <div class="card">
        <div class="card-header warehouse-report-header">
            <h5 class="mb-0 warehouse-report-title">
                <i class="material-icons align-middle mr-2">list</i>
                Physical Count List ({{ $items->total() ?? $items->count() }} total items)
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <!-- Loading Overlay -->
                <div class="warehouse-loading-overlay" id="tableLoadingOverlay" style="display: none;">
                    <div class="warehouse-loading-content">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <div class="mt-2">Loading items...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    <table id="count-table" class="table table-hover mb-0 warehouse-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="min-width: 200px;">Item</th>
                                <th style="min-width: 120px;">Category</th>
                                <th style="min-width: 120px;">Division</th>
                                <th style="min-width: 100px;">Current Stock</th>
                                <th style="min-width: 130px;">Physical Count</th>
                                <th style="min-width: 90px;">Variance</th>
                                <th style="min-width: 100px;">Status</th>
                                <th style="min-width: 120px;">Last Updated</th>
                                <th style="min-width: 100px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                        @if($items->count() > 0)
                            @foreach($items as $item)
                                <tr data-item-id="{{ $item->id }}" class="count-row">
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="mr-3">
                                                <div class="bg-primary text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 40px; height: 40px;">
                                                    <span class="font-weight-bold" style="font-size: 14px;">{{ substr($item->item_description ?? $item->item_code ?? 'U', 0, 1) }}</span>
                                                </div>
                                            </div>
                                            <div>
                                                <div class="font-weight-medium">{{ $item->item_description ?? $item->item_code ?? 'Unknown Item' }}</div>
                                                <small class="text-muted">{{ $item->item_code ?? 'No Code' }}</small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        @if($item->category)
                                            <div>
                                                <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">category</i>
                                                <span>{{ $item->category->category_name }}</span>
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td>
                                        @php
                                            // Get unique divisions that have this item in inventory
                                            $itemDivisions = $item->inventories ? $item->inventories->filter(function($inv) {
                                                return $inv->division_id && $inv->quantity_available > 0;
                                            })->pluck('division')->unique('id') : collect();
                                        @endphp
                                        @if($itemDivisions->count() > 0)
                                            @if($itemDivisions->count() == 1)
                                                <div>
                                                    <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">business</i>
                                                    <span>{{ $itemDivisions->first()->division_name ?? 'Unknown' }}</span>
                                                </div>
                                            @else
                                                <div>
                                                    <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">business</i>
                                                    <span title="{{ $itemDivisions->pluck('division_name')->join(', ') }}">
                                                        {{ $itemDivisions->count() }} divisions
                                                    </span>
                                                </div>
                                            @endif
                                        @else
                                            <span class="text-muted">No Division</span>
                                        @endif
                                    </td>
                                    <td>
                                        @php
                                            $currentStock = $item->inventories ? $item->inventories->sum('quantity_available') : 0;
                                        @endphp
                                        <div>
                                            <div class="font-weight-medium mb-1">{{ number_format($currentStock, 2) }}</div>
                                            <small class="text-muted">{{ $item->unit_of_measure ?? 'pcs' }}</small>
                                        </div>
                                    </td>
                                    <td>
                                        <input type="number"
                                               class="form-control form-control-sm physical-count-input"
                                               data-item-id="{{ $item->id }}"
                                               data-current-stock="{{ $currentStock }}"
                                               placeholder="Enter count"
                                               min="0"
                                               step="0.01"
                                               style="width: 120px;">
                                    </td>
                                    <td>
                                        <span class="variance-display text-muted">-</span>
                                    </td>
                                    <td>
                                        <span class="status-badge badge badge-secondary">Pending</span>
                                    </td>
                                    <td>
                                        <div>
                                            <div class="small">{{ now()->format('M j, Y') }}</div>
                                            <div class="small text-muted">by {{ auth()->user()->name }}</div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-success save-count-btn"
                                                    data-item-id="{{ $item->id }}"
                                                    title="Save Count"
                                                    style="display: none;">
                                                <i class="material-icons" style="font-size: 16px;">save</i>
                                            </button>
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-primary view-history-btn"
                                                    data-item-id="{{ $item->id }}"
                                                    title="View History">
                                                <i class="material-icons" style="font-size: 16px;">history</i>
                                            </button>
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-warning recount-btn"
                                                    data-item-id="{{ $item->id }}"
                                                    title="Recount"
                                                    style="display: none;">
                                                <i class="material-icons" style="font-size: 16px;">refresh</i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        @else
                            <tr>
                                <td colspan="9" class="warehouse-empty-state">
                                    <i class="material-icons">inventory</i>
                                    <h5>No Items Found</h5>
                                    <p class="text-muted">No items available for counting.</p>
                                </td>
                            </tr>
                        @endif
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        @if(method_exists($items, 'hasPages') && $items->hasPages())
            <div class="card-footer">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        Showing {{ $items->firstItem() }} to {{ $items->lastItem() }}
                        of {{ $items->total() }} items
                    </div>
                    <div>
                        <nav class="warehouse-pagination">
                            {{ $items->links('pagination::bootstrap-4') }}
                        </nav>
                    </div>
                </div>
            </div>
        @endif
    </div>

    <!-- Start Count Modal -->
    <div class="modal fade" id="startCountModal" tabindex="-1" role="dialog" aria-labelledby="startCountModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="startCountModalLabel">
                        <i class="material-icons mr-2">play_arrow</i>
                        Start New Physical Count
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="startCountForm">
                        @csrf
                        <div class="form-group">
                            <label for="count_type">Count Type</label>
                            <select name="count_type" id="count_type" class="form-control" required>
                                <option value="">Select Count Type</option>
                                <option value="full">Full Physical Count</option>
                                <option value="cycle">Cycle Count</option>
                                <option value="spot">Spot Check</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="count_date">Count Date</label>
                            <input type="date" name="count_date" id="count_date" class="form-control" value="{{ date('Y-m-d') }}" required>
                        </div>

                        <div class="form-group">
                            <label for="count_notes">Notes</label>
                            <textarea name="count_notes" id="count_notes" class="form-control" rows="3" placeholder="Optional notes about this count session..."></textarea>
                        </div>

                        <div class="alert alert-info">
                            <h6>Count Instructions:</h6>
                            <small>
                                1. Ensure all items are properly counted<br>
                                2. Enter accurate physical quantities<br>
                                3. Review discrepancies before finalizing<br>
                                4. Save progress regularly during counting
                            </small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" onclick="startNewCount()" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 16px;">play_arrow</i>
                        Start Count
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Count History Modal -->
    <div class="modal fade" id="countHistoryModal" tabindex="-1" role="dialog" aria-labelledby="countHistoryModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="countHistoryModalLabel">
                        <i class="material-icons mr-2">history</i>
                        Count History
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="countHistoryContent">
                    <!-- History content will be loaded here -->
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <link href="{{ asset('admin-assets/css/warehouse-reports.css') }}" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    <style>
        /* Select2 custom styling */
        .select2-container--bootstrap-5 .select2-selection {
            min-height: 38px;
            border: 1px solid #ced4da;
        }
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--bootstrap-5 .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
        .select2-container {
            width: 100% !important;
        }
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 4px;
        }

        .btn-sm .material-icons {
            font-size: 16px !important;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            background-color: #f8f9fa;
        }

        .table-responsive {
            border-radius: 0.375rem;
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            font-size: 0.75rem;
            font-weight: 500;
            line-height: 1;
            border-radius: 0.375rem;
        }

        .variance-display.text-success {
            font-weight: 600;
            color: #28a745 !important;
        }

        .variance-display.text-danger {
            font-weight: 600;
            color: #dc3545 !important;
        }

        .variance-display.text-primary {
            font-weight: 600;
            color: #007bff !important;
        }

        .physical-count-input {
            transition: all 0.15s ease-in-out;
        }

        .physical-count-input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
        }

        .count-row:hover {
            background-color: #f8f9fa;
        }

        .count-row.counted {
            background-color: #e8f5e8;
        }

        .count-row.discrepancy {
            background-color: #fff3cd;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        /* Aggressive Modal z-index fix */
        .modal,
        #startCountModal,
        #countHistoryModal {
            z-index: 999999 !important;
            position: fixed !important;
        }

        .modal-backdrop,
        .modal-backdrop.fade,
        .modal-backdrop.show {
            z-index: 999998 !important;
            position: fixed !important;
        }

        .modal-dialog {
            z-index: 1000000 !important;
            position: relative !important;
        }

        .modal-content {
            z-index: 1000001 !important;
            position: relative !important;
        }

        /* Force modal to appear above everything */
        .modal.show,
        .modal.fade.show {
            display: block !important;
            z-index: 999999 !important;
            opacity: 1 !important;
        }

        /* Override any potential conflicts */
        .modal * {
            position: relative;
        }

        /* Ensure body doesn't scroll when modal is open */
        body.modal-open {
            overflow: hidden !important;
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="{{ asset('admin-assets/js/warehouse-reports.js') }}"></script>

    <script>
        let countStats = {
            total: {{ $items->total() ?? $items->count() ?? 0 }},
            counted: 0,
            matched: 0,
            discrepancies: 0
        };

        $(document).ready(function() {
            // Initialize Select2 for searchable dropdowns
            $('#filter-category, #filter-division, #filter-status').select2({
                theme: 'bootstrap-5',
                allowClear: true,
                placeholder: function() {
                    return $(this).data('placeholder') || 'Select...';
                }
            });

            initializeCountHandlers();

            // Hide loading overlay on page load
            $('#tableLoadingOverlay').hide();
        });

        function initializeCountHandlers() {
            // Handle physical count input
            $('.physical-count-input').off('input').on('input', function() {
                const itemId = $(this).data('item-id');
                const currentStock = parseFloat($(this).data('current-stock'));
                const physicalCount = parseFloat($(this).val()) || 0;
                const variance = physicalCount - currentStock;
                const row = $(this).closest('tr');

                updateVarianceDisplay(row, variance, $(this).val());
                updateStatusBadge(row, variance, $(this).val());
                toggleActionButtons(row, $(this).val());
            });

            // Handle save count
            $('.save-count-btn').off('click').on('click', function() {
                const itemId = $(this).data('item-id');
                const row = $(this).closest('tr');
                const input = row.find('.physical-count-input');

                saveItemCount(itemId, row, input);
            });

            // Handle recount
            $('.recount-btn').off('click').on('click', function() {
                const row = $(this).closest('tr');
                const input = row.find('.physical-count-input');

                enableRecount(row, input);
            });

            // Handle view history
            $('.view-history-btn').off('click').on('click', function() {
                const itemId = $(this).data('item-id');
                showCountHistory(itemId);
            });
        }

        function updateVarianceDisplay(row, variance, inputValue) {
            const varianceSpan = row.find('.variance-display');

            if (inputValue) {
                varianceSpan.text(variance.toFixed(2));
                if (variance === 0) {
                    varianceSpan.removeClass().addClass('variance-display text-success');
                } else if (variance > 0) {
                    varianceSpan.removeClass().addClass('variance-display text-primary');
                } else {
                    varianceSpan.removeClass().addClass('variance-display text-danger');
                }
            } else {
                varianceSpan.text('-').removeClass().addClass('variance-display text-muted');
            }
        }

        function updateStatusBadge(row, variance, inputValue) {
            const statusBadge = row.find('.status-badge');

            if (inputValue) {
                if (variance === 0) {
                    statusBadge.text('Matched').removeClass().addClass('status-badge badge badge-success');
                } else {
                    statusBadge.text('Discrepancy').removeClass().addClass('status-badge badge badge-warning');
                }
            } else {
                statusBadge.text('Pending').removeClass().addClass('status-badge badge badge-secondary');
            }
        }

        function toggleActionButtons(row, inputValue) {
            const saveBtn = row.find('.save-count-btn');
            const recountBtn = row.find('.recount-btn');

            if (inputValue) {
                saveBtn.show();
                recountBtn.hide();
            } else {
                saveBtn.hide();
                recountBtn.hide();
            }
        }

        function saveItemCount(itemId, row, input) {
            const physicalCount = parseFloat(input.val()) || 0;
            const currentStock = parseFloat(input.data('current-stock'));
            const variance = physicalCount - currentStock;

            // Simulate saving
            row.find('.status-badge').text('Counted').removeClass().addClass('status-badge badge badge-info');
            input.prop('disabled', true);
            row.find('.save-count-btn').hide();
            row.find('.recount-btn').show();
            row.addClass('counted');

            updateCountStats();
            showAlert('Count saved successfully!', 'success');
        }

        function enableRecount(row, input) {
            input.prop('disabled', false).focus();
            row.find('.recount-btn').hide();
            row.removeClass('counted discrepancy');

            updateCountStats();
        }

        function updateCountStats() {
            countStats.counted = $('.status-badge:contains("Counted")').length;
            countStats.matched = $('.status-badge:contains("Matched")').length;
            countStats.discrepancies = $('.status-badge:contains("Discrepancy")').length;

            // Update stats cards if they exist
            updateStatsCards();
        }

        function updateStatsCards() {
            // This would update the warehouse stats cards if they have IDs
            // Implementation depends on the warehouse component structure
        }

        function applyFilters() {
            // Show loading overlay
            $('#tableLoadingOverlay').show();

            // Build query string with filter parameters
            const params = new URLSearchParams();

            const category = $('#filter-category').val();
            const division = $('#filter-division').val();
            const status = $('#filter-status').val();
            const search = $('#filter-search').val();
            const varianceMin = $('#filter-variance-min').val();
            const varianceMax = $('#filter-variance-max').val();

            if (category) params.append('category', category);
            if (division) params.append('division', division);
            if (status) params.append('status', status);
            if (search) params.append('search', search);
            if (varianceMin) params.append('variance_min', varianceMin);
            if (varianceMax) params.append('variance_max', varianceMax);

            // Navigate to the filtered URL
            window.location.href = window.location.pathname + (params.toString() ? '?' + params.toString() : '');
        }

        function clearFilters() {
            // Show loading overlay
            $('#tableLoadingOverlay').show();

            // Navigate to the base URL without any filters
            window.location.href = window.location.pathname;
        }

        function exportCountData() {
            const btn = event.target.closest('button');
            const originalHtml = btn.innerHTML;
            btn.innerHTML = '<i class="material-icons mr-1" style="font-size: 16px; animation: spin 1s linear infinite;">sync</i>Exporting...';
            btn.disabled = true;

            setTimeout(() => {
                btn.innerHTML = originalHtml;
                btn.disabled = false;
                showAlert('Export functionality will be implemented', 'info');
            }, 800);
        }

        function showStartCountModal() {
            // Clear form and show modal
            $('#startCountForm')[0].reset();
            $('#startCountModal').modal('show');
        }

        function startNewCount() {
            const form = $('#startCountForm')[0];
            const formData = new FormData(form);

            // Simulate starting count
            $('#startCountModal').modal('hide');
            showAlert('New count session started successfully!', 'success');
        }

        function showCountHistory(itemId) {
            $('#countHistoryContent').html(`
                <div class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                    <p class="mt-2">Loading count history...</p>
                </div>
            `);

            $('#countHistoryModal').modal('show');

            // Simulate loading history
            setTimeout(() => {
                $('#countHistoryContent').html(`
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>System Count</th>
                                    <th>Physical Count</th>
                                    <th>Variance</th>
                                    <th>User</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>${new Date().toLocaleDateString()}</td>
                                    <td>Cycle Count</td>
                                    <td>100.00</td>
                                    <td>98.50</td>
                                    <td class="text-danger">-1.50</td>
                                    <td>{{ auth()->user()->name }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                `);
            }, 1000);
        }

        function showAlert(message, type) {
            // Remove any existing alerts first
            $('.warehouse-alert').remove();

            const alertClass = type === 'success' ? 'alert-success' : (type === 'info' ? 'alert-info' : 'alert-danger');
            const icon = type === 'success' ? 'check_circle' : (type === 'info' ? 'info' : 'error');
            const iconColor = type === 'success' ? '#28a745' : (type === 'info' ? '#17a2b8' : '#dc3545');

            const alert = `
                <div class="alert ${alertClass} alert-dismissible fade show warehouse-alert"
                     style="position: fixed; top: 20px; right: 20px; z-index: 999999;
                            min-width: 300px; max-width: 500px; border-radius: 8px;
                            box-shadow: 0 4px 12px rgba(0,0,0,0.15); border: none;">
                    <div class="d-flex align-items-center">
                        <i class="material-icons mr-2" style="color: ${iconColor}; font-size: 24px;">${icon}</i>
                        <div class="flex-grow-1">
                            <strong style="font-size: 14px;">${message}</strong>
                        </div>
                        <button type="button" class="close ml-2" data-dismiss="alert" aria-label="Close"
                                style="font-size: 18px; opacity: 0.7;">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                </div>
            `;

            $('body').append(alert);

            // Auto-hide after 4 seconds with smooth animation
            setTimeout(() => {
                $('.warehouse-alert').fadeOut(300, function() {
                    $(this).remove();
                });
            }, 4000);
        }
    </script>
@endpush