@extends('layouts.admin-simple')

@section('title', 'Inventory Dashboard')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item active">Inventory Dashboard</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">Inventory Dashboard</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Real-time inventory monitoring and analytics</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <button type="button" onclick="refreshDashboard()" class="btn btn-sm btn-outline-primary mr-2" title="Refresh dashboard data">
                <i class="material-icons mr-1" style="font-size: 16px;">refresh</i>
                Refresh
            </button>
            <button type="button" onclick="exportInventoryReport()" class="btn btn-sm btn-info mr-2" title="Export inventory report">
                <i class="material-icons mr-1" style="font-size: 16px;">file_download</i>
                Export
            </button>
            <div class="badge badge-success">
                <i class="material-icons mr-1" style="font-size: 12px;">schedule</i>
                <span id="lastUpdated">Just now</span>
            </div>
        </div>
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    @php
        $goodQtyTotal = \App\Models\Warehouse\Inventory::sum('quantity_available') ?: 0;
        $damagedQtyTotal = \App\Models\DamagedItem::sum('quantity') ?: 0;
        $totalStockValue = \App\Models\Warehouse\Inventory::sum('total_value') ?: 0;
        $lowStockCount = \App\Models\Warehouse\Inventory::join('items', 'inventory.item_id', '=', 'items.id')
            ->where('items.reorder_point', '>', 0)
            ->where('inventory.quantity_available', '>', 0)
            ->whereColumn('inventory.quantity_available', '<=', 'items.reorder_point')
            ->count();
        $recentMovementsCount = \App\Models\Warehouse\StockMovement::where('created_at', '>=', now()->subDays(7))->count();
    @endphp
    <div class="row mb-4">
        <div class="col-lg-2 col-md-6 mb-4">
            <div id="totalItems">
                <x-warehouse.stats-card
                    title="Total Quantity"
                    :value="$goodQtyTotal + $damagedQtyTotal"
                    icon="inventory_2"
                    color="primary"
                    :subtitle="\App\Models\Warehouse\ItemCategory::count() . ' categories'"
                    :loading="false"
                />
            </div>
        </div>

        <div class="col-lg-2 col-md-6 mb-4">
            <div id="totalStockValue">
                <x-warehouse.stats-card
                    title="Total Stock Value"
                    :value="$totalStockValue"
                    icon="attach_money"
                    color="success"
                    subtitle="Live valuation"
                    :loading="false"
                    :currency="true"
                />
            </div>
        </div>

        <div class="col-lg-2 col-md-6 mb-4">
            <div id="goodQualityCount">
                <x-warehouse.stats-card
                    title="Good Quality Qty"
                    :value="$goodQtyTotal"
                    icon="check_circle"
                    color="success"
                    subtitle="Total available units"
                    :loading="false"
                />
            </div>
        </div>

        <div class="col-lg-2 col-md-6 mb-4">
            <div id="damagedItemsCount">
                <x-warehouse.stats-card
                    title="Damaged Qty"
                    :value="$damagedQtyTotal"
                    icon="error"
                    color="danger"
                    subtitle="Total damaged units"
                    :loading="false"
                />
            </div>
        </div>

        <div class="col-lg-2 col-md-6 mb-4">
            <div id="lowStockCount">
                <x-warehouse.stats-card
                    title="Low Stock Items"
                    :value="$lowStockCount"
                    icon="priority_high"
                    color="warning"
                    subtitle="Requiring attention"
                    :loading="false"
                    :url="route('warehouse.inventory.low-stock')"
                />
            </div>
        </div>

        <div class="col-lg-2 col-md-6 mb-4">
            <div id="recentMovements">
                <x-warehouse.stats-card
                    title="Recent Movements"
                    :value="$recentMovementsCount"
                    icon="swap_horiz"
                    color="info"
                    subtitle="Last 7 days"
                    :loading="false"
                />
            </div>
        </div>

    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <div class="col-xl-6 mb-4">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 d-flex align-items-center">
                        <i class="material-icons mr-2">trending_up</i>
                        Stock Movement Trends
                    </h5>
                    <div class="btn-group btn-group-sm" role="group">
                        <button type="button" class="btn btn-outline-primary active" onclick="updateChart('7d')">7 Days</button>
                        <button type="button" class="btn btn-outline-primary" onclick="updateChart('30d')">30 Days</button>
                        <button type="button" class="btn btn-outline-primary" onclick="updateChart('90d')">90 Days</button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 350px;">
                        <canvas id="stockMovementChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0 d-flex align-items-center">
                        <i class="material-icons mr-2">donut_large</i>
                        Category Distribution
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 350px;">
                        <canvas id="categoryChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 mb-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0 d-flex align-items-center">
                        <i class="material-icons mr-2">business</i>
                        Division Distribution
                    </h5>
                </div>
                <div class="card-body">
                    <div class="chart-container" style="position: relative; height: 350px;">
                        <canvas id="divisionChart"></canvas>
                    </div>
                </div>
            </div>
        </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>
                Filters
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-xl-2 col-md-6 mb-3">
                    <label class="form-label">Stock Status</label>
                    <select id="filter-status" class="form-control">
                        <option value="">All Status</option>
                        <option value="in-stock">In Stock</option>
                        <option value="low-stock">Low Stock</option>
                        <option value="out-of-stock">Out of Stock</option>
                    </select>
                </div>

                <div class="col-xl-2 col-md-6 mb-3">
                    <label class="form-label">Category</label>
                    <select id="filter-category" class="form-control">
                        <option value="">All Categories</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">
                        <option value="">All Divisions</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">Stock Range</label>
                    <div class="d-flex">
                        <input type="number" id="filter-stock-min" placeholder="Min" min="0" class="form-control mr-2">
                        <input type="number" id="filter-stock-max" placeholder="Max" min="0" class="form-control">
                    </div>
                </div>

                <div class="col-xl-2 col-md-6 mb-3">
                    <label class="form-label">Value Range</label>
                    <div class="d-flex">
                        <input type="number" id="filter-value-min" placeholder="Min د.إ" min="0" step="0.01" class="form-control mr-2">
                        <input type="number" id="filter-value-max" placeholder="Max د.إ" min="0" step="0.01" 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>

    <!-- Inventory Table -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">list</i>
                Current Inventory Levels
            </h5>
            <div class="d-flex align-items-center">
                <label class="text-muted mr-2" style="font-size: 14px;">Show:</label>
                <select id="entries-per-page" class="form-control form-control-sm" style="width: auto;">
                    <option value="10">10</option>
                    <option value="25">25</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
                <span class="text-muted ml-2" style="font-size: 14px;">entries</span>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <div class="warehouse-loading-overlay" id="loadingOverlay" style="display: none;">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">Loading...</span>
                    </div>
                </div>
                <div class="warehouse-table-wrapper">
                    <table id="inventory-table" class="table table-hover mb-0 warehouse-table">
                        <thead class="thead-light">
                            <tr>
                                <th style="white-space: nowrap; min-width: 200px;">Item</th>
                                <th style="white-space: nowrap; min-width: 150px;">Category</th>
                                <th style="white-space: nowrap; min-width: 150px;">Division</th>
                                <th style="white-space: nowrap; min-width: 120px;">Current Stock</th>
                                <th style="white-space: nowrap; min-width: 100px;">Min Level</th>
                                <th style="white-space: nowrap; min-width: 100px;">Reserved</th>
                                <th style="white-space: nowrap; min-width: 120px;">Value</th>
                                <th style="white-space: nowrap; min-width: 120px;">Status</th>
                                <th style="white-space: nowrap; min-width: 150px;">Last Movement</th>
                                <th class="text-right" style="white-space: nowrap; min-width: 100px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Data will be populated by DataTables -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="{{ asset('admin-assets/css/warehouse-reports.css') }}">
    <style>
        .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;
        }

        .status-in-stock {
            color: #155724;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
        }

        .status-low-stock {
            color: #856404;
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
        }

        .status-out-of-stock {
            color: #721c24;
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
        }

        .card {
            transition: transform 0.2s ease-in-out;
        }

        .card:hover {
            transform: translateY(-2px);
        }

        .pulse {
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

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

        /* Chart responsiveness */
        .chart-container {
            position: relative;
            width: 100%;
        }

        .chart-container canvas {
            display: block;
            width: 100% !important;
            height: auto !important;
        }

        /* Responsive chart heights */
        @media (max-width: 768px) {
            .chart-container {
                height: 300px !important;
            }
        }

        @media (min-width: 769px) and (max-width: 1200px) {
            .chart-container {
                height: 350px !important;
            }
        }

        @media (min-width: 1201px) {
            .chart-container {
                height: 400px !important;
            }
        }

        /* Dirham symbol styles */
        .dirham-symbol-inline {
            position: relative;
        }

        .dirham-symbol-inline::before {
            content: '';
            display: inline-block;
            width: 16px;
            height: 16px;
            margin-right: 4px;
            background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 1000 870' width='16' height='16' style='fill: currentColor;'%3E%3Cpath d='m88.3 1c0.4 0.6 2.6 3.3 4.7 5.9 15.3 18.2 26.8 47.8 33 85.1 4.1 24.5 4.3 32.2 4.3 125.6v87h-41.8c-38.2 0-42.6-0.2-50.1-1.7-11.8-2.5-24-9.2-32.2-17.8-6.5-6.9-6.3-7.3-5.9 13.6 0.5 17.3 0.7 19.2 3.2 28.6 4 14.9 9.5 26 17.8 35.9 11.3 13.6 22.8 21.2 39.2 26.3 3.5 1 10.9 1.4 37.1 1.6l32.7 0.5v43.3 43.4l-46.1-0.3-46.3-0.3-8-3.2c-9.5-3.8-13.8-6.6-23.1-14.9l-6.8-6.1 0.4 19.1c0.5 17.7 0.6 19.7 3.1 28.7 8.7 31.8 29.7 54.5 57.4 61.9 6.9 1.9 9.6 2 38.5 2.4l30.9 0.4v89.6c0 54.1-0.3 94-0.8 100.8-0.5 6.2-2.1 17.8-3.5 25.9-6.5 37.3-18.2 65.4-35 83.6l-3.4 3.7h169.1c101.1 0 176.7-0.4 187.8-0.9 19.5-1 63-5.3 72.8-7.4 3.1-0.6 8.9-1.5 12.7-2.1 8.1-1.2 21.5-4 40.8-8.9 27.2-6.8 52-15.3 76.3-26.1 7.6-3.4 29.4-14.5 35.2-18 3.1-1.8 6.8-4 8.2-4.7 3.9-2.1 10.4-6.3 19.9-13.1 4.7-3.4 9.4-6.7 10.4-7.4 4.2-2.8 18.7-14.9 25.3-21 25.1-23.1 46.1-48.8 62.4-76.3 2.3-4 5.3-9 6.6-11.1 3.3-5.6 16.9-33.6 18.2-37.8 0.6-1.9 1.4-3.9 1.8-4.3 2.6-3.4 17.6-50.6 19.4-60.9 0.6-3.3 0.9-3.8 3.4-4.3 1.6-0.3 24.9-0.3 51.8-0.1 53.8 0.4 53.8 0.4 65.7 5.9 6.7 3.1 8.7 4.5 16.1 11.2 9.7 8.7 8.8 10.1 8.2-11.7-0.4-12.8-0.9-20.7-1.8-23.9-3.4-12.3-4.2-14.9-7.2-21.1-9.8-21.4-26.2-36.7-47.2-44l-8.2-3-33.4-0.4-33.3-0.5 0.4-11.7c0.4-15.4 0.4-45.9-0.1-61.6l-0.4-12.6 44.6-0.2c38.2-0.2 45.3 0 49.5 1.1 12.6 3.5 21.1 8.3 31.5 17.8l5.8 5.4v-14.8c0-17.6-0.9-25.4-4.5-37-7.1-23.5-21.1-41-41.1-51.8-13-7-13.8-7.2-58.5-7.5-26.2-0.2-39.9-0.6-40.6-1.2-0.6-0.6-1.1-1.6-1.1-2.4 0-0.8-1.5-7.1-3.5-13.9-23.4-82.7-67.1-148.4-131-197.1-8.7-6.7-30-20.8-38.6-25.6-3.3-1.9-6.9-3.9-7.8-4.5-4.2-2.3-28.3-14.1-34.3-16.6-3.6-1.6-8.3-3.6-10.4-4.4-35.3-15.3-94.5-29.8-139.7-34.3-7.4-0.7-17.2-1.8-21.7-2.2-20.4-2.3-48.7-2.6-209.4-2.6-135.8 0-169.9 0.3-169.4 1zm330.7 43.3c33.8 2 54.6 4.6 78.9 10.5 74.2 17.6 126.4 54.8 164.3 117 3.5 5.8 18.3 36 20.5 42.1 10.5 28.3 15.6 45.1 20.1 67.3 1.1 5.4 2.6 12.6 3.3 16 0.7 3.3 1 6.4 0.7 6.7-0.5 0.4-100.9 0.6-223.3 0.5l-222.5-0.2-0.3-128.5c-0.1-70.6 0-129.3 0.3-130.4l0.4-1.9h71.1c39 0 78 0.4 86.5 0.9zm297.5 350.3c0.7 4.3 0.7 77.3 0 80.9l-0.6 2.7-227.5-0.2-227.4-0.3-0.2-42.4c-0.2-23.3 0-42.7 0.2-43.1 0.3-0.5 97.2-0.8 227.7-0.8h227.2zm-10.2 171.7c0.5 1.5-1.9 13.8-6.8 33.8-5.6 22.5-13.2 45.2-20.9 62-3.8 8.6-13.3 27.2-15.6 30.7-1.1 1.6-4.3 6.7-7.1 11.2-18 28.2-43.7 53.9-73 72.9-10.7 6.8-32.7 18.4-38.6 20.2-1.2 0.3-2.5 0.9-3 1.3-0.7 0.6-9.8 4-20.4 7.8-19.5 6.9-56.6 14.4-86.4 17.5-19.3 1.9-22.4 2-96.7 2h-76.9v-129.7-129.8l220.9-0.4c121.5-0.2 221.6-0.5 222.4-0.7 0.9-0.1 1.8 0.5 2.1 1.2z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-size: contain;
            background-position: center;
            vertical-align: middle;
        }

        /* Stats cards responsive layout - Better spacing for 4 cards */
        .row .col-lg-3 {
            display: flex;
            align-items: stretch;
        }

        /* Responsive breakpoints for better card spacing */
        @media (max-width: 1200px) {
            .row .col-lg-3 {
                flex: 0 0 50%;
                max-width: 50%;
            }
        }

        @media (max-width: 768px) {
            .row .col-lg-3 {
                flex: 0 0 100%;
                max-width: 100%;
            }
        }

        /* Stats card container spacing */
        .row.mb-4 {
            margin-left: -7.5px;
            margin-right: -7.5px;
        }

        .row.mb-4 > [class*="col-"] {
            padding-left: 7.5px;
            padding-right: 7.5px;
        }

        /* DataTables search and entries padding */
        .dataTables_wrapper .dataTables_length {
            padding: 15px 20px;
        }

        .dataTables_wrapper .dataTables_filter {
            padding: 15px 20px 15px 0;
        }

        .dataTables_wrapper .dataTables_filter input {
            padding: 8px 15px;
            min-width: 300px;
        }

        /* Filter buttons styling - smaller size to match form fields */
        .card-body .btn-primary.btn-sm,
        .card-body .btn-outline-secondary.btn-sm {
            height: 32px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 0 12px;
            font-size: 13px;
        }

        .card-body .btn-primary.btn-sm .material-icons,
        .card-body .btn-outline-secondary.btn-sm .material-icons {
            font-size: 16px !important;
        }

        /* Warehouse table styling */
        .warehouse-table-container {
            position: relative;
            min-height: 200px;
        }

        .warehouse-loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10;
        }

        .warehouse-table-wrapper {
            overflow-x: auto;
        }

        .warehouse-table {
            width: 100%;
        }

        .warehouse-table thead th {
            background-color: #f8f9fa;
            font-weight: 600;
            border-bottom: 2px solid #dee2e6;
            padding: 12px 15px;
        }

        .warehouse-table tbody td {
            padding: 12px 15px;
            vertical-align: middle;
        }
    </style>
