@extends('layouts.admin-simple')

@section('title', 'Reference Allocations - ' . $item->item_description)

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item">Reports</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.reports.stock-on-project') }}">Stock on Project</a></li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.reports.stock-on-project.details', $project->id) }}">{{ $project->project_name }}</a></li>
    <li class="breadcrumb-item active">Reference Allocations</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">Reference Allocations</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">
                Item: {{ $item->item_description }} ({{ $item->item_code }}) |
                Project: {{ $project->project_name }}
            </p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.reports.stock-on-project.details', $project->id) }}" class="btn btn-sm btn-secondary mr-2">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to Stock Details
            </a>
        </div>
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    <div class="row mb-4 warehouse-stats-row">
        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total References"
                :value="$references->count()"
                icon="receipt_long"
                color="primary"
                subtitle="Reference allocations"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Released Quantity"
                :value="number_format($totals['total_released'], 2)"
                icon="output"
                color="info"
                subtitle="Total quantity released"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Net Available"
                :value="number_format($totals['total_net'], 2)"
                icon="check_circle"
                color="success"
                subtitle="Net available quantity"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Value"
                :value="'AED ' . number_format($totals['total_value'], 2)"
                icon="attach_money"
                color="warning"
                subtitle="Total allocation value"
            />
        </div>
    </div>

    <!-- Item Information Card -->
    <div class="card mb-4">
        <div class="card-header warehouse-report-header">
            <h5 class="mb-0 warehouse-report-title">
                <i class="material-icons align-middle mr-2">inventory_2</i>
                Item Information
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <div class="d-flex align-items-center mb-2">
                        <strong class="mr-2">Item Code:</strong>
                        <code class="text-primary">{{ $item->item_code }}</code>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="d-flex align-items-center mb-2">
                        <strong class="mr-2">Description:</strong>
                        <span>{{ $item->item_description }}</span>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="d-flex align-items-center mb-2">
                        <strong class="mr-2">Unit:</strong>
                        <span class="badge badge-secondary">{{ $item->unit_of_measure }}</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="card mb-4 warehouse-filters-panel">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="material-icons align-middle mr-2">filter_list</i>
                Filters
            </h5>
        </div>
        <div class="card-body">
            <form id="filterForm" class="warehouse-filter-form" method="GET" action="{{ route('warehouse.reports.item-reference-allocations', [$project->id, $item->id]) }}">
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Reference Type</label>
                        <select name="type" class="form-control warehouse-select2" data-placeholder="All Types">
                            <option value="">All Types</option>
                            <option value="Material Request" {{ request('type') == 'Material Request' ? 'selected' : '' }}>Material Request</option>
                            <option value="Direct Delivery" {{ request('type') == 'Direct Delivery' ? 'selected' : '' }}>Direct Delivery</option>
                            <option value="Material Transfer" {{ request('type') == 'Material Transfer' ? 'selected' : '' }}>Material Transfer</option>
                        </select>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control warehouse-select2" data-placeholder="All Statuses">
                            <option value="">All Statuses</option>
                            <option value="successful" {{ request('status') == 'successful' ? 'selected' : '' }}>Successful</option>
                            <option value="delivered" {{ request('status') == 'delivered' ? 'selected' : '' }}>Delivered</option>
                            <option value="approved" {{ request('status') == 'approved' ? 'selected' : '' }}>Approved</option>
                            <option value="received" {{ request('status') == 'received' ? 'selected' : '' }}>Received</option>
                        </select>
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">Date From</label>
                        <input type="date" name="date_from" value="{{ request('date_from') }}" class="form-control">
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">Date To</label>
                        <input type="date" name="date_to" value="{{ request('date_to') }}" class="form-control">
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary btn-block">
                            <i class="material-icons" style="font-size: 18px; vertical-align: middle;">search</i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Export Buttons -->
    <div class="row warehouse-export-buttons mb-4">
        <div class="col-12 text-right">
            <button class="btn btn-success warehouse-export-btn" data-export="excel">
                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">download</i>
                Export Excel
            </button>
            <button class="btn btn-info warehouse-export-btn" data-export="pdf">
                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">picture_as_pdf</i>
                Export PDF
            </button>
            <button class="btn btn-secondary warehouse-export-btn" data-action="print">
                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">print</i>
                Print
            </button>
        </div>
    </div>

    <!-- Reference Allocations 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">receipt_long</i>
                Reference Allocations - {{ $item->item_description }} ({{ $references->count() }} references)
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <!-- Loading Overlay -->
                <div class="warehouse-loading-overlay" id="tableLoadingOverlay">
                    <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 allocations data...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    @if($references->count() > 0)
                        <table class="table table-hover mb-0 warehouse-table">
                            <thead class="thead-light">
                                <tr>
                                    <th style="min-width: 120px;">Type</th>
                                    <th style="min-width: 180px;">Reference #</th>
                                    <th style="min-width: 100px;">Date</th>
                                    <th style="min-width: 150px;">Requested By / Supplier</th>
                                    <th style="min-width: 150px;">Division / From</th>
                                    <th style="min-width: 100px;">Status</th>
                                    <th style="min-width: 90px;" class="text-right">Released</th>
                                    <th style="min-width: 90px;" class="text-right">Returned</th>
                                    <th style="min-width: 90px;" class="text-right">Dmg. Returned</th>
                                    <th style="min-width: 90px;" class="text-right">Transferred</th>
                                    <th style="min-width: 90px;" class="text-right">Net Qty</th>
                                    <th style="min-width: 100px;" class="text-right">Unit Price</th>
                                    <th style="min-width: 120px;" class="text-right">Value (AED)</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($references as $ref)
                                    @php
                                        $typeClass = $ref['type'] === 'Material Request' ? 'badge-primary' :
                                                    ($ref['type'] === 'Direct Delivery' ? 'badge-success' :
                                                    ($ref['type'] === 'FOC Transfer' ? 'badge-warning' : 'badge-info'));
                                        $statusClass = in_array(strtolower($ref['status']), ['successful', 'delivered', 'approved', 'received', 'fully dispatched', 'partially dispatched', 'transferred', 'dispatched']) ?
                                                       'badge-success' : 'badge-warning';
                                    @endphp
                                    <tr>
                                        <td>
                                            <span class="badge {{ $typeClass }}">{{ $ref['type'] }}</span>
                                        </td>
                                        <td>
                                            <strong>{{ $ref['reference_number'] }}</strong>
                                        </td>
                                        <td>{{ $ref['date'] }}</td>
                                        <td>{{ $ref['requested_by'] }}</td>
                                        <td>{{ $ref['division'] }}</td>
                                        <td>
                                            <span class="badge {{ $statusClass }}">{{ $ref['status'] }}</span>
                                        </td>
                                        <td class="text-right">
                                            {{ number_format($ref['quantity_released'], 2) }}
                                        </td>
                                        <td class="text-right">
                                            @if($ref['quantity_returned'] > 0)
                                                <span class="text-warning">{{ number_format($ref['quantity_returned'], 2) }}</span>
                                            @else
                                                <span class="text-muted">0.00</span>
                                            @endif
                                        </td>
                                        <td class="text-right">
                                            @if(($ref['quantity_damaged'] ?? 0) > 0)
                                                <span class="text-danger">{{ number_format($ref['quantity_damaged'], 2) }}</span>
                                            @else
                                                <span class="text-muted">0.00</span>
                                            @endif
                                        </td>
                                        <td class="text-right">
                                            @if($ref['quantity_transferred'] > 0)
                                                <span class="text-info">{{ number_format($ref['quantity_transferred'], 2) }}</span>
                                            @else
                                                <span class="text-muted">0.00</span>
                                            @endif
                                        </td>
                                        <td class="text-right">
                                            <strong class="text-success">{{ number_format($ref['net_quantity'], 2) }}</strong>
                                        </td>
                                        <td class="text-right warehouse-cell-currency">
                                            {{ number_format($ref['unit_price'] ?? 0, 2) }}
                                        </td>
                                        <td class="text-right warehouse-cell-currency">
                                            <strong class="text-success">{{ number_format($ref['total_value'], 2) }}</strong>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                            <tfoot class="thead-light">
                                <tr>
                                    <th colspan="6"><strong>Total</strong></th>
                                    <th class="text-right">
                                        <strong class="text-primary">{{ number_format($totals['total_released'], 2) }}</strong>
                                    </th>
                                    <th class="text-right">
                                        <strong class="text-warning">{{ number_format($totals['total_returned'], 2) }}</strong>
                                    </th>
                                    <th class="text-right">
                                        <strong class="text-danger">{{ number_format($totals['total_damaged'] ?? 0, 2) }}</strong>
                                    </th>
                                    <th class="text-right">
                                        <strong class="text-info">{{ number_format($totals['total_transferred'], 2) }}</strong>
                                    </th>
                                    <th class="text-right">
                                        <strong class="text-success">{{ number_format($totals['total_net'], 2) }}</strong>
                                    </th>
                                    <th></th>
                                    <th class="text-right">
                                        <strong class="text-success">AED {{ number_format($totals['total_value'], 2) }}</strong>
                                    </th>
                                </tr>
                            </tfoot>
                        </table>
                    @else
                        <div class="warehouse-empty-state p-5 text-center">
                            <div class="warehouse-empty-icon mb-3">
                                <i class="material-icons" style="font-size: 64px; color: #ccc;">inbox</i>
                            </div>
                            <h5 class="warehouse-empty-title">No Reference Allocations Found</h5>
                            <p class="warehouse-empty-description text-muted">
                                No reference allocations found for this item in the selected project.<br>
                                This means the item hasn't been delivered or transferred to this project.
                            </p>
                            <div class="warehouse-empty-actions mt-3">
                                <a href="{{ route('warehouse.reports.stock-on-project.details', $project->id) }}" class="btn btn-primary">
                                    <i class="material-icons mr-1">arrow_back</i>
                                    Back to Stock Details
                                </a>
                            </div>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    <!-- Additional Information -->
    @if($references->count() > 0)
    <div class="card mt-4">
        <div class="card-header warehouse-report-header">
            <h5 class="mb-0 warehouse-report-title">
                <i class="material-icons align-middle mr-2">info</i>
                Allocation Summary
            </h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-4">
                    <div class="d-flex align-items-center p-3 bg-light rounded">
                        <div class="mr-3">
                            <div class="bg-primary text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 50px; height: 50px;">
                                <span class="font-weight-bold">{{ $references->where('type', 'Material Request')->count() }}</span>
                            </div>
                        </div>
                        <div>
                            <div class="font-weight-semibold">Material Requests</div>
                            <small class="text-muted">Inventory dispatch references</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="d-flex align-items-center p-3 bg-light rounded">
                        <div class="mr-3">
                            <div class="bg-success text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 50px; height: 50px;">
                                <span class="font-weight-bold">{{ $references->where('type', 'Direct Delivery')->count() }}</span>
                            </div>
                        </div>
                        <div>
                            <div class="font-weight-semibold">Direct Deliveries</div>
                            <small class="text-muted">Supplier direct delivery references</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="d-flex align-items-center p-3 bg-light rounded">
                        <div class="mr-3">
                            <div class="bg-info text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 50px; height: 50px;">
                                <span class="font-weight-bold">{{ $references->where('type', 'Material Transfer')->count() }}</span>
                            </div>
                        </div>
                        <div>
                            <div class="font-weight-semibold">Material Transfers</div>
                            <small class="text-muted">Project transfer references</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif
@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-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;
        }
    </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>
    $(document).ready(function() {
        // Initialize Select2 for filter dropdowns
        $('.warehouse-select2').select2({
            theme: 'bootstrap-5',
            allowClear: true,
            placeholder: function() {
                return $(this).data('placeholder') || 'Select...';
            }
        });

        // Hide loading overlay
        $('#tableLoadingOverlay').hide();

        // Export buttons functionality
        $('.warehouse-export-btn').on('click', function() {
            const exportType = $(this).data('export');
            const action = $(this).data('action');

            if (action === 'print') {
                window.print();
                return;
            }

            if (exportType) {
                // Build export URL with current filters
                const currentUrl = new URL(window.location.href);
                currentUrl.searchParams.set('export', exportType);
                window.location.href = currentUrl.toString();
            }
        });
    });
    </script>
@endpush
