@extends('layouts.admin-simple')

@section('title', 'Inventory Aging Report')

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Inventory</li>
    <li class="breadcrumb-item active">Aging Report</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 Aging Report</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Analyze inventory based on age and identify slow-moving items</p>
        </div>
        @can('warehouse.inventory.view')
        <div class="page-actions-right d-flex align-items-center">
            <button type="button" onclick="refreshAgingReport()" class="btn btn-sm btn-success mr-2" title="Refresh aging data">
                <i class="material-icons mr-1" style="font-size: 16px;">refresh</i>
                Refresh
            </button>

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

            <button type="button" onclick="printAgingReport()" class="btn btn-sm btn-primary" title="Print aging report">
                <i class="material-icons mr-1" style="font-size: 16px;">print</i>
                Print
            </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="Fresh Items (0-30 Days)"
                :value="collect($agingInventory)->where('age_days', '<=', 30)->count()"
                icon="new_releases"
                color="success"
                subtitle="Recent inventory"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Moderate Age (31-90 Days)"
                :value="collect($agingInventory)->whereBetween('age_days', [31, 90])->count()"
                icon="schedule"
                color="info"
                subtitle="Moderately aged items"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Slow Moving (91-180 Days)"
                :value="collect($agingInventory)->whereBetween('age_days', [91, 180])->count()"
                icon="slow_motion_video"
                color="warning"
                subtitle="Requires attention"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <x-warehouse.stats-card
                title="Dead Stock (180+ Days)"
                :value="collect($agingInventory)->where('age_days', '>', 180)->count()"
                icon="block"
                color="danger"
                subtitle="Immediate action needed"
            />
        </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>
                Aging Report Filters
            </h5>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('warehouse.inventory.aging-report') }}">
                <div class="row">
                    <div class="col-xl-2 col-md-6 mb-3">
                        <label class="form-label">Aging Period</label>
                        <select name="days" id="days" class="form-control" data-placeholder="Select Period">
                            <option value="30" {{ $days == 30 ? 'selected' : '' }}>30 Days</option>
                            <option value="60" {{ $days == 60 ? 'selected' : '' }}>60 Days</option>
                            <option value="90" {{ $days == 90 ? 'selected' : '' }}>90 Days</option>
                            <option value="180" {{ $days == 180 ? 'selected' : '' }}>180 Days</option>
                            <option value="365" {{ $days == 365 ? 'selected' : '' }}>1 Year</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" data-placeholder="All Categories">
                            <option value=""></option>
                            @foreach(collect($agingInventory)->pluck('category')->unique()->filter() as $category)
                                <option value="{{ $category }}">{{ $category }}</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">Age Group</label>
                        <select id="filter-age-group" class="form-control" data-placeholder="All Age Groups">
                            <option value=""></option>
                            <option value="fresh">Fresh (0-30 days)</option>
                            <option value="moderate">Moderate (31-90 days)</option>
                            <option value="slow">Slow Moving (91-180 days)</option>
                            <option value="dead">Dead Stock (180+ days)</option>
                        </select>
                    </div>

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

                <div class="d-flex justify-content-between align-items-center mt-3 pt-3 border-top">
                    <button type="submit" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 18px; vertical-align: middle;">update</i>
                        Update Report
                    </button>

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

    <!-- Breakdown Cards Row -->
    <div class="row mb-4">
        <!-- Age Distribution Card -->
        <div class="col-lg-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0 d-flex align-items-center">
                        <i class="material-icons mr-2">pie_chart</i>
                        Age Distribution Analysis
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-lg-6 col-md-6 mb-3">
                            <div class="text-center">
                                <div class="h5 mb-1 text-success">{{ collect($agingInventory)->where('age_days', '<=', 30)->count() }}</div>
                                <div class="small text-muted">Fresh Items</div>
                                <div class="small text-success">
                                    <span class="dirham-symbol-inline">{{ number_format(collect($agingInventory)->where('age_days', '<=', 30)->sum('value'), 0) }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 mb-3">
                            <div class="text-center">
                                <div class="h5 mb-1 text-info">{{ collect($agingInventory)->whereBetween('age_days', [31, 90])->count() }}</div>
                                <div class="small text-muted">Moderate Age</div>
                                <div class="small text-info">
                                    <span class="dirham-symbol-inline">{{ number_format(collect($agingInventory)->whereBetween('age_days', [31, 90])->sum('value'), 0) }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 mb-3">
                            <div class="text-center">
                                <div class="h5 mb-1 text-warning">{{ collect($agingInventory)->whereBetween('age_days', [91, 180])->count() }}</div>
                                <div class="small text-muted">Slow Moving</div>
                                <div class="small text-warning">
                                    <span class="dirham-symbol-inline">{{ number_format(collect($agingInventory)->whereBetween('age_days', [91, 180])->sum('value'), 0) }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-6 col-md-6 mb-3">
                            <div class="text-center">
                                <div class="h5 mb-1 text-danger">{{ collect($agingInventory)->where('age_days', '>', 180)->count() }}</div>
                                <div class="small text-muted">Dead Stock</div>
                                <div class="small text-danger">
                                    <span class="dirham-symbol-inline">{{ number_format(collect($agingInventory)->where('age_days', '>', 180)->sum('value'), 0) }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Division Breakdown Card -->
        <div class="col-lg-6">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0 d-flex align-items-center">
                        <i class="material-icons mr-2">business</i>
                        Aging by Division
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        @if(isset($divisionBreakdown) && $divisionBreakdown->count() > 0)
                            @foreach($divisionBreakdown->take(6) as $division)
                            <div class="col-lg-4 col-md-6 mb-3">
                                <div class="text-center">
                                    <div class="h5 mb-1 text-info"><span class="dirham-symbol-inline">{{ number_format($division['total_value'], 0) }}</span></div>
                                    <div class="small text-muted">{{ $division['division'] }}</div>
                                    <div class="small text-success">{{ $division['item_count'] }} items ({{ $division['avg_age_days'] }} days avg)</div>
                                </div>
                            </div>
                            @endforeach
                        @else
                            <div class="col-12">
                                <div class="text-center text-muted py-3">
                                    <i class="material-icons" style="font-size: 48px; opacity: 0.3;">business</i>
                                    <p class="mb-0 mt-2">No division data available</p>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Aging Report 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>
                Aging Report Details ({{ collect($agingInventory)->count() }} items)
            </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">
            @if(collect($agingInventory)->count() > 0)
                <div class="table-responsive">
                    <table id="aging-table" class="table table-hover">
                        <thead>
                            <tr>
                                <th>Item</th>
                                <th>Category</th>
                                <th>Division</th>
                                <th>Current Stock</th>
                                <th>Age (Days)</th>
                                <th>Last Transaction</th>
                                <th>Value</th>
                                <th>Age Category</th>
                                <th class="text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach(collect($agingInventory) as $item)
                                @php
                                    $agingCategory = '';
                                    $badgeClass = '';
                                    $rowClass = '';
                                    if ($item['age_days'] <= 30) {
                                        $agingCategory = 'Fresh';
                                        $badgeClass = 'badge-success';
                                        $rowClass = 'table-success-light';
                                    } elseif ($item['age_days'] <= 90) {
                                        $agingCategory = 'Moderate';
                                        $badgeClass = 'badge-info';
                                        $rowClass = 'table-info-light';
                                    } elseif ($item['age_days'] <= 180) {
                                        $agingCategory = 'Slow Moving';
                                        $badgeClass = 'badge-warning';
                                        $rowClass = 'table-warning-light';
                                    } else {
                                        $agingCategory = 'Dead Stock';
                                        $badgeClass = 'badge-danger';
                                        $rowClass = 'table-danger-light';
                                    }
                                @endphp
                                <tr class="aging-row {{ $rowClass }}" data-age-days="{{ $item['age_days'] }}" data-category="{{ $item['category'] ?? '' }}" data-division="{{ $item['division'] ?? '' }}">
                                    <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_name'] ?? 'U', 0, 1) }}</span>
                                                </div>
                                            </div>
                                            <div>
                                                <div class="font-weight-medium">{{ $item['item_name'] ?? 'Unknown Item' }}</div>
                                                <small class="text-muted">{{ $item['item_code'] ?? 'No Code' }}</small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        @if($item['category'] ?? null)
                                            <div>
                                                <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">category</i>
                                                <span>{{ $item['category'] }}</span>
                                            </div>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if(!empty($item['division']))
                                            <div>
                                                <i class="material-icons text-muted mr-1" style="font-size: 14px; vertical-align: middle;">business</i>
                                                <span>{{ $item['division'] }}</span>
                                            </div>
                                        @else
                                            <span class="text-muted">No Division</span>
                                        @endif
                                    </td>
                                    <td>
                                        <div>
                                            <div class="font-weight-medium mb-1">{{ number_format($item['current_stock'] ?? 0, 2) }}</div>
                                            <small class="text-muted">units</small>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge {{ $badgeClass }} age-badge" data-age="{{ $item['age_days'] ?? 0 }}">
                                            {{ $item['age_days'] ?? 0 }} days
                                        </span>
                                    </td>
                                    <td>
                                        <div>
                                            <div class="small">{{ $item['last_transaction'] ?? 'N/A' }}</div>
                                        </div>
                                    </td>
                                    <td class="text-right">
                                        <div class="font-weight-medium"><span class="dirham-symbol-inline">{{ number_format($item['value'] ?? 0, 2) }}</span></div>
                                    </td>
                                    <td>
                                        <span class="badge {{ $badgeClass }}">{{ $agingCategory }}</span>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-primary view-item-btn"
                                                    title="View Item Details"
                                                    data-item-code="{{ $item['item_code'] ?? '' }}">
                                                <i class="material-icons" style="font-size: 16px;">visibility</i>
                                            </button>
                                            @can('warehouse.inventory.adjust')
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-warning adjust-stock-btn"
                                                    title="Adjust Stock"
                                                    data-item-code="{{ $item['item_code'] ?? '' }}">
                                                <i class="material-icons" style="font-size: 16px;">tune</i>
                                            </button>
                                            @endcan
                                            <button type="button"
                                                    class="btn btn-sm btn-outline-info history-btn"
                                                    title="View History"
                                                    data-item-code="{{ $item['item_code'] ?? '' }}">
                                                <i class="material-icons" style="font-size: 16px;">history</i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                        <tfoot>
                            <tr class="table-info">
                                <th colspan="6" class="text-right">Total Items:</th>
                                <th class="text-right">
                                    <strong><span class="dirham-symbol-inline">{{ number_format(collect($agingInventory)->sum('value'), 2) }}</span></strong>
                                </th>
                                <th colspan="2">
                                    <strong>{{ collect($agingInventory)->count() }} items</strong>
                                </th>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <!-- Summary and Recommendations -->
                <div class="row mt-4">
                    <div class="col-md-6">
                        <div class="card border-left-info">
                            <div class="card-body">
                                <h6 class="font-weight-bold text-info">Report Summary</h6>
                                <ul class="mb-0">
                                    <li>Total Items Analyzed: {{ collect($agingInventory)->count() }}</li>
                                    <li>Average Age: {{ collect($agingInventory)->avg('age_days') ? round(collect($agingInventory)->avg('age_days')) : 0 }} days</li>
                                    <li>Total Value: <span class="dirham-symbol-inline">{{ number_format(collect($agingInventory)->sum('value'), 2) }}</span></li>
                                    <li>Report Generated: {{ now()->format('F j, Y g:i A') }}</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card border-left-warning">
                            <div class="card-body">
                                <h6 class="font-weight-bold text-warning">Recommendations</h6>
                                <ul class="mb-0">
                                    @if(collect($agingInventory)->where('age_days', '>', 180)->count() > 0)
                                        <li>Review {{ collect($agingInventory)->where('age_days', '>', 180)->count() }} dead stock items for disposal</li>
                                    @endif
                                    @if(collect($agingInventory)->whereBetween('age_days', [91, 180])->count() > 0)
                                        <li>Monitor {{ collect($agingInventory)->whereBetween('age_days', [91, 180])->count() }} slow-moving items</li>
                                    @endif
                                    <li>Consider promotional sales for aged inventory</li>
                                    <li>Review reorder points for slow-moving items</li>
                                    <li>Implement FIFO inventory rotation practices</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            @else
                <div class="text-center py-5">
                    <i class="material-icons text-success mb-3" style="font-size: 48px;">check_circle</i>
                    <h5 class="text-muted">No Aging Inventory Found</h5>
                    <p class="text-muted">All inventory items are within the acceptable age range of {{ $days }} days.</p>
                    <a href="{{ route('warehouse.inventory.index') }}" class="btn btn-primary">
                        <i class="material-icons mr-1">inventory</i>
                        View Current Inventory
                    </a>
                </div>
            @endif
        </div>
    </div>
@endsection

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

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

        .table-success-light {
            background-color: rgba(40, 167, 69, 0.1);
        }

        .table-info-light {
            background-color: rgba(23, 162, 184, 0.1);
        }

        .table-warning-light {
            background-color: rgba(255, 193, 7, 0.1);
        }

        .table-danger-light {
            background-color: rgba(220, 53, 69, 0.1);
        }

        .age-badge {
            font-weight: 500;
            font-size: 0.75rem;
        }

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

        @media print {
            .btn, .card-header, .no-print, .page-actions-right {
                display: none !important;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
            .table-responsive {
                overflow: visible !important;
            }
        }

        .distribution-card {
            border-left: 4px solid #007bff;
            transition: all 0.15s ease-in-out;
        }

        .distribution-card:hover {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }

        /* UAE Dirham Symbol */
        .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;
        }
    </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/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
        let agingTable;

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

            initializeDataTable();
            initializeEventHandlers();

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

            // Auto-refresh on aging period change
            $('#days').change(function() {
                $(this).closest('form').submit();
            });
        });

        function initializeDataTable() {
            agingTable = $('#aging-table').DataTable({
                processing: false,
                serverSide: false,
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                order: [[4, 'desc']], // Sort by age descending (column shifted due to Division)
                language: {
                    processing: '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></div>',
                    emptyTable: 'No aging inventory found',
                    zeroRecords: 'No matching items found'
                },
                columnDefs: [
                    { orderable: false, targets: [8] }, // Actions column
                    { searchable: false, targets: [8] }, // Actions column
                    { type: 'num', targets: [3, 4, 6] }, // Numeric columns (shifted by 1)
                    { className: 'text-right', targets: [6] } // Right-align value column (shifted by 1)
                ],
                drawCallback: function(settings) {
                    $('#entries-per-page').val(settings._iDisplayLength);
                    initializeEventHandlers(); // Re-initialize handlers for new DOM elements
                }
            });
        }

        function initializeEventHandlers() {
            // View item button
            $('.view-item-btn').off('click').on('click', function() {
                const itemCode = $(this).data('item-code');
                showItemDetails(itemCode);
            });

            // Adjust stock button
            $('.adjust-stock-btn').off('click').on('click', function() {
                const itemCode = $(this).data('item-code');
                adjustItemStock(itemCode);
            });

            // History button
            $('.history-btn').off('click').on('click', function() {
                const itemCode = $(this).data('item-code');
                showItemHistory(itemCode);
            });
        }

        function applyAgingFilters() {
            const category = $('#filter-category').val();
            const division = $('#filter-division').val();
            const ageGroup = $('#filter-age-group').val();
            const search = $('#filter-search').val();

            // Clear any previous custom filters
            $.fn.dataTable.ext.search = $.fn.dataTable.ext.search.filter(function(fn) {
                return fn.name !== 'agingFilter';
            });

            // Apply DataTable search
            agingTable.search(search);

            // Apply custom filters
            const agingFilter = function(settings, data, dataIndex) {
                if (settings.nTable.id !== 'aging-table') {
                    return true;
                }

                const row = agingTable.row(dataIndex).node();
                const rowCategory = $(row).data('category') || '';
                const rowDivision = $(row).data('division') || '';
                const rowAgeDays = parseInt($(row).data('age-days')) || 0;

                // Category filter
                if (category && rowCategory.indexOf($('#filter-category option:selected').text()) === -1) {
                    return false;
                }

                // Division filter
                if (division) {
                    const selectedDivisionText = $('#filter-division option:selected').text();
                    if (rowDivision.indexOf(selectedDivisionText) === -1) {
                        return false;
                    }
                }

                // Age group filter
                if (ageGroup) {
                    switch (ageGroup) {
                        case 'fresh':
                            if (rowAgeDays > 30) return false;
                            break;
                        case 'moderate':
                            if (rowAgeDays <= 30 || rowAgeDays > 90) return false;
                            break;
                        case 'slow':
                            if (rowAgeDays <= 90 || rowAgeDays > 180) return false;
                            break;
                        case 'dead':
                            if (rowAgeDays <= 180) return false;
                            break;
                    }
                }

                return true;
            };

            // Name the function for later removal
            Object.defineProperty(agingFilter, 'name', { value: 'agingFilter' });
            $.fn.dataTable.ext.search.push(agingFilter);

            agingTable.draw();
        }

        function clearAgingFilters() {
            $('#filter-category, #filter-division, #filter-age-group, #filter-search').val('');

            // Clear custom filters
            $.fn.dataTable.ext.search = $.fn.dataTable.ext.search.filter(function(fn) {
                return fn.name !== 'agingFilter';
            });

            agingTable.search('').draw();
        }

        function refreshAgingReport() {
            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;

            setTimeout(() => {
                btn.innerHTML = originalHtml;
                btn.disabled = false;
                location.reload();
            }, 1500);
        }

        function exportAgingReport() {
            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 printAgingReport() {
            window.print();
        }

        function showItemDetails(itemCode) {
            showAlert(`Item details for ${itemCode} will be implemented`, 'info');
        }

        function adjustItemStock(itemCode) {
            showAlert(`Stock adjustment for ${itemCode} will be implemented`, 'info');
        }

        function showItemHistory(itemCode) {
            showAlert(`Item history for ${itemCode} will be implemented`, 'info');
        }

        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);
        }

        // Apply filters when filter controls change
        $('#filter-category, #filter-division, #filter-age-group, #filter-search').on('change keyup', function() {
            applyAgingFilters();
        });
    </script>
@endpush