@extends('layouts.admin-simple')

@section('title', 'Stock Details - ' . $project->project_name)

@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 active">{{ $project->project_name }}</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">{{ $project->project_name }} - Stock Details</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">
                Project: {{ $project->project_number ?: 'N/A' }} |
                Status: {{ ucfirst(str_replace('_', ' ', $project->status)) }}
            </p>
        </div>
        <div class="page-actions-right d-flex align-items-center">
            <a href="{{ route('warehouse.reports.stock-on-project') }}" class="btn btn-sm btn-secondary mr-2">
                <i class="material-icons mr-1" style="font-size: 16px;">arrow_back</i>
                Back to Report
            </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 Items"
                :value="$totalItems"
                icon="inventory_2"
                color="primary"
                subtitle="Unique items in project"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Quantity"
                :value="number_format($totalStock, 2)"
                icon="inventory"
                color="success"
                subtitle="Total stock quantity"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Value"
                :value="'AED ' . number_format($totalValue, 2)"
                icon="attach_money"
                color="info"
                subtitle="Total inventory value"
                :showDirham="true"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Project Created"
                :value="$project->created_at->format('M Y')"
                icon="date_range"
                color="warning"
                subtitle="Project start date"
            />
        </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.stock-on-project.details', $project->id) }}">
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" value="{{ request('search') }}" class="form-control"
                               placeholder="Item name, code or description">
                    </div>

                    <div class="col-md-3 mb-3">
                        <label class="form-label">Category</label>
                        <select name="category_id" class="form-control warehouse-select2" data-placeholder="All Categories">
                            <option value="">All Categories</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                                    {{ $category->category_name }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label class="form-label">Stock Status</label>
                        <select name="stock_status" class="form-control warehouse-select2" data-placeholder="All Stock Levels">
                            <option value="">All Stock Levels</option>
                            <option value="low_stock" {{ request('stock_status') == 'low_stock' ? 'selected' : '' }}>Low Stock</option>
                            <option value="out_of_stock" {{ request('stock_status') == 'out_of_stock' ? 'selected' : '' }}>Out of Stock</option>
                        </select>
                    </div>

                    <div class="col-md-3 mb-3">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-flex">
                            <button type="submit" class="btn btn-primary mr-2">
                                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">search</i>
                                Apply
                            </button>
                            <a href="{{ route('warehouse.reports.stock-on-project.details', $project->id) }}" class="btn btn-outline-secondary">
                                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">clear</i>
                                Clear
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Export Buttons -->
    <div class="row warehouse-export-buttons">
        <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>

    <!-- Stock Details 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">inventory</i>
                Stock Details - {{ $project->project_name }} ({{ $items->count() }} items)
            </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 stock data...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    @if($items->count() > 0)
                        <table class="table table-hover mb-0 warehouse-table">
                            <thead class="thead-light">
                                <tr>
                                    <th style="min-width: 90px;">Type</th>
                                    <th style="min-width: 250px;">Item</th>
                                    <th style="min-width: 120px;">Code</th>
                                    <th style="min-width: 120px;">Category</th>
                                    <th style="min-width: 80px;">Unit</th>
                                    <th style="min-width: 100px;" class="text-right">Effective Stock</th>
                                    <th style="min-width: 100px;" class="text-right">Total Delivered</th>
                                    <th style="min-width: 100px;" class="text-right">Returned Qty</th>
                                    <th style="min-width: 100px;" class="text-right">Damaged Qty</th>
                                    <th style="min-width: 100px;" class="text-right">Total Stock</th>
                                    <th style="min-width: 100px;" class="text-right">Min Stock</th>
                                    <th style="min-width: 120px;" class="text-right">Unit Cost (AED)</th>
                                    <th style="min-width: 120px;" class="text-right">Total Value (AED)</th>
                                    <th style="min-width: 80px;" class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($items as $item)
                                    @php
                                        // Include damaged stock (in FOC) as project is responsible
                                        $currentStock = ($item->project_stock ?? 0) ;
                                        $itemTotalValue = $currentStock * ($item->effective_unit_price ?? $item->unit_cost ?? 0);
                                        $isLowStock = $currentStock > 0 && $item->reorder_point > 0 && $currentStock <= $item->reorder_point;
                                        $isOutOfStock = $currentStock == 0;
                                    @endphp
                                    <tr>
                                        <td>
                                            @if(($item->goods_type ?? 'direct') === 'indirect')
                                                <span class="badge badge-warning">Indirect</span>
                                            @else
                                                <span class="badge badge-primary">Direct</span>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="mr-3">
                                                    <div class="bg-{{ $isOutOfStock ? 'danger' : ($isLowStock ? 'warning' : 'primary') }} text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 40px; height: 40px;">
                                                        <i class="material-icons" style="font-size: 20px;">inventory_2</i>
                                                    </div>
                                                </div>
                                                <div>
                                                    <div class="font-weight-medium">{{ Str::limit($item->item_description, 40) }}</div>
                                                    <small class="text-muted">{{ $item->item_code }}</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <code class="text-primary">{{ $item->item_code }}</code>
                                        </td>
                                        <td>
                                            @if($item->category)
                                                <span class="badge warehouse-badge warehouse-status-secondary">
                                                    {{ Str::limit($item->category->category_name, 15) }}
                                                </span>
                                            @else
                                                <span class="text-muted">-</span>
                                            @endif
                                        </td>
                                        <td>{{ $item->unit_of_measure }}</td>
                                        <td class="text-right">
                                            @php
                                                $netQty = ($item->total_delivered ?? 0) - ($item->total_returned ?? 0) - ($item->damaged_stock ?? 0) - ($item->total_transferred_out ?? 0);
                                            @endphp
                                            <strong class="text-{{ $netQty > 0 ? 'success' : ($netQty < 0 ? 'danger' : 'muted') }}">
                                                {{ number_format($netQty, 2) }}
                                            </strong>
                                        </td>
                                        <td class="text-right">
                                            <span class="badge badge-primary">{{ number_format($item->total_delivered ?? 0, 2) }}</span>
                                        </td>
                                        <td class="text-right">
                                            @if(($item->total_returned ?? 0) > 0)
                                                <span class="badge badge-warning">{{ number_format($item->total_returned, 2) }}</span>
                                            @else
                                                <span class="text-muted">0.00</span>
                                            @endif
                                        </td>
                                        <td class="text-right">
                                            @if(($item->damaged_stock ?? 0) > 0)
                                                <span class="badge badge-danger">{{ number_format($item->damaged_stock, 2) }}</span>
                                            @else
                                                <span class="text-muted">0.00</span>
                                            @endif
                                        </td>
                                        
                                        <td class="text-right">
                                            @if($isOutOfStock)
                                                <span class="badge badge-danger">0</span>
                                            @elseif($isLowStock)
                                                <span class="badge badge-warning">{{ number_format($currentStock, 2) }}</span>
                                            @else
                                                <span class="font-weight-medium text-success">{{ number_format($currentStock, 2) }}</span>
                                            @endif
                                        </td>
                                        <td class="text-right">
                                            <span class="text-muted">{{ number_format($item->min_stock_level) }}</span>
                                        </td>
                                        <td class="text-right warehouse-cell-currency">
                                            {{ number_format($item->effective_unit_price ?? $item->unit_cost ?? 0, 2) }}
                                        </td>
                                        <td class="text-right warehouse-cell-currency">
                                            <strong class="text-success">{{ number_format($itemTotalValue, 2) }}</strong>
                                        </td>
                                        <td class="text-center">
                                            @if(($item->goods_type ?? 'direct') === 'indirect')
                                                <a href="{{ route('warehouse.indirect-goods.catalog.show', $item->id) }}"
                                                   class="btn btn-sm btn-outline-primary"
                                                   title="View Indirect Good">
                                                    <i class="material-icons" style="font-size: 18px;">visibility</i>
                                                </a>
                                            @else
                                            <a href="{{ route('warehouse.reports.item-reference-allocations', [$project->id, $item->id]) }}"
                                               class="btn btn-sm btn-outline-primary"
                                               title="View Reference Allocations">
                                                <i class="material-icons" style="font-size: 18px;">visibility</i>
                                            </a>
                                            @endif
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                            <tfoot class="thead-light">
                                <tr>
                                    <th colspan="5"><strong>Total</strong></th>
                                    <th class="text-right">
                                        <strong class="text-success">{{ number_format($items->sum('total_delivered') - $items->sum('total_returned') - $items->sum('damaged_stock'), 2) }}</strong>

                                    </th>
                                    <th class="text-right">
                                        <strong class="text-primary">{{ number_format($items->sum('total_delivered'), 2) }}</strong>
                                    </th>
                                    <th class="text-right">
                                        <strong class="text-warning">{{ number_format($items->sum('total_returned'), 2) }}</strong>
                                    </th>
                                    <th></th>
                                    <th class="text-right">
                                        <strong class="text-primary">{{ number_format($totalStock, 2) }}</strong>
                                    </th>
                                    <th></th>
                                    <th></th>
                                    <th class="text-right">
                                        <strong class="text-success">AED {{ number_format($totalValue, 2) }}</strong>
                                    </th>
                                    <th></th>
                                </tr>
                            </tfoot>
                        </table>
                    @else
                        <div class="text-center py-5">
                            <i class="material-icons text-muted mb-3" style="font-size: 64px;">inventory</i>
                            <h5 class="text-muted mb-2">No Items Found</h5>
                            <p class="text-muted mb-0">
                                No items match your current filter criteria for this project.<br>
                                Try adjusting your filters or check if items have been assigned to this project.
                            </p>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>

    @if($items->count() > 0)
    <!-- Stock Status Summary -->
    <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">analytics</i>
                Stock Status Summary
            </h5>
        </div>
        <div class="card-body">
            @php
                $inStockCount = $items->filter(function($item) {
                    $stock = $item->project_stock ?? 0;
                    return $item->reorder_point > 0 ? $stock > $item->reorder_point : $stock > 0;
                })->count();

                $lowStockCount = $items->filter(function($item) {
                    $stock = $item->project_stock ?? 0;
                    return $stock > 0 && $item->reorder_point > 0 && $stock <= $item->reorder_point;
                })->count();

                $outOfStockCount = $items->filter(function($item) {
                    return ($item->project_stock ?? 0) == 0;
                })->count();
            @endphp

            <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-success text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 50px; height: 50px;">
                                <span class="font-weight-bold">{{ $inStockCount }}</span>
                            </div>
                        </div>
                        <div>
                            <div class="font-weight-semibold">Items in Stock</div>
                            <small class="text-muted">Above minimum stock level</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-warning text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 50px; height: 50px;">
                                <span class="font-weight-bold">{{ $lowStockCount }}</span>
                            </div>
                        </div>
                        <div>
                            <div class="font-weight-semibold">Low Stock Items</div>
                            <small class="text-muted">At or below minimum stock level</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-danger text-white d-flex align-items-center justify-content-center rounded-circle" style="width: 50px; height: 50px;">
                                <span class="font-weight-bold">{{ $outOfStockCount }}</span>
                            </div>
                        </div>
                        <div>
                            <div class="font-weight-semibold">Out of Stock Items</div>
                            <small class="text-muted">No stock available</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
