@extends('layouts.admin-simple')

@section('title', 'Direct Deliveries')

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

@section('breadcrumb')
    <li class="breadcrumb-item">Warehouse</li>
    <li class="breadcrumb-item active">Direct Deliveries</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">Direct Deliveries</h3>
            <p class="text-muted mb-0" style="font-size: 13px;">Manage supplier deliveries and purchase orders</p>
        </div>
        @can('warehouse.outgoing.create')
        <a href="{{ route('warehouse.direct-deliveries.create') }}" class="btn btn-primary">
            <i class="material-icons mr-1" style="font-size: 18px;">add</i>
            New Direct Delivery
        </a>
        @endcan
    </div>
@endsection

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

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

    <!-- 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.direct-deliveries.index') }}" id="filterForm">
                <div class="row">
                    <div class="col-md-3">
                        <x-warehouse.select2-dropdown
                            name="status"
                            id="status_filter"
                            label="Status"
                            placeholder="All Status"
                            :options="[
                                ['value' => '', 'text' => 'All Status'],
                                ['value' => 'pending', 'text' => 'Pending'],
                                ['value' => 'partially_received', 'text' => 'Partially Received'],
                                ['value' => 'received', 'text' => 'Received'],
                                ['value' => 'cancelled', 'text' => 'Cancelled']
                            ]"
                            :selected="request('status')"
                            allowClear="true"
                        />
                    </div>
                    <div class="col-md-3">
                        <x-warehouse.select2-dropdown
                            name="supplier_id"
                            id="supplier_filter"
                            label="Supplier"
                            placeholder="All Suppliers"
                            :options="collect([['value' => '', 'text' => 'All Suppliers']])->merge($suppliers->map(function($supplier) {
                                return ['value' => $supplier->id, 'text' => $supplier->name];
                            }))"
                            :selected="request('supplier_id')"
                            allowClear="true"
                        />
                    </div>
                    <div class="col-md-3">
                        <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">
                        <x-warehouse.select2-dropdown
                            name="delivery_type"
                            id="delivery_type_filter"
                            label="Type"
                            placeholder="All Types"
                            :options="[
                                ['value' => '', 'text' => 'All Types'],
                                ['value' => 'purchase_order', 'text' => 'Purchase Order'],
                                ['value' => 'direct_purchase', 'text' => 'Direct Purchase'],
                                ['value' => 'emergency', 'text' => 'Emergency']
                            ]"
                            :selected="request('delivery_type')"
                            allowClear="true"
                        />
                    </div>
                </div>
                <div class="row">
                    <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-6 d-flex align-items-end">
                        <div class="form-group w-100">
                            <button type="submit" class="btn btn-primary mr-2">
                                <i class="material-icons mr-1" style="font-size: 16px;">search</i>
                                Filter
                            </button>
                            <a href="{{ route('warehouse.direct-deliveries.index') }}" class="btn btn-outline-secondary">
                                <i class="material-icons mr-1" style="font-size: 16px;">clear</i>
                                Clear
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Direct Deliveries 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">local_shipping</i>
                Direct Deliveries
            </h5>
        </div>
        <div class="card-body p-0">
            @if($directDeliveries->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 deliveries...</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;">Delivery #</th>
                                <th style="min-width: 120px;">Date</th>
                                <th style="min-width: 180px;">Supplier</th>
                                <th style="min-width: 150px;">Project</th>
                                <th style="min-width: 120px;">Type</th>
                                <th style="min-width: 100px;">Status</th>
                                <th style="min-width: 80px;">Items</th>
                                <th style="min-width: 120px;">Total Value</th>
                                <th style="min-width: 140px;">Delivered By</th>
                                <th style="min-width: 220px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($directDeliveries as $delivery)
                                <tr>
                                    <td style="white-space: nowrap;">
                                        <strong class="text-primary">{{ $delivery->delivery_number }}</strong>
                                        @if($delivery->purchase_order_number)
                                        <br><small class="text-muted">PO: {{ $delivery->purchase_order_number }}</small>
                                        @endif
                                    </td>
                                    <td>{{ $delivery->delivery_date->format('d-M-Y') }}</td>
                                    <td>
                                        @if($delivery->supplier)
                                            <span class="text-primary">
                                                {{ $delivery->supplier->name }}
                                            </span>
                                            @if($delivery->supplier_delivery_note)
                                            <br><small class="text-muted">Note: {{ $delivery->supplier_delivery_note }}</small>
                                            @endif
                                        @else
                                            <span class="text-muted">
                                                <i class="material-icons small" style="font-size: 14px;">edit</i>
                                                Pending Supplier Selection
                                            </span>
                                            <br><small class="text-warning">Material Request - Needs supplier details</small>
                                        @endif
                                    </td>
                                    <td>
                                        <span class="text-success">
                                            {{ $delivery->project->project_name }}
                                        </span>
                                        @if($delivery->projectDivision)
                                        <br><small class="text-muted">{{ $delivery->projectDivision->division_name }}</small>
                                        @endif
                                    </td>
                                    <td>
                                        <span class="badge badge-{{ $delivery->delivery_type_color }}">
                                            {{ $delivery->delivery_type_display }}
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge badge-{{ $delivery->status_color }}">
                                            {{ ucfirst(str_replace('_', ' ', $delivery->status)) }}
                                        </span>
                                        @if($delivery->needsApproval())
                                        <br><small class="text-warning">Needs Approval</small>
                                        @endif
                                    </td>
                                    <td>
                                        <span class="badge badge-light">{{ $delivery->items->count() }} items</span>
                                    </td>
                                    <td>
                                        @if($delivery->total_amount)
                                        {{ $delivery->currency }} {{ number_format($delivery->total_amount, 2) }}
                                        @else
                                        <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td>
                                        @if($delivery->delivered_by)
                                        {{ $delivery->delivered_by }}
                                        @if($delivery->vehicle_number)
                                        <br><small class="text-muted">{{ $delivery->vehicle_number }}</small>
                                        @endif
                                        @else
                                        <span class="text-muted">-</span>
                                        @endif
                                    </td>
                                    <td style="white-space: nowrap;">
                                        <div class="d-flex align-items-center">
                                            <!-- View Button -->
                                            <a href="{{ route('warehouse.direct-deliveries.show', $delivery) }}"
                                               class="btn btn-sm btn-info mr-1"
                                               title="View Details">
                                                <i class="material-icons mr-1" style="font-size: 14px;">visibility</i>
                                                View
                                            </a>

                                            @if($delivery->canEdit())
                                            <!-- Edit Button -->
                                            <a href="{{ route('warehouse.direct-deliveries.edit', $delivery) }}"
                                               class="btn btn-sm btn-warning mr-1"
                                               title="Edit">
                                                <i class="material-icons mr-1" style="font-size: 14px;">edit</i>
                                                Edit
                                            </a>
                                            @endif

                                            @if($delivery->canReceive())
                                            <!-- Process Receipt Button -->
                                            <a href="{{ route('warehouse.direct-deliveries.receipt', $delivery) }}"
                                               class="btn btn-sm btn-success mr-1"
                                               title="Process Receipt">
                                                <i class="material-icons mr-1" style="font-size: 14px;">receipt</i>
                                                Receipt
                                            </a>
                                            @endif

                                            @if($delivery->needsApproval())
                                            <!-- Approve Button -->
                                            <button type="button" class="btn btn-sm btn-primary mr-1"
                                                    onclick="approveDelivery({{ $delivery->id }})" title="Approve">
                                                <i class="material-icons mr-1" style="font-size: 14px;">approval</i>
                                                Approve
                                            </button>
                                            @endif

                                            <!-- Print Button -->
                                            <button type="button" class="btn btn-sm btn-outline-info"
                                                    onclick="printDirectDelivery({{ $delivery->id }})" title="Print Delivery Note">
                                                <i class="material-icons" style="font-size: 14px;">print</i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                    </div>
                </div>

                <!-- Pagination -->
                @if($directDeliveries->hasPages())
                    <div class="mt-3">
                        {{ $directDeliveries->appends(request()->query())->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;">local_shipping</i>
                    <h5 class="text-muted">No Direct Deliveries Found</h5>
                    <p class="text-muted">No deliveries match your current filters</p>
                    @can('warehouse.outgoing.create')
                    <a href="{{ route('warehouse.direct-deliveries.create') }}" class="btn btn-primary">
                        <i class="material-icons mr-1" style="font-size: 18px;">add</i>
                        Create First Direct Delivery
                    </a>
                    @endcan
                </div>
            @endif
        </div>
    </div>
</div>

<!-- Approval Modal -->
<div class="modal fade" id="approvalModal" tabindex="-1" role="dialog" aria-labelledby="approvalModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="approvalModalLabel">Approve Direct Delivery</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="approvalForm" method="POST">
                @csrf
                <div class="modal-body">
                    <div class="form-group">
                        <label for="approval_notes">Approval Notes</label>
                        <textarea name="approval_notes" id="approval_notes" class="form-control" rows="3" placeholder="Optional notes for this approval..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Approve Delivery</button>
                </div>
            </form>
        </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 applyFilters() {
    const params = new URLSearchParams();

    // Get filter values
    const status = $('#status_filter').val();
    const supplier = $('#supplier_filter').val();
    const project = $('#project_filter').val();
    const deliveryType = $('#delivery_type_filter').val();
    const dateFrom = document.getElementById('date_from').value;
    const dateTo = document.getElementById('date_to').value;

    // Add non-empty parameters
    if (status) params.append('status', status);
    if (supplier) params.append('supplier_id', supplier);
    if (project) params.append('project_id', project);
    if (deliveryType) params.append('delivery_type', deliveryType);
    if (dateFrom) params.append('date_from', dateFrom);
    if (dateTo) params.append('date_to', dateTo);

    // Redirect with filters
    window.location.href = '{{ route("warehouse.direct-deliveries.index") }}?' + params.toString();
}

function approveDelivery(deliveryId) {
    document.getElementById('approvalForm').action = `/warehouse/direct-deliveries/${deliveryId}/approve`;
    $('#approvalModal').modal('show');
}

// Print function for direct deliveries
function printDirectDelivery(id) {
    console.log('printDirectDelivery called with id:', id);

    // Open print view in new window - using Laravel route helper
    const printUrl = '{{ route("warehouse.direct-deliveries.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');
    }
}
</script>
@endpush