@extends('layouts.admin-simple')

@section('title', 'Materials Report')

@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 active">Materials Report</li>
@endsection

@section('page-title')
    <div class="page-title-left">
        <h3 class="mb-1">Materials Report</h3>
        <p class="text-muted mb-0" style="font-size: 13px;">Comprehensive materials analysis with pricing insights</p>
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Total Materials"
                :value="$items->total()"
                icon="inventory"
                color="primary"
                subtitle="All material items"
            />
        </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="account_balance_wallet"
                color="success"
                subtitle="Total materials value"
                :showDirham="true"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Low Stock Items"
                :value="$lowStockCount"
                icon="warning"
                color="warning"
                subtitle="Materials below reorder point"
            />
        </div>

        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Out of Stock"
                :value="$outOfStockCount"
                icon="error"
                color="danger"
                subtitle="Materials completely out of stock"
            />
        </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.materials') }}">
                <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="Material code or description">
                    </div>

                    <div class="col-md-3 mb-3">
                        <label class="form-label">Category</label>
                        <select name="category_id" id="filter-category" class="form-control" 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-2 mb-3">
                        <label class="form-label">Division</label>
                        <select name="division_id" id="filter-division" class="form-control" data-placeholder="All Divisions">
                            <option value="">All Divisions</option>
                            @foreach($divisions as $division)
                                <option value="{{ $division->id }}" {{ request('division_id') == $division->id ? 'selected' : '' }}>
                                    {{ $division->division_name }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div class="col-md-2 mb-3">
                        <label class="form-label">Stock Status</label>
                        <select name="status" id="filter-status" class="form-control" data-placeholder="All Statuses">
                            <option value="">All Statuses</option>
                            @foreach($stockStatuses as $status)
                                <option value="{{ $status }}" {{ request('status') == $status ? 'selected' : '' }}>
                                    {{ ucfirst(str_replace('_', ' ', $status)) }}
                                </option>
                            @endforeach
                        </select>
                    </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>
                            Apply
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Export Buttons -->
    <div class="row warehouse-export-buttons mb-3">
        <div class="col-12 text-right">
            <button type="button" onclick="exportToExcel()" class="btn btn-success">
                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">download</i>
                Export Excel
            </button>
            <button type="button" onclick="exportToPdf()" class="btn btn-info">
                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">picture_as_pdf</i>
                Export PDF
            </button>
            <button type="button" onclick="printReport()" class="btn btn-secondary">
                <i class="material-icons" style="font-size: 18px; vertical-align: middle;">print</i>
                Print
            </button>
        </div>
    </div>

    <!-- Materials Report Table -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="material-icons align-middle mr-2">assessment</i>
                Materials Report ({{ $items->total() }} total materials)
            </h5>
        </div>
        <div class="card-body p-0">
            <div class="warehouse-table-container">
                <!-- Loading Overlay for Table -->
                <div class="warehouse-loading-overlay" id="tableLoadingOverlay">
                    <div class="d-flex align-items-center justify-content-center" style="height: 400px;">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                            <div class="mt-2">Loading data...</div>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <div class="warehouse-table-wrapper">
                    <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: 150px;">Material Code</th>
                                <th style="min-width: 200px;">Description</th>
                                <th style="min-width: 120px;">Category</th>
                                <th style="min-width: 80px;">Unit</th>
                                <th style="min-width: 100px;" class="text-right">Quantity</th>
                                <th style="min-width: 140px; white-space: nowrap;" class="text-right">Avg Unit Price</th>
                                <th style="min-width: 150px;" class="text-right">Price Range</th>
                                <th style="min-width: 120px;" class="text-right">Total Value</th>
                                <th style="min-width: 100px;" class="text-center">Production</th>
                                <th style="min-width: 100px;" class="text-center">Expiry</th>
                                <th style="min-width: 90px;" class="text-right">BMC</th>
                                <th style="min-width: 90px;" class="text-right">CRES</th>
                                <th style="min-width: 100px;" class="text-center">Status</th>
                                <th style="min-width: 80px;" class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="tableBody">
                            @forelse($items as $item)
                                <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 style="white-space: nowrap;">{{ $item->item_code }}</td>
                                    <td>{{ Str::limit($item->item_description, 50) }}</td>
                                    <td>
                                        <span class="badge badge-secondary">{{ $item->category }}</span>
                                    </td>
                                    <td>{{ $item->unit_of_measure }}</td>
                                    <td class="text-right">
                                        <strong>{{ number_format($item->total_quantity, 2) }}</strong>
                                    </td>
                                    <td class="text-right">
                                        AED {{ number_format($item->average_unit_price, 2) }}
                                    </td>
                                    <td class="text-right">
                                        @if($item->min_price > 0 && $item->max_price > 0)
                                            <small>
                                                Min: AED {{ number_format($item->min_price, 2) }}<br>
                                                Max: AED {{ number_format($item->max_price, 2) }}
                                            </small>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td class="text-right">
                                        <strong>AED {{ number_format($item->total_value, 2) }}</strong>
                                    </td>
                                    <td class="text-center">
                                        {{ $item->latest_production_date ? $item->latest_production_date->format('d M Y') : '-' }}
                                    </td>
                                    <td class="text-center">
                                        @if($item->latest_expiry_date)
                                            @php
                                                $daysUntilExpiry = now()->diffInDays($item->latest_expiry_date, false);
                                            @endphp
                                            <span class="{{ $daysUntilExpiry < 0 ? 'text-danger' : ($daysUntilExpiry <= 30 ? 'text-warning' : '') }}">
                                                {{ $item->latest_expiry_date->format('d M Y') }}
                                                @if($daysUntilExpiry < 0)
                                                    <br><small class="text-danger">Expired</small>
                                                @elseif($daysUntilExpiry <= 30)
                                                    <br><small class="text-warning">{{ $daysUntilExpiry }} days</small>
                                                @endif
                                            </span>
                                        @else
                                            -
                                        @endif
                                    </td>
                                    @php
                                        $divByName = collect($item->divisions)->keyBy(fn($d) => strtoupper($d['name']));
                                        $bmcQty  = $divByName->get('BMC DUBAI')['quantity']  ?? null;
                                        $cresQty = $divByName->get('CRES DUBAI')['quantity'] ?? null;
                                    @endphp
                                    <td class="text-right">
                                        @if($bmcQty !== null)
                                            <strong>{{ number_format($bmcQty, 2) }}</strong>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td class="text-right">
                                        @if($cresQty !== null)
                                            <strong>{{ number_format($cresQty, 2) }}</strong>
                                        @else
                                            <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td class="text-center">
                                        <span class="badge badge-{{
                                            $item->overall_status === 'in_stock' ? 'success' :
                                            ($item->overall_status === 'low_stock' ? 'warning' : 'danger')
                                        }}">
                                            {{ ucfirst(str_replace('_', ' ', $item->overall_status)) }}
                                        </span>
                                    </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">
                                                <i class="material-icons" style="font-size: 16px;">visibility</i>
                                            </a>
                                        @else
                                        <a href="{{ route('warehouse.reports.materials.item-details', $item->id) }}"
                                           class="btn btn-sm btn-outline-primary">
                                            <i class="material-icons" style="font-size: 16px;">visibility</i>
                                        </a>
                                        @endif
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="15" class="text-center py-4">
                                        <i class="material-icons text-muted" style="font-size: 48px;">inventory</i>
                                        <h5 class="text-muted mt-3">No Materials Found</h5>
                                        <p class="text-muted">No materials match your current filters.</p>
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        @if($items->hasPages())
            <div class="card-footer">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        Showing {{ $items->firstItem() }} to {{ $items->lastItem() }} of {{ $items->total() }} materials
                    </div>
                    <div>
                        <nav class="warehouse-pagination">
                            {{ $items->links('pagination::bootstrap-4') }}
                        </nav>
                    </div>
                </div>
            </div>
        @endif
    </div>
