@extends('layouts.admin-simple')

@section('title', 'Item Details - ' . $item->item_code)

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.reports.index') }}">Reports</a></li>
    <li class="breadcrumb-item"><a href="{{ route('warehouse.reports.inventory') }}">Inventory Report</a></li>
    <li class="breadcrumb-item active">{{ $item->item_code }}</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">{{ $item->item_code }} - Detailed Analysis</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">{{ $item->item_description }}</p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.reports.inventory') }}" class="btn btn-sm btn-outline-secondary mr-2">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to Report
            </a>
            <button type="button" onclick="printItemDetails()" class="btn btn-sm btn-info">
                <i class="material-icons mr-1" style="font-size: 16px;">print</i>
                Print Details
            </button>
        </div>
    </div>
@endsection

@section('content')
    <!-- Item Summary -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">info</i>
                Item Information
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <table class="table table-sm table-borderless">
                        <tr>
                            <td width="40%"><strong>Item Code:</strong></td>
                            <td>{{ $item->item_code }}</td>
                        </tr>
                        <tr>
                            <td><strong>Description:</strong></td>
                            <td>{{ $item->item_description }}</td>
                        </tr>
                        <tr>
                            <td><strong>Category:</strong></td>
                            <td>{{ $item->category->category_name ?? 'Unknown' }}</td>
                        </tr>
                        <tr>
                            <td><strong>Unit of Measure:</strong></td>
                            <td>{{ $item->unit_of_measure }}</td>
                        </tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <table class="table table-sm table-borderless">
                        <tr>
                            <td width="40%"><strong>Total Quantity:</strong></td>
                            <td><strong>{{ number_format($inventoryDetails->sum('quantity'), 2) }} {{ $item->unit_of_measure }}</strong></td>
                        </tr>
                        <tr>
                            <td><strong>Total Value:</strong></td>
                            <td><strong>AED {{ number_format($inventoryDetails->sum('total_value'), 2) }}</strong></td>
                        </tr>
                        <tr>
                            <td><strong>Purchase History:</strong></td>
                            <td>{{ $pricingHistory->count() }} purchase operations</td>
                        </tr>
                        <tr>
                            <td><strong>Storage Locations:</strong></td>
                            <td>{{ $inventoryDetails->groupBy('division')->count() }} divisions</td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Pricing History -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">attach_money</i>
                Purchase Price History ({{ $pricingHistory->count() }} records)
            </h6>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th>Date</th>
                            <th>Operation</th>
                            <th>Supplier</th>
                            <th>Quantity</th>
                            <th>Unit Price (Original)</th>
                            <th>Unit Price (د.إ)</th>
                            <th>Total Value (د.إ)</th>
                            <th>Batch</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($pricingHistory as $purchase)
                            <tr>
                                <td>{{ $purchase->date->format('d M, Y') }}</td>
                                <td>
                                    <span class="badge badge-outline-primary">{{ $purchase->operation_number }}</span>
                                </td>
                                <td>{{ $purchase->supplier }}</td>
                                <td class="text-right">{{ number_format($purchase->quantity, 2) }}</td>
                                <td class="text-right">
                                    {{ $purchase->currency }} {{ number_format($purchase->original_unit_price, 2) }}
                                </td>
                                <td class="text-right">
                                    <strong>AED {{ number_format($purchase->unit_price, 2) }}</strong>
                                </td>
                                <td class="text-right">
                                    <strong>AED {{ number_format($purchase->total_price, 2) }}</strong>
                                </td>
                                <td>{{ $purchase->batch_number ?: '-' }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="text-center py-3">
                                    <span class="text-muted">No purchase history found</span>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Current Inventory Breakdown -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">inventory_2</i>
                Current Inventory Breakdown ({{ $inventoryDetails->count() }} batches)
            </h6>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th>Division</th>
                            <th>Location</th>
                            <th>Batch Number</th>
                            <th>Quantity</th>
                            <th>Unit Price</th>
                            <th>Total Value</th>
                            <th>Production Date</th>
                            <th>Expiry Date</th>
                            <th>Days to Expiry</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($inventoryDetails as $inventory)
                            <tr class="{{ $inventory->days_until_expiry !== null && $inventory->days_until_expiry < 0 ? 'table-danger' : ($inventory->days_until_expiry !== null && $inventory->days_until_expiry <= 30 ? 'table-warning' : '') }}">
                                <td>
                                    <span class="badge badge-light">{{ $inventory->division }}</span>
                                </td>
                                <td>{{ $inventory->location ?: '-' }}</td>
                                <td>
                                    <code>{{ $inventory->batch_number ?: '-' }}</code>
                                </td>
                                <td class="text-right">
                                    <strong>{{ number_format($inventory->quantity, 2) }}</strong> {{ $item->unit_of_measure }}
                                </td>
                                <td class="text-right">
                                    AED {{ number_format($inventory->unit_price, 2) }}
                                </td>
                                <td class="text-right">
                                    <strong>AED {{ number_format($inventory->total_value, 2) }}</strong>
                                </td>
                                <td class="text-center">
                                    {{ $inventory->production_date ? $inventory->production_date->format('d M, Y') : '-' }}
                                </td>
                                <td class="text-center">
                                    @if($inventory->expiry_date)
                                        {{ $inventory->expiry_date->format('d M, Y') }}
                                    @else
                                        -
                                    @endif
                                </td>
                                <td class="text-center">
                                    @if($inventory->days_until_expiry !== null)
                                        @if($inventory->days_until_expiry < 0)
                                            <span class="text-danger font-weight-bold">Expired ({{ abs($inventory->days_until_expiry) }} days ago)</span>
                                        @elseif($inventory->days_until_expiry <= 30)
                                            <span class="text-warning font-weight-bold">{{ $inventory->days_until_expiry }} days</span>
                                        @else
                                            <span class="text-success">{{ $inventory->days_until_expiry }} days</span>
                                        @endif
                                    @else
                                        -
                                    @endif
                                </td>
                                <td class="text-center">
                                    <span class="badge badge-{{
                                        $inventory->status === 'in_stock' ? 'success' :
                                        ($inventory->status === 'low_stock' ? 'warning' : 'danger')
                                    }}">
                                        {{ ucfirst(str_replace('_', ' ', $inventory->status)) }}
                                    </span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="10" class="text-center py-3">
                                    <span class="text-muted">No current inventory found</span>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Stock Movements -->
    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h6 class="card-title mb-0 d-flex align-items-center">
                <i class="material-icons mr-2">swap_vert</i>
                Stock Movements ({{ $stockMovements->total() }} total)
            </h6>
            <div class="d-flex align-items-center">
                <span class="text-muted mr-3">
                    Showing {{ $stockMovements->firstItem() ?? 0 }} - {{ $stockMovements->lastItem() ?? 0 }} of {{ $stockMovements->total() }}
                </span>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-hover mb-0" id="stockMovementsTable">
                    <thead class="bg-light">
                        <tr>
                            <th style="width: 150px;">Date</th>
                            <th style="width: 100px;">Type</th>
                            <th style="width: 120px;" class="text-right">Quantity</th>
                            <th style="width: 180px;">Reference</th>
                            <th>Notes</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($stockMovements as $movement)
                            @php
                                // Get reference number based on reference_type
                                $referenceNumber = 'N/A';
                                $reference = null;

                                // Map reference_type to model class
                                $referenceModel = match($movement->reference_type) {
                                    'incoming' => \App\Models\Warehouse\IncomingTransaction::class,
                                    'supplier_delivery', 'material_request', 'foc_transfer' => \App\Models\Warehouse\IncomingOperation::class,
                                    'outgoing', 'OutgoingTransaction', 'foc_dispatch' => \App\Models\Warehouse\OutgoingTransaction::class,
                                    'return' => \App\Models\Warehouse\ReturnTransaction::class,
                                    'DirectDelivery', 'direct_delivery', 'App\Models\DirectDelivery' => \App\Models\DirectDelivery::class,
                                    'MaterialTransferRequest', 'material_transfer', 'App\Models\Warehouse\MaterialTransferRequest' => \App\Models\Warehouse\MaterialTransferRequest::class,
                                    'material_transfer_issue' => \App\Models\Warehouse\MaterialTransferIssue::class,
                                    'site_transfer' => \App\Models\Warehouse\MaterialSiteTransfer::class,
                                    'opening_stock_import', 'condition_conversion' => \App\Models\Warehouse\IncomingOperation::class,
                                    default => null
                                };

                                if ($referenceModel && $movement->reference_id) {
                                    $reference = $referenceModel::find($movement->reference_id);
                                }

                                if ($reference) {
                                    if (method_exists($reference, 'getReferenceNumberAttribute') || isset($reference->reference_number)) {
                                        $referenceNumber = $reference->reference_number;
                                    } elseif (isset($reference->operation_number)) {
                                        $referenceNumber = $reference->operation_number;
                                    } elseif (isset($reference->material_request_number)) {
                                        $referenceNumber = $reference->material_request_number;
                                    } elseif (isset($reference->return_number)) {
                                        $referenceNumber = $reference->return_number;
                                    } elseif (isset($reference->delivery_note_number)) {
                                        $referenceNumber = $reference->delivery_note_number ?: $reference->lpo_number;
                                    } elseif (isset($reference->lpo_number)) {
                                        $referenceNumber = $reference->lpo_number;
                                    } elseif (isset($reference->transfer_request_number)) {
                                        $referenceNumber = $reference->transfer_request_number;
                                    } elseif (isset($reference->delivery_number)) {
                                        $referenceNumber = $reference->delivery_number;
                                    } else {
                                        $referenceNumber = strtoupper(str_replace('_', '-', $movement->reference_type)) . '-' . str_pad($reference->id, 6, '0', STR_PAD_LEFT);
                                    }
                                } elseif ($movement->reference_type === 'stock_adjustment') {
                                    $referenceNumber = 'ADJ-' . str_pad($movement->id, 6, '0', STR_PAD_LEFT);
                                } elseif ($movement->reference_type) {
                                    $referenceNumber = strtoupper(str_replace('_', '-', $movement->reference_type)) . '-' . str_pad($movement->reference_id, 6, '0', STR_PAD_LEFT);
                                }

                                // Determine badge class based on movement type
                                $badgeClass = match($movement->movement_type) {
                                    'in', 'transfer_in' => 'badge-success',
                                    'out', 'transfer_out' => 'badge-danger',
                                    'return' => 'badge-info',
                                    'adjustment' => 'badge-warning',
                                    'transfer' => 'badge-primary',
                                    default => 'badge-secondary'
                                };
                                $badgeText = match($movement->movement_type) {
                                    'in' => 'Stock In',
                                    'out' => 'Stock Out',
                                    'transfer_in' => 'Transfer In',
                                    'transfer_out' => 'Transfer Out',
                                    'return' => 'Return',
                                    'adjustment' => 'Adjustment',
                                    'transfer' => 'Transfer',
                                    default => ucfirst(str_replace('_', ' ', $movement->movement_type))
                                };

                                // Determine if this movement increases or decreases stock
                                $isIncrease = in_array($movement->movement_type, ['in', 'return', 'transfer_in'])
                                    || ($movement->movement_type === 'adjustment' && $movement->quantity_after > $movement->quantity_before);
                            @endphp
                            <tr>
                                <td>{{ $movement->created_at->format('d M, Y H:i') }}</td>
                                <td>
                                    <span class="badge {{ $badgeClass }}">{{ $badgeText }}</span>
                                </td>
                                <td class="text-right">
                                    @if($isIncrease)
                                        <span class="text-success font-weight-bold">+{{ number_format($movement->quantity_moved, 2) }}</span>
                                    @else
                                        <span class="text-danger font-weight-bold">-{{ number_format($movement->quantity_moved, 2) }}</span>
                                    @endif
                                    {{ $item->unit_of_measure }}
                                </td>
                                <td><code>{{ $referenceNumber }}</code></td>
                                <td>{{ Str::limit($movement->notes, 50) ?? '-' }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" class="text-center py-3">
                                    <span class="text-muted">No stock movements found</span>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
        @if($stockMovements->hasPages())
            <div class="card-footer bg-white">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="text-muted small">
                        Page {{ $stockMovements->currentPage() }} of {{ $stockMovements->lastPage() }}
                    </div>
                    <div>
                        {{ $stockMovements->links('pagination::bootstrap-4') }}
                    </div>
                </div>
            </div>
        @endif
    </div>

    <!-- Price Analysis Summary -->
    <div class="row">
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2">analytics</i>
                        Price Analysis
                    </h6>
                </div>
                <div class="card-body">
                    @if($pricingHistory->count() > 0)
                        <div class="list-group list-group-flush">
                            <div class="list-group-item d-flex justify-content-between px-0">
                                <span><strong>Lowest Purchase Price:</strong></span>
                                <span class="text-success font-weight-bold">AED {{ number_format($pricingHistory->min('unit_price'), 2) }}</span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between px-0">
                                <span><strong>Highest Purchase Price:</strong></span>
                                <span class="text-danger font-weight-bold">AED {{ number_format($pricingHistory->max('unit_price'), 2) }}</span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between px-0">
                                <span><strong>Average Purchase Price:</strong></span>
                                <span class="text-primary font-weight-bold">AED {{ number_format($pricingHistory->avg('unit_price'), 2) }}</span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between px-0">
                                <span><strong>Current Weighted Average:</strong></span>
                                <span class="text-info font-weight-bold">
                                    AED {{ $inventoryDetails->sum('quantity') > 0 ? number_format($inventoryDetails->sum('total_value') / $inventoryDetails->sum('quantity'), 2) : '0.00' }}
                                </span>
                            </div>
                            <div class="list-group-item d-flex justify-content-between px-0">
                                <span><strong>Price Variance:</strong></span>
                                <span class="text-warning font-weight-bold">
                                    AED {{ number_format($pricingHistory->max('unit_price') - $pricingHistory->min('unit_price'), 2) }}
                                </span>
                            </div>
                        </div>
                    @else
                        <div class="text-center text-muted">
                            <p>No pricing data available</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2">donut_large</i>
                        Inventory Distribution
                    </h6>
                </div>
                <div class="card-body">
                    @if($inventoryDetails->count() > 0)
                        <div class="list-group list-group-flush">
                            @foreach($inventoryDetails->groupBy('division') as $division => $items)
                                <div class="list-group-item d-flex justify-content-between align-items-center px-0">
                                    <div>
                                        <div class="font-weight-medium">{{ $division }}</div>
                                        <small class="text-muted">{{ $items->count() }} batches</small>
                                    </div>
                                    <div class="text-right">
                                        <div class="font-weight-bold">{{ number_format($items->sum('quantity'), 2) }} {{ $item->unit_of_measure }}</div>
                                        <small class="text-muted">AED {{ number_format($items->sum('total_value'), 2) }}</small>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <div class="text-center text-muted">
                            <p>No inventory distribution data available</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
    <style>
        .table-borderless td {
            border: none;
            padding: 0.25rem 0.5rem;
        }

        .badge-outline-primary {
            color: #007bff;
            border: 1px solid #007bff;
            background-color: transparent;
        }

        .table th {
            border-top: none;
            font-weight: 600;
            color: #495057;
            font-size: 12px;
        }

        .table td {
            font-size: 13px;
            vertical-align: middle;
        }

        .list-group-item {
            border-left: none;
            border-right: none;
        }

        code {
            font-size: 12px;
            color: #6c757d;
            background-color: #f8f9fa;
            padding: 2px 6px;
            border-radius: 3px;
        }

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

        .table-warning {
            background-color: rgba(255, 193, 7, 0.1);
        }
    </style>
@endpush

@push('scripts')
    <script>
        function printItemDetails() {
            window.print();
        }
    </script>
@endpush