@extends('layouts.admin-simple')

@section('title', 'Material Issue Decision Center')

{{-- Force cache refresh --}}
<!-- Last updated: {{ now() }} -->

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item active">Material Issue</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">Material Issue Decision Center</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Process material requests and decide issue method</p>
        </div>
    </div>
@endsection

@section('content')
<div class="container-fluid">

    <!-- Flash Messages are handled by the layout -->

    <!-- 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="Pending Decisions"
                :value="$stats['pending_decisions']"
                icon="pending_actions"
                color="warning"
                subtitle="Awaiting issue decision"
            />
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Inventory Issues"
                :value="$stats['inventory_issues']"
                icon="inventory"
                color="success"
                subtitle="Dispatched from warehouse"
            />
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Direct Deliveries"
                :value="$stats['direct_deliveries']"
                icon="local_shipping"
                color="info"
                subtitle="Supplier deliveries"
            />
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <x-warehouse.stats-card
                title="Project Transfers"
                :value="$stats['project_transfers']"
                icon="swap_horiz"
                color="primary"
                subtitle="Inter-project transfers"
            />
        </div>
    </div>

    <!-- Filters Panel -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0">
                <i class="material-icons mr-2">filter_list</i>
                Filters
            </h6>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('warehouse.material-issue.index') }}" id="filterForm">
                <div class="row">
                    <div class="col-md-4">
                        <x-warehouse.select2-dropdown
                            name="project_id"
                            id="project_filter"
                            label="Project"
                            placeholder="All Projects"
                            :options="collect([['value' => '', 'text' => 'All Projects']])->merge($projects->map(function($project) {
                                return ['value' => $project->id, 'text' => $project->project_name];
                            }))"
                            :selected="request('project_id')"
                            allowClear="true"
                        />
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="date_from">From Date</label>
                            <input type="date" name="date_from" id="date_from" class="form-control"
                                   value="{{ request('date_from') }}">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="date_to">To Date</label>
                            <input type="date" name="date_to" id="date_to" class="form-control"
                                   value="{{ request('date_to') }}">
                        </div>
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <div class="form-group w-100">
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="material-icons mr-1" style="font-size: 16px;">search</i>
                                Filter
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Pending / Completed Toggle -->
    <div class="card">
        <div class="card-header warehouse-report-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0 warehouse-report-title">
                <i class="material-icons align-middle mr-2">assignment</i>
                Material Requests
            </h5>
            <div class="btn-group" role="group">
                <a href="{{ route('warehouse.material-issue.index', array_merge(request()->except('view_mode'), ['view_mode' => 'pending'])) }}"
                   class="btn btn-sm {{ (request('view_mode', 'pending') === 'pending') ? 'btn-warning' : 'btn-outline-warning' }}">
                    <i class="material-icons" style="font-size: 14px; vertical-align: middle;">pending</i>
                    Pending Issues
                </a>
                <a href="{{ route('warehouse.material-issue.index', array_merge(request()->except('view_mode'), ['view_mode' => 'completed'])) }}"
                   class="btn btn-sm {{ (request('view_mode') === 'completed') ? 'btn-success' : 'btn-outline-success' }}">
                    <i class="material-icons" style="font-size: 14px; vertical-align: middle;">check_circle</i>
                    Completed Issues
                </a>
            </div>
        </div>
        <div class="card-body p-0">
            @if($pendingRequests->count() > 0)
                <div class="warehouse-table-container">
                    <!-- Loading Overlay -->
                    <div class="warehouse-loading-overlay" id="tableLoadingOverlay" style="display: none;">
                        <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 material requests...</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: 140px;">Request #</th>
                                <th style="min-width: 130px;">Goods Type</th>
                                <th style="min-width: 120px;">Request Date</th>
                                <th style="min-width: 200px;">Project</th>
                                <th style="min-width: 150px;">Requested By</th>
                                <th style="min-width: 100px;">Items Count</th>
                                <th style="min-width: 100px;">Priority</th>
                                <th style="min-width: 130px;">Dispatch Status</th>
                                <th style="min-width: 180px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($pendingRequests as $request)
                                <tr>
                                    <td style="white-space: nowrap;">
                                        <strong class="text-primary">
                                            {{ $request->display_number }}
                                        </strong>
                                    </td>
                                    <td>
                                        @foreach(($request->goods_types ?? collect([(object) ['label' => $request->goods_type_label, 'class' => $request->goods_type_class]])) as $goodsType)
                                            <span class="badge badge-{{ $goodsType->class }} mb-1">
                                                {{ $goodsType->label }}
                                            </span>
                                        @endforeach
                                    </td>
                                    <td>{{ $request->display_date ? $request->display_date->format('d-M-Y') : '-' }}</td>
                                    <td>
                                        <div>
                                            <strong>{{ $request->project->project_name ?? 'N/A' }}</strong>
                                            @if($request->division)
                                                <br><small class="text-muted">{{ $request->division->division_name }}</small>
                                            @endif
                                        </div>
                                    </td>
                                    <td>{{ $request->requester->name ?? 'N/A' }}</td>
                                    <td>
                                        <span class="badge badge-light">{{ $request->items_count }} items</span>
                                    </td>
                                    <td>
                                        @php
                                            $daysSince = $request->display_date ? round($request->display_date->diffInDays(now())) : 0;
                                            if ($daysSince > 7) {
                                                $priority = 'High';
                                                $priorityClass = 'danger';
                                            } elseif ($daysSince > 3) {
                                                $priority = 'Medium';
                                                $priorityClass = 'warning';
                                            } else {
                                                $priority = 'Normal';
                                                $priorityClass = 'success';
                                            }
                                        @endphp
                                        <span class="badge badge-{{ $priorityClass }}">
                                            {{ $priority }}
                                        </span>
                                        <br><small class="text-muted">{{ $daysSince }} day{{ $daysSince != 1 ? 's' : '' }}</small>
                                    </td>
                                    <td>
                                        <span class="badge {{ $request->dispatch_class }}">
                                            <i class="material-icons" style="font-size: 12px;">{{ $request->dispatch_icon }}</i>
                                            {{ $request->dispatch_label }}
                                        </span>
                                    </td>
                                    <td style="white-space: nowrap;">
                                        <div class="d-flex align-items-center">
                                            @php
                                                $sources = $request->source_rows ?? collect([$request]);
                                                $directSource = $sources->firstWhere('source_type', 'direct');
                                                $viewSource = $directSource ?: $sources->first();
                                                $viewUrl = $viewSource
                                                    ? route(
                                                        'warehouse.inventory.material-issued.show',
                                                        array_filter([
                                                            'id' => $viewSource->id,
                                                            'source' => $viewSource->source_type === 'indirect' ? 'indirect' : null,
                                                        ])
                                                    )
                                                    : null;
                                                $printUrl = $viewSource
                                                    ? route(
                                                        'warehouse.inventory.material-issued.combined-print',
                                                        array_filter([
                                                            'id' => $viewSource->id,
                                                            'source' => $viewSource->source_type === 'indirect' ? 'indirect' : null,
                                                        ])
                                                    )
                                                    : null;
                                            @endphp

                                            @if($request->source_type === 'combined' && $directSource && $request->dispatch_status !== 'fully_dispatched')
                                                <a href="{{ $directSource->process_url }}"
                                                   class="btn btn-sm btn-success mr-1"
                                                   title="Issue Direct and Indirect Goods">
                                                    <i class="material-icons mr-1" style="font-size: 14px;">assignment</i>
                                                    Issue Request
                                                </a>
                                            @endif

                                            @foreach($sources as $source)
                                                @if($source->dispatch_status !== 'fully_dispatched' && $source->source_type === 'direct')
                                                    <!-- Process Button - only show if not fully dispatched -->
                                                    @if($request->source_type !== 'combined')
                                                        <a href="{{ $source->process_url }}"
                                                           class="btn btn-sm btn-success mr-1"
                                                           title="Process Direct Goods">
                                                            <i class="material-icons mr-1" style="font-size: 14px;">assignment</i>
                                                            Process Direct
                                                        </a>
                                                    @endif
                                                @endif
                                                @if($source->dispatch_status !== 'fully_dispatched' && $source->source_type === 'indirect')
                                                    @if($request->source_type !== 'combined')
                                                        <form method="POST"
                                                              action="{{ $source->issue_url }}"
                                                              class="mr-1"
                                                              onsubmit="return confirm('Issue indirect goods for {{ e($source->display_number) }}?');">
                                                            @csrf
                                                            <button type="submit" class="btn btn-sm btn-success" title="Issue Indirect Goods">
                                                                <i class="material-icons mr-1" style="font-size: 14px;">local_shipping</i>
                                                                Issue Indirect
                                                            </button>
                                                        </form>
                                                    @endif
                                                @endif
                                            @endforeach

                                            @if($viewUrl)
                                                <a href="{{ $viewUrl }}"
                                                   class="btn btn-sm btn-outline-primary mr-1"
                                                   title="View Material Issue Details">
                                                    <i class="material-icons" style="font-size: 14px;">visibility</i>
                                                    View
                                                </a>
                                            @endif
                                            @if($printUrl)
                                                <a href="{{ $printUrl }}"
                                                   target="_blank"
                                                   class="btn btn-sm btn-outline-info mr-1"
                                                   title="Print Material Issue">
                                                    <i class="material-icons" style="font-size: 14px;">print</i>
                                                </a>
                                            @endif
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                    </div>
                </div>

                <!-- Pagination -->
                @if($pendingRequests->hasPages())
                    <div class="mt-3">
                        {{ $pendingRequests->links('pagination::bootstrap-4') }}
                    </div>
                @endif
            @else
                <div class="text-center py-5">
                    <i class="material-icons text-muted mb-3" style="font-size: 64px;">assignment_turned_in</i>
                    @if(request('view_mode') === 'completed')
                        <h5 class="text-muted">No Completed Issues</h5>
                        <p class="text-muted">No completed material issues found</p>
                    @else
                        <h5 class="text-muted">No Pending Requests</h5>
                        <p class="text-muted">All material requests have been processed</p>
                    @endif
                </div>
            @endif
        </div>
    </div>


    <!-- Process Info Card -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card border-left-info">
                <div class="card-body">
                    <h6 class="text-info mb-2">
                        <i class="material-icons align-middle mr-1">info</i>
                        Material Issue Process
                    </h6>
                    <div class="row">
                        <div class="col-md-4">
                            <h6 class="font-weight-bold text-success">
                                <i class="material-icons align-middle mr-1">inventory</i>
                                Inventory Dispatch
                            </h6>
                            <ul class="text-sm mb-0">
                                <li>Issue materials from warehouse stock</li>
                                <li>Direct inventory deduction</li>
                                <li>Immediate project allocation</li>
                            </ul>
                        </div>
                        <div class="col-md-4">
                            <h6 class="font-weight-bold text-info">
                                <i class="material-icons align-middle mr-1">local_shipping</i>
                                Direct Delivery
                            </h6>
                            <ul class="text-sm mb-0">
                                <li>Order directly from supplier</li>
                                <li>Direct site delivery</li>
                                <li>Purchase order management</li>
                            </ul>
                        </div>
                        <div class="col-md-4">
                            <h6 class="font-weight-bold text-primary">
                                <i class="material-icons align-middle mr-1">swap_horiz</i>
                                Project Transfer
                            </h6>
                            <ul class="text-sm mb-0">
                                <li>Transfer from another project</li>
                                <li>Inter-project material sharing</li>
                                <li>Requires source project approval</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View Details Modal -->