@endpush

@push('scripts')
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script>
        let inventoryTable;
        let stockMovementChart;
        let categoryChart;
        let divisionChart;
        let refreshInterval;

        $(document).ready(function() {
            initializeDataTable();
            initializeCharts();
            startAutoRefresh();

            // Entries per page change handler
            $('#entries-per-page').change(function() {
                inventoryTable.page.len($(this).val()).draw();
            });
        });

        function initializeDataTable() {
            // Set up CSRF token for all AJAX requests
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            inventoryTable = $('#inventory-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: '{{ route("warehouse.inventory.index") }}',
                    type: 'GET',
                    data: function(d) {
                        d.ajax_request = true;
                        d.status = $('#filter-status').val();
                        d.category = $('#filter-category').val();
                        d.division = $('#filter-division').val();
                        d.stock_min = $('#filter-stock-min').val();
                        d.stock_max = $('#filter-stock-max').val();
                        d.value_min = $('#filter-value-min').val();
                        d.value_max = $('#filter-value-max').val();
                        return d;
                    },
                    error: function(xhr, error, code) {
                        console.error('DataTable Ajax Error:', error, code);
                        showAlert('Error loading inventory data. Please refresh the page.', 'error');
                    }
                },
                columns: [
                    {
                        data: null,
                        name: 'item_name',
                        render: function(data, type, row) {
                            return `
                                <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;">${row.item_name.charAt(0).toUpperCase()}</span>
                                        </div>
                                    </div>
                                    <div>
                                        <div class="font-weight-medium">${row.item_name}</div>
                                        <small class="text-muted">${row.item_code || 'No code'}</small>
                                    </div>
                                </div>
                            `;
                        }
                    },
                    {
                        data: 'category',
                        name: 'category',
                        render: function(data) {
                            return `
                                <div>
                                    <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">category</i>
                                    <span>${data || 'Uncategorized'}</span>
                                </div>
                            `;
                        }
                    },
                    {
                        data: 'division',
                        name: 'division',
                        render: function(data) {
                            if (!data) {
                                return '<span class="text-muted">No Division</span>';
                            }
                            return `
                                <div>
                                    <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">business</i>
                                    <span>${data}</span>
                                </div>
                            `;
                        }
                    },
                    {
                        data: 'current_stock',
                        name: 'current_stock',
                        className: 'text-right',
                        render: function(data, type, row) {
                            const color = data <= 0 ? 'danger' : (data <= row.min_level ? 'warning' : 'success');
                            return `<span class="badge badge-${color}">${data} ${row.unit || 'units'}</span>`;
                        }
                    },
                    {
                        data: 'min_level',
                        name: 'min_level',
                        className: 'text-right',
                        render: function(data) {
                            return data ? `<span class="badge badge-info">${data}</span>` : '<span class="text-muted">Not set</span>';
                        }
                    },
                    {
                        data: 'reserved_stock',
                        name: 'reserved_stock',
                        className: 'text-right',
                        render: function(data) {
                            return data > 0 ? `<span class="badge badge-warning">${data}</span>` : '<span class="text-muted">0</span>';
                        }
                    },
                    {
                        data: 'stock_value',
                        name: 'stock_value',
                        className: 'text-right',
                        render: function(data) {
                            return data ? `<span class="dirham-symbol-inline">${parseFloat(data).toFixed(2)}</span>` : '<span class="dirham-symbol-inline">0.00</span>';
                        }
                    },
                    {
                        data: null,
                        name: 'status',
                        render: function(data, type, row) {
                            let statusClass = 'status-in-stock';
                            let statusText = 'In Stock';

                            if (row.current_stock <= 0) {
                                statusClass = 'status-out-of-stock';
                                statusText = 'Out of Stock';
                            } else if (row.current_stock <= row.min_level) {
                                statusClass = 'status-low-stock';
                                statusText = 'Low Stock';
                            }

                            return `<span class="status-badge ${statusClass}">${statusText}</span>`;
                        }
                    },
                    {
                        data: 'last_movement',
                        name: 'last_movement',
                        render: function(data) {
                            return `
                                <div>
                                    <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">schedule</i>
                                    <span>${data || 'No movements'}</span>
                                </div>
                            `;
                        }
                    },
                    {
                        data: null,
                        name: 'actions',
                        orderable: false,
                        searchable: false,
                        render: function(data) {
                            return `
                                <div class="btn-group" role="group">
                                    <button onclick="viewMovements(${data.id})" class="btn btn-sm btn-outline-info" title="View Movements">
                                        <i class="material-icons" style="font-size: 16px;">history</i>
                                    </button>
                                </div>
                            `;
                        }
                    }
                ],
                order: [[0, 'asc']],
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                language: {
                    processing: '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>',
                    emptyTable: 'No inventory items found',
                    zeroRecords: 'No matching items found'
                },
                drawCallback: function(settings) {
                    $('#entries-per-page').val(settings._iDisplayLength);
                }
            });
        }

        function initializeCharts() {
            // Stock Movement Chart
            const ctx1 = document.getElementById('stockMovementChart').getContext('2d');
            stockMovementChart = new Chart(ctx1, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: 'Stock In',
                        data: [],
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        tension: 0.1,
                        fill: true
                    }, {
                        label: 'Stock Out',
                        data: [],
                        borderColor: 'rgb(255, 99, 132)',
                        backgroundColor: 'rgba(255, 99, 132, 0.2)',
                        tension: 0.1,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        intersect: false,
                        mode: 'index'
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                            labels: {
                                padding: 20,
                                usePointStyle: true
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleColor: 'white',
                            bodyColor: 'white',
                            borderColor: 'rgba(255,255,255,0.1)',
                            borderWidth: 1
                        }
                    },
                    scales: {
                        x: {
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.1)'
                            }
                        }
                    }
                }
            });

            // Category Distribution Chart
            const ctx2 = document.getElementById('categoryChart').getContext('2d');
            categoryChart = new Chart(ctx2, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: [
                            'rgba(255, 99, 132, 0.8)',
                            'rgba(54, 162, 235, 0.8)',
                            'rgba(255, 205, 86, 0.8)',
                            'rgba(75, 192, 192, 0.8)',
                            'rgba(153, 102, 255, 0.8)',
                            'rgba(255, 159, 64, 0.8)',
                            'rgba(255, 206, 86, 0.8)',
                            'rgba(75, 192, 192, 0.8)'
                        ],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                usePointStyle: true,
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleColor: 'white',
                            bodyColor: 'white',
                            borderColor: 'rgba(255,255,255,0.1)',
                            borderWidth: 1,
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} (${percentage}%)`;
                                }
                            }
                        }
                    },
                    cutout: '60%'
                }
            });

            // Division Distribution Chart
            const ctx3 = document.getElementById('divisionChart').getContext('2d');
            divisionChart = new Chart(ctx3, {
                type: 'doughnut',
                data: {
                    labels: [],
                    datasets: [{
                        data: [],
                        backgroundColor: [
                            'rgba(102, 126, 234, 0.8)',
                            'rgba(118, 75, 162, 0.8)',
                            'rgba(237, 137, 54, 0.8)',
                            'rgba(72, 187, 120, 0.8)',
                            'rgba(236, 72, 153, 0.8)',
                            'rgba(56, 178, 172, 0.8)',
                            'rgba(245, 101, 101, 0.8)',
                            'rgba(66, 153, 225, 0.8)'
                        ],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 15,
                                usePointStyle: true,
                                font: {
                                    size: 11
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleColor: 'white',
                            bodyColor: 'white',
                            borderColor: 'rgba(255,255,255,0.1)',
                            borderWidth: 1,
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ${value} items (${percentage}%)`;
                                }
                            }
                        }
                    },
                    cutout: '60%'
                }
            });

            // Load initial chart data
            loadChartData();
        }

        function loadChartData() {
            // Load stock movement data
            $.get('{{ route("warehouse.inventory.index") }}', { chart_data: 'movements' })
                .done(function(data) {
                    if (data.movements) {
                        stockMovementChart.data.labels = data.movements.labels;
                        stockMovementChart.data.datasets[0].data = data.movements.stock_in;
                        stockMovementChart.data.datasets[1].data = data.movements.stock_out;
                        stockMovementChart.update();
                    }
                });

            // Load category distribution data
            $.get('{{ route("warehouse.inventory.index") }}', { chart_data: 'categories' })
                .done(function(data) {
                    if (data.categories) {
                        categoryChart.data.labels = data.categories.labels;
                        categoryChart.data.datasets[0].data = data.categories.values;
                        categoryChart.update();
                    }
                });

            // Load division distribution data
            $.get('{{ route("warehouse.inventory.index") }}', { chart_data: 'divisions' })
                .done(function(data) {
                    if (data.divisions) {
                        divisionChart.data.labels = data.divisions.labels;
                        divisionChart.data.datasets[0].data = data.divisions.values;
                        divisionChart.update();
                    }
                });
        }

        function applyFilters() {
            inventoryTable.draw();
        }

        function clearFilters() {
            $('#filter-status, #filter-category, #filter-division, #filter-stock-min, #filter-stock-max, #filter-value-min, #filter-value-max').val('');
            inventoryTable.draw();
        }

        function refreshDashboard() {
            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>Refreshing...';
            btn.disabled = true;

            // Show refresh animation
            $('#lastUpdated').addClass('pulse');

            // Refresh metrics
            $.get('{{ route("warehouse.inventory.index") }}', { refresh: 'metrics' })
                .done(function(data) {
                    if (data.metrics) {
                        // Update stats cards
                        updateStatsCard('#totalItems', data.metrics.total_items);
                        updateStatsCard('#totalStockValue', data.metrics.total_value);
                        updateStatsCard('#goodQualityCount', data.metrics.good_quality_count);
                        updateStatsCard('#damagedItemsCount', data.metrics.damaged_items_count);
                        updateStatsCard('#lowStockCount', data.metrics.low_stock_count);
                        updateStatsCard('#recentMovements', data.metrics.recent_movements);
                    }

                    // Refresh table
                    inventoryTable.draw();

                    // Refresh charts
                    loadChartData();

                    // Update timestamp
                    $('#lastUpdated').text('Just now').removeClass('pulse');

                    btn.innerHTML = originalHtml;
                    btn.disabled = false;
                    showAlert('Dashboard refreshed successfully!', 'success');
                })
                .fail(function() {
                    btn.innerHTML = originalHtml;
                    btn.disabled = false;
                    showAlert('Failed to refresh dashboard', 'error');
                });
        }

        function updateStatsCard(selector, value) {
            const element = $(selector + ' h3');
            if (element.length) {
                element.text(value);
            }
        }

        function startAutoRefresh() {
            // Auto-refresh every 5 minutes
            refreshInterval = setInterval(function() {
                // Refresh silently without showing buttons
                $.get('{{ route("warehouse.inventory.index") }}', { refresh: 'metrics' })
                    .done(function(data) {
                        if (data.metrics) {
                            updateStatsCard('#totalItems', data.metrics.total_items);
                            updateStatsCard('#totalStockValue', data.metrics.total_value);
                            updateStatsCard('#goodQualityCount', data.metrics.good_quality_count);
                            updateStatsCard('#damagedItemsCount', data.metrics.damaged_items_count);
                            updateStatsCard('#lowStockCount', data.metrics.low_stock_count);
                            updateStatsCard('#recentMovements', data.metrics.recent_movements);
                        }
                        $('#lastUpdated').text('Just now');
                    });
            }, 300000);
        }

        function updateChart(period) {
            // Update active button
            $('.btn-group .btn').removeClass('active');
            $(`button[onclick="updateChart('${period}')"]`).addClass('active');

            // Load new data for period
            $.get('{{ route("warehouse.inventory.index") }}', { chart_data: 'movements', period: period })
                .done(function(data) {
                    if (data.movements) {
                        stockMovementChart.data.labels = data.movements.labels;
                        stockMovementChart.data.datasets[0].data = data.movements.stock_in;
                        stockMovementChart.data.datasets[1].data = data.movements.stock_out;
                        stockMovementChart.update();
                    }
                });
        }

        function adjustStock(itemId) {
            window.location.href = `{{ url('warehouse/inventory') }}/${itemId}/adjust`;
        }

        function viewMovements(itemId) {
            window.location.href = `{{ url('warehouse/inventory') }}/${itemId}/stock-movements`;
        }

        function exportInventoryReport() {
            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 is not yet implemented', 'info');
            }, 800);
        }

        // Handle window resize for chart responsiveness
        $(window).on('resize', function() {
            if (stockMovementChart) {
                stockMovementChart.resize();
            }
            if (categoryChart) {
                categoryChart.resize();
            }
            if (divisionChart) {
                divisionChart.resize();
            }
        });

        // Cleanup on page unload
        $(window).on('beforeunload', function() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
        });

        function showAlert(message, type) {
            const alertClass = type === 'success' ? 'alert-success' : type === 'info' ? 'alert-info' : 'alert-danger';
            const alert = `
                <div class="alert ${alertClass} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;">
                    ${message}
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            `;
            $('body').append(alert);
            setTimeout(() => $('.alert').alert('close'), 5000);
        }
    </script>
@endpush