@extends('layouts.admin-simple')

@section('title', 'Direct Delivery Details')

@push('styles')
<style>
.select2-container {
    width: 100% !important;
}

.select2-dropdown {
    min-width: 200px;
    max-width: 400px;
    width: auto !important;
}

.select2-container .select2-selection--single {
    min-width: 200px;
    max-width: 100%;
}

.select2-container--open .select2-dropdown--below {
    width: auto !important;
    min-width: 200px;
}

.info-section {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
}

.info-label {
    font-weight: 600;
    color: #6c757d;
    margin-bottom: 5px;
}

.info-value {
    color: #495057;
    margin-bottom: 15px;
}

.status-pending { background-color: #ffc107; }
.status-partially-received { background-color: #17a2b8; }
.status-received { background-color: #28a745; }
.status-cancelled { background-color: #dc3545; }

.delivery-type-purchase-order { background-color: #007bff; }
.delivery-type-direct-purchase { background-color: #6f42c1; }
.delivery-type-emergency { background-color: #dc3545; }
</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="card-title mb-0">
                        <i class="material-icons mr-2">local_shipping</i>
                        Direct Delivery Details
                    </h4>
                    <div>
                        @if($directDelivery->needsApproval())
                        <button type="button" class="btn btn-outline-info mr-2"
                                onclick="approveDelivery({{ $directDelivery->id }})">
                            <i class="material-icons mr-1">approval</i>
                            Approve
                        </button>
                        @endif
                        @if($directDelivery->canBeReturned())
                        <a href="{{ route('warehouse.direct-deliveries.site-return', $directDelivery) }}"
                           class="btn btn-outline-danger mr-2">
                            <i class="material-icons mr-1">keyboard_return</i>
                            Create Site Return
                        </a>
                        @endif
                        <a href="{{ route('warehouse.direct-deliveries.index') }}" class="btn btn-secondary">
                            <i class="material-icons mr-1">arrow_back</i>
                            Back to List
                        </a>
                    </div>
                </div>

                <div class="card-body">
                    <!-- Flash Messages -->
                    @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="material-icons mr-2">check_circle</i>
                        {{ session('success') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    @endif

                    @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="material-icons mr-2">error</i>
                        {{ session('error') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    @endif

                    @if(session('warning'))
                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                        <i class="material-icons mr-2">warning</i>
                        {{ session('warning') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    @endif

                    <!-- Basic Information -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="info-section">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="material-icons mr-2">info</i>
                                    Delivery Information
                                </h5>

                                <div class="info-label">Delivery Number</div>
                                <div class="info-value"><strong>{{ $directDelivery->delivery_number }}</strong></div>

                                <div class="info-label">Reference Number</div>
                                <div class="info-value">
                                    <strong>{{ $directDelivery->reference_number }}</strong>
                                    <small class="text-muted d-block">For site returns</small>
                                </div>

                                <div class="info-label">Status</div>
                                <div class="info-value">
                                    <span class="badge badge-{{ $directDelivery->status_color }}">
                                        {{ ucfirst(str_replace('_', ' ', $directDelivery->status)) }}
                                    </span>
                                    @if($directDelivery->needsApproval())
                                    <span class="badge badge-warning ml-2">Needs Approval</span>
                                    @endif
                                </div>

                                <div class="info-label">Delivery Date</div>
                                <div class="info-value">{{ $directDelivery->delivery_date->format('M d, Y') }}</div>

                                @if($directDelivery->order_date)
                                <div class="info-label">Order Date</div>
                                <div class="info-value">{{ $directDelivery->order_date->format('M d, Y') }}</div>
                                @endif

                                <div class="info-label">Delivery Type</div>
                                <div class="info-value">
                                    <span class="badge badge-{{ $directDelivery->delivery_type_color }}">
                                        {{ $directDelivery->delivery_type_display }}
                                    </span>
                                </div>

                                @if($directDelivery->purchase_order_number)
                                <div class="info-label">Purchase Order Number</div>
                                <div class="info-value">{{ $directDelivery->purchase_order_number }}</div>
                                @endif

                                <div class="info-label">Return Policy</div>
                                <div class="info-value">
                                    @if($directDelivery->can_be_returned)
                                    <span class="badge badge-success">Items Can Be Returned</span>
                                    @else
                                    <span class="badge badge-secondary">Items Cannot Be Returned</span>
                                    @endif
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="info-section">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="material-icons mr-2">business</i>
                                    Supplier & Project Details
                                </h5>

                                <div class="info-label">Supplier</div>
                                <div class="info-value">
                                    @if($directDelivery->supplier)
                                        <strong>{{ $directDelivery->supplier->name }}</strong>
                                        @if($directDelivery->supplier->contact_person)
                                        <br><small class="text-muted">Contact: {{ $directDelivery->supplier->contact_person }}</small>
                                        @endif
                                        @if($directDelivery->supplier->phone)
                                        <br><small class="text-muted">Phone: {{ $directDelivery->supplier->phone }}</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
                                </div>

                                <div class="info-label">Destination Project</div>
                                <div class="info-value">
                                    <strong>{{ $directDelivery->project->project_name }}</strong>
                                </div>

                                @if($directDelivery->projectDivision)
                                <div class="info-label">Division</div>
                                <div class="info-value">
                                    <strong>{{ $directDelivery->projectDivision->division_name }}</strong>
                                    @if($directDelivery->projectDivision->division_code)
                                    <small class="text-muted">({{ $directDelivery->projectDivision->division_code }})</small>
                                    @endif
                                </div>
                                @endif

                                @if($directDelivery->supplier_delivery_note)
                                <div class="info-label">Supplier Delivery Note</div>
                                <div class="info-value">{{ $directDelivery->supplier_delivery_note }}</div>
                                @endif

                                @if($directDelivery->delivered_by)
                                <div class="info-label">Delivered By</div>
                                <div class="info-value">
                                    {{ $directDelivery->delivered_by }}
                                    @if($directDelivery->vehicle_number)
                                    <br><small class="text-muted">Vehicle: {{ $directDelivery->vehicle_number }}</small>
                                    @endif
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>

                    <!-- Approval Information -->
                    @if($directDelivery->approved_at || $directDelivery->received_at)
                    <div class="row">
                        <div class="col-12">
                            <div class="info-section">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="material-icons mr-2">check_circle</i>
                                    Process Information
                                </h5>

                                <div class="row">
                                    @if($directDelivery->approved_at)
                                    <div class="col-md-6">
                                        <div class="info-label">Approved By</div>
                                        <div class="info-value">
                                            {{ $directDelivery->approvedBy->name ?? 'Unknown User' }}
                                            <br><small class="text-muted">{{ $directDelivery->approved_at->format('M d, Y H:i') }}</small>
                                            @if($directDelivery->approval_notes)
                                            <br><small class="text-muted">Notes: {{ $directDelivery->approval_notes }}</small>
                                            @endif
                                        </div>
                                    </div>
                                    @endif

                                    @if($directDelivery->received_at)
                                    <div class="col-md-6">
                                        <div class="info-label">Received By</div>
                                        <div class="info-value">
                                            {{ $directDelivery->receivedBy->name ?? 'Unknown User' }}
                                            <br><small class="text-muted">{{ $directDelivery->received_at->format('M d, Y H:i') }}</small>
                                            @if($directDelivery->receipt_notes)
                                            <br><small class="text-muted">Notes: {{ $directDelivery->receipt_notes }}</small>
                                            @endif
                                        </div>
                                    </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    @endif

                    <!-- Delivery Notes -->
                    @if($directDelivery->delivery_notes)
                    <div class="row">
                        <div class="col-12">
                            <div class="info-section">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="material-icons mr-2">note</i>
                                    Delivery Notes
                                </h5>
                                <p class="mb-0">{{ $directDelivery->delivery_notes }}</p>
                            </div>
                        </div>
                    </div>
                    @endif

                    <!-- Items Section -->
                    <div class="row">
                        <div class="col-12">
                            <div class="info-section">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="material-icons mr-2">list</i>
                                    Delivery Items ({{ $directDelivery->items->count() }})
                                </h5>

                                <div class="table-responsive">
                                    <table class="table table-bordered table-striped">
                                        <thead class="thead-light">
                                            <tr>
                                                <th>Item</th>
                                                <th>Ordered</th>
                                                <th>Delivered</th>
                                                @if($directDelivery->status == 'partially_delivered')
                                                <th>Remaining</th>
                                                <th>Progress</th>
                                                @endif
                                                @if($directDelivery->status !== 'pending')
                                                <th>Received</th>
                                                <th>Rejected</th>
                                                <th>Returned</th>
                                                @endif
                                                <th>Unit</th>
                                                <th>Unit Price ({{ config('app.currency', 'AED') }})</th>
                                                <th>Total Price</th>
                                                @if($directDelivery->status !== 'pending')
                                                <th>Quality</th>
                                                @endif
                                                <th>Details</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @php $grandTotal = 0; @endphp
                                            @foreach($directDelivery->items as $item)
                                            @php
                                                $itemTotal = $item->received_quantity > 0
                                                    ? $item->received_quantity * $item->unit_price
                                                    : $item->delivered_quantity * $item->unit_price;
                                                $grandTotal += $itemTotal;
                                            @endphp
                                            <tr>
                                                <td>
                                                    <strong>{{ $item->item->item_description }}</strong>
                                                    @if($item->item->item_code)
                                                    <br><small class="text-muted">{{ $item->item->item_code }}</small>
                                                    @endif
                                                    @if($item->batch_number)
                                                    <br><small class="text-info">Batch: {{ $item->batch_number }}</small>
                                                    @endif
                                                </td>
                                                <td>{{ number_format($item->ordered_quantity, 2) }}</td>
                                                <td>
                                                    <span class="font-weight-bold {{ $item->isPartiallyDelivered() ? 'text-warning' : ($item->isFullyDelivered() ? 'text-success' : 'text-muted') }}">
                                                        {{ number_format($item->delivered_quantity, 2) }}
                                                    </span>
                                                    @if($item->isPartiallyDelivered())
                                                    <br><small class="text-muted">{{ $item->getDeliveryStatusDescription() }}</small>
                                                    @endif
                                                </td>
                                                @if($directDelivery->status == 'partially_delivered')
                                                <td>
                                                    <span class="font-weight-bold text-primary">
                                                        {{ number_format($item->getRemainingDeliverableQuantity(), 2) }}
                                                    </span>
                                                    <br><small class="text-muted">pending</small>
                                                </td>
                                                <td>
                                                    <div class="progress" style="height: 20px;">
                                                        <div class="progress-bar bg-{{ $item->getDeliveryCompletionPercentage() < 50 ? 'warning' : 'info' }}"
                                                             role="progressbar"
                                                             style="width: {{ $item->getDeliveryCompletionPercentage() }}%"
                                                             aria-valuenow="{{ $item->getDeliveryCompletionPercentage() }}"
                                                             aria-valuemin="0"
                                                             aria-valuemax="100">
                                                            {{ $item->getDeliveryCompletionPercentage() }}%
                                                        </div>
                                                    </div>
                                                    <small class="text-muted">{{ $item->getDeliveryCompletionPercentage() }}% Complete</small>
                                                </td>
                                                @endif
                                                @if($directDelivery->status !== 'pending')
                                                <td>{{ number_format($item->received_quantity ?? 0, 2) }}</td>
                                                <td>{{ number_format($item->rejected_quantity ?? 0, 2) }}</td>
                                                <td>
                                                    {{ number_format($item->returned_quantity ?? 0, 2) }}
                                                    @if($item->canBeReturned())
                                                    <br><small class="text-success">{{ $item->return_status }}</small>
                                                    @elseif($item->returned_quantity > 0)
                                                    <br><small class="text-muted">{{ $item->return_status }}</small>
                                                    @endif
                                                </td>
                                                @endif
                                                <td>{{ $item->unit_of_measure ?: '-' }}</td>
                                                <td>{{ number_format($item->unit_price, 2) }}</td>
                                                <td>{{ number_format($itemTotal, 2) }}</td>
                                                @if($directDelivery->status !== 'pending')
                                                <td>
                                                    @if($item->quality_status)
                                                    <span class="badge badge-{{ $item->quality_status === 'passed' ? 'success' : ($item->quality_status === 'failed' ? 'danger' : 'warning') }}">
                                                        {{ ucfirst($item->quality_status) }}
                                                    </span>
                                                    @else
                                                    <span class="text-muted">-</span>
                                                    @endif
                                                </td>
                                                @endif
                                                <td>
                                                    @if($item->expiry_date)
                                                    <small class="text-muted">Exp: {{ $item->expiry_date->format('M d, Y') }}</small><br>
                                                    @endif
                                                    @if($item->manufacturer)
                                                    <small class="text-muted">Mfg: {{ $item->manufacturer }}</small><br>
                                                    @endif
                                                    @if($item->storage_location)
                                                    <small class="text-success">Location: {{ $item->storage_location }}</small>
                                                    @endif
                                                </td>
                                            </tr>
                                            @endforeach
                                        </tbody>
                                        <tfoot class="thead-light">
                                            <tr>
                                                <th colspan="{{ $directDelivery->status === 'pending' ? 7 : ($directDelivery->status === 'partially_delivered' ? 12 : 10) }}" class="text-right">Grand Total:</th>
                                                <th>{{ config('app.currency', 'AED') }} {{ number_format($grandTotal, 2) }}</th>
                                                <th></th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>

                                @if($directDelivery->status == 'partially_delivered')
                                <!-- Delivery Progress Summary -->
                                <div class="alert alert-info mt-3">
                                    <h6 class="alert-heading">
                                        <i class="material-icons mr-2">info</i>
                                        Delivery Progress Summary
                                    </h6>
                                    @php
                                        $totalOrdered = $directDelivery->items->sum('ordered_quantity');
                                        $totalDelivered = $directDelivery->items->sum('delivered_quantity');
                                        $totalRemaining = $totalOrdered - $totalDelivered;
                                        $overallProgress = $totalOrdered > 0 ? round(($totalDelivered / $totalOrdered) * 100, 2) : 0;
                                    @endphp
                                    <div class="row">
                                        <div class="col-md-3">
                                            <strong>Total Ordered:</strong><br>
                                            <span class="h6">{{ number_format($totalOrdered, 2) }}</span>
                                        </div>
                                        <div class="col-md-3">
                                            <strong>Total Delivered:</strong><br>
                                            <span class="h6 text-success">{{ number_format($totalDelivered, 2) }}</span>
                                        </div>
                                        <div class="col-md-3">
                                            <strong>Remaining to Deliver:</strong><br>
                                            <span class="h6 text-primary">{{ number_format($totalRemaining, 2) }}</span>
                                        </div>
                                        <div class="col-md-3">
                                            <strong>Overall Progress:</strong><br>
                                            <div class="progress mt-1" style="height: 25px;">
                                                <div class="progress-bar bg-{{ $overallProgress < 50 ? 'warning' : 'info' }}"
                                                     role="progressbar"
                                                     style="width: {{ $overallProgress }}%">
                                                    {{ $overallProgress }}%
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </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('scripts')
<script>
function approveDelivery(deliveryId) {
    document.getElementById('approvalForm').action = `/warehouse/direct-deliveries/${deliveryId}/approve`;
    $('#approvalModal').modal('show');
}
</script>
@endpush