<div class="modal fade" id="viewDetailsModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="material-icons align-middle mr-1">assignment</i>
                    Material Request Details
                </h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body" id="modalContent">
                <!-- Content will be loaded dynamically -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
    <link rel="stylesheet" href="{{ asset('admin-assets/css/warehouse-reports.css') }}">
@endpush

@push('scripts')
    <script src="{{ asset('admin-assets/js/warehouse-reports.js') }}"></script>
<script>
function printMaterialRequest(id) {
    console.log('printMaterialRequest called with id:', id);

    // Open print view in new window - using Laravel route helper
    const printUrl = '{{ route("warehouse.inventory.material-issued.print", ":id") }}'.replace(':id', id);
    console.log('Opening print URL:', printUrl);
    const printWindow = window.open(printUrl, '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');

    if (printWindow) {
        printWindow.focus();

        // Wait for content to load then print
        printWindow.addEventListener('load', function() {
            setTimeout(() => {
                printWindow.print();
            }, 1000);
        });
    } else {
        // Fallback: navigate to print page if popup blocked
        window.open(printUrl, '_blank');
    }
}

function viewRequestDetails(id) {
    $('#viewDetailsModal').modal('show');
    $('#modalContent').html('<div class="text-center py-3"><i class="material-icons fa-spin">refresh</i> Loading...</div>');

    // Fetch request details (you'll need to implement this route)
    fetch(`/warehouse/outgoing/${id}`)
        .then(response => response.json())
        .then(data => {
            let itemsHtml = data.items.map(item => `
                <tr>
                    <td>${item.item.item_code}</td>
                    <td>${item.item.item_description}</td>
                    <td>${item.quantity_requested} ${item.item.unit_of_measure}</td>
                </tr>
            `).join('');

            $('#modalContent').html(`
                <div class="row">
                    <div class="col-md-6">
                        <strong>Request Number:</strong><br>
                        <span class="text-primary">${data.material_request_number || 'MR-' + data.id.toString().padStart(6, '0')}</span>
                    </div>
                    <div class="col-md-6">
                        <strong>Date:</strong><br>
                        ${new Date(data.transaction_date).toLocaleDateString()}
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-md-6">
                        <strong>Project:</strong><br>
                        ${data.project ? data.project.project_name : 'N/A'}
                    </div>
                    <div class="col-md-6">
                        <strong>Requested By:</strong><br>
                        ${data.requester ? data.requester.name : 'N/A'}
                    </div>
                </div>
                <div class="mt-3">
                    <strong>Requested Items:</strong>
                    <table class="table table-sm mt-2">
                        <thead>
                            <tr>
                                <th>Code</th>
                                <th>Description</th>
                                <th>Quantity</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${itemsHtml}
                        </tbody>
                    </table>
                </div>
            `);
        })
        .catch(error => {
            $('#modalContent').html('<div class="alert alert-danger">Error loading request details</div>');
        });
}
</script>
@endpush