@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
            $('#filter-category, #filter-division, #filter-status').select2({
                theme: 'bootstrap-5',
                allowClear: true,
                placeholder: function() {
                    return $(this).data('placeholder') || 'Select...';
                }
            });
        });

        function exportToExcel() {
            // Get current filter values
            const formData = new FormData(document.getElementById('filterForm'));
            const params = new URLSearchParams(formData);
            params.set('export', 'excel');

            // Build export URL with current filters
            const exportUrl = '{{ route("warehouse.reports.materials") }}?' + params.toString();

            // Show notification
            showNotification('Generating Excel export...', 'info');

            // Create a temporary link and trigger download
            const link = document.createElement('a');
            link.href = exportUrl;
            link.download = 'materials-report.xlsx';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            // Show success feedback
            setTimeout(function() {
                showNotification('Excel export started! Download will begin shortly.', 'success');
            }, 500);
        }

        function exportToPdf() {
            // Get current filter values
            const formData = new FormData(document.getElementById('filterForm'));
            const params = new URLSearchParams(formData);
            params.set('export', 'pdf');

            // Build export URL with current filters
            const exportUrl = '{{ route("warehouse.reports.materials") }}?' + params.toString();

            // Show notification
            showNotification('Generating PDF report...', 'info');

            // Open in new tab for PDF (printable HTML)
            window.open(exportUrl, '_blank');
        }

        function printReport() {
            // Get current filter values
            const formData = new FormData(document.getElementById('filterForm'));
            const params = new URLSearchParams(formData);
            params.set('export', 'pdf');

            // Build export URL with current filters
            const exportUrl = '{{ route("warehouse.reports.materials") }}?' + params.toString();

            // Open PDF view and trigger print
            const printWindow = window.open(exportUrl, '_blank');
            printWindow.onload = function() {
                printWindow.print();
            };
        }

        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `alert alert-${type === 'success' ? 'success' : (type === 'error' ? 'danger' : 'info')} alert-dismissible fade show position-fixed`;
            notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            notification.innerHTML = `
                ${message}
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            `;

            // Add to page
            document.body.appendChild(notification);

            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 5000);
        }
    </script>
@endpush
