@extends('layouts.admin.app')

@php
    $mode = $mode ?? 'orders';
@endphp
@section('title', $mode === 'outstanding' ? translate('Courier Outstanding') : translate('Courier Orders'))

@section('content')
    <div class="content container-fluid">
        <div class="page-header">
            <h1 class="page-header-title">
                <span class="page-header-icon"><i class="tio-local-shipping"></i></span>
                <span>{{ $mode === 'outstanding' ? translate('Courier Outstanding Report') : translate('Order-wise Courier Money Status') }}</span>
            </h1>
            <div class="page-header-right">
                @php
                    $exportUrl = route('admin.courier.export', ['report' => $mode === 'outstanding' ? 'outstanding' : 'orders', 'type' => 'csv']) . (request()->getQueryString() ? '?' . request()->getQueryString() : '');
                @endphp
                <a class="btn btn-outline-primary" href="{{ $exportUrl }}">
                    <i class="tio-download-to"></i> {{ translate('Export CSV') }}
                </a>
            </div>
        </div>

        @include('admin-views.courier.partials._nav')
        @if(!empty($queryError))
            <div class="alert alert-soft-warning">
                <strong>{{ translate('Report warning') }}:</strong>
                {{ translate('Courier report query could not load live rows. Please check server log for details.') }}
                <div class="fs-12 text-muted text-break">{{ $queryError }}</div>
            </div>
        @endif
        @include('admin-views.courier.partials._summary', ['summary' => $summary])

        <div class="card mb-3">
            <div class="card-body">
                <form method="get">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <select name="courier_id" class="form-control">
                                <option value="">{{ translate('All Couriers') }}</option>
                                @foreach($couriers as $courier)
                                    <option value="{{ $courier->id }}" {{ (string) request('courier_id') === (string) $courier->id ? 'selected' : '' }}>{{ $courier->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2"><input type="text" name="parcel_id" value="{{ request('parcel_id') }}" class="form-control" placeholder="{{ translate('Parcel ID') }}"></div>
                        <div class="col-md-2"><input type="text" name="invoice_no" value="{{ request('invoice_no') }}" class="form-control" placeholder="{{ translate('Invoice No') }}"></div>
                        <div class="col-md-2"><input type="text" name="mobile" value="{{ request('mobile') }}" class="form-control" placeholder="{{ translate('Customer Mobile') }}"></div>
                        <div class="col-md-3">
                            <div class="input-group">
                                <input type="date" name="from" value="{{ request('from') }}" class="form-control">
                                <input type="date" name="to" value="{{ request('to') }}" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <select name="collection_status" class="form-control">
                                <option value="all">{{ translate('Collection Status') }}</option>
                                @foreach(['collected', 'pending', 'cod_collected'] as $status)
                                    <option value="{{ $status }}" {{ request('collection_status') === $status ? 'selected' : '' }}>{{ translate(str_replace('_', ' ', $status)) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2">
                            <select name="settlement_status" class="form-control">
                                <option value="all">{{ translate('Settlement Status') }}</option>
                                @foreach(['unsettled', 'partially_settled', 'settled', 'disputed', 'hold'] as $status)
                                    <option value="{{ $status }}" {{ request('settlement_status') === $status ? 'selected' : '' }}>{{ translate(str_replace('_', ' ', $status)) }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-2"><input type="text" name="courier_status" value="{{ request('courier_status') }}" class="form-control" placeholder="{{ translate('Courier Status') }}"></div>
                        <div class="col-md-2"><input type="text" name="payment_status" value="{{ request('payment_status') }}" class="form-control" placeholder="{{ translate('Payment Status') }}"></div>
                        <div class="col-md-2"><button class="btn btn--primary btn-block"><i class="tio-search"></i> {{ translate('Filter') }}</button></div>
                        <div class="col-md-2"><a class="btn btn--reset btn-block" href="{{ $mode === 'outstanding' ? route('admin.courier.outstanding') : route('admin.courier.orders') }}">{{ translate('Reset') }}</a></div>
                    </div>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header border-0">
                <h4 class="card-title">{{ translate('Courier Parcels') }} <span class="badge badge-soft-secondary">{{ $shipments->total() }}</span></h4>
            </div>
            <div class="table-responsive">
                <table class="table table-borderless table-thead-bordered table-nowrap card-table">
                    <thead class="thead-light">
                    <tr>
                        <th>{{ translate('Order') }}</th>
                        <th>{{ translate('Customer') }}</th>
                        <th>{{ translate('Courier / Parcel') }}</th>
                        <th>{{ translate('Status') }}</th>
                        <th class="text-right">{{ translate('COD') }}</th>
                        <th class="text-right">{{ translate('Charges') }}</th>
                        <th class="text-right">{{ translate('Net Receivable') }}</th>
                        <th class="text-right">{{ translate('Received') }}</th>
                        <th class="text-right">{{ translate('Balance') }}</th>
                        <th>{{ translate('Dates') }}</th>
                    </tr>
                    </thead>
                    <tbody>
                    @forelse($shipments as $shipment)
                        @php
                            $order = $shipment->order;
                            $charges = (float) $shipment->actual_delivery_cost + (float) $shipment->actual_cod_charge + (float) $shipment->actual_return_cost;
                            $netReceivable = $shipment->net_receivable_amount ?? max((float) $shipment->collectable_amount - $charges, 0);
                            $balance = $shipment->balance_amount ?? ($netReceivable - (float) $shipment->settled_amount);
                            $courierName = $shipment->courier?->name ?: (filled($shipment->provider) ? ucfirst((string) $shipment->provider) : translate('N/A'));
                        @endphp
                        <tr>
                            <td>
                                @if($order)
                                    <a href="{{ route('admin.order.details', ['id' => $order->id, 'module_id' => $order->module_id]) }}">#{{ $order->id }}</a>
                                    <div class="fs-12 text-muted">{{ translate($order->payment_status) }} / {{ translate($order->order_status) }}</div>
                                @else
                                    {{ translate('N/A') }}
                                @endif
                            </td>
                            <td>
                                <div>{{ trim(($order?->customer?->f_name ?? '') . ' ' . ($order?->customer?->l_name ?? '')) ?: translate('Guest') }}</div>
                                <div class="fs-12 text-muted">{{ $order?->customer?->phone ?? translate('N/A') }}</div>
                            </td>
                            <td>
                                <strong>{{ $courierName }}</strong>
                                <div class="fs-12 text-muted text-break">{{ $shipment->courier_consignment_id ?: $shipment->courier_parcel_id ?: $shipment->courier_tracking_id }}</div>
                            </td>
                            <td>
                                <span class="badge badge-soft-info">{{ $shipment->courier_status ?: translate('N/A') }}</span>
                                <div class="fs-12 mt-1">{{ translate('Collection') }}: {{ translate(str_replace('_', ' ', $shipment->cod_collection_status ?: 'pending')) }}</div>
                                <div class="fs-12">{{ translate('Settlement') }}: {{ translate(str_replace('_', ' ', $shipment->settlement_status ?: 'unsettled')) }}</div>
                            </td>
                            <td class="text-right">{{ \App\CentralLogics\Helpers::format_currency($shipment->collectable_amount) }}</td>
                            <td class="text-right">{{ \App\CentralLogics\Helpers::format_currency($charges) }}</td>
                            <td class="text-right">{{ \App\CentralLogics\Helpers::format_currency($netReceivable) }}</td>
                            <td class="text-right">{{ \App\CentralLogics\Helpers::format_currency($shipment->settled_amount ?? 0) }}</td>
                            <td class="text-right font-weight-bold">{{ \App\CentralLogics\Helpers::format_currency($balance) }}</td>
                            <td>
                                <div class="fs-12">{{ translate('Delivered') }}: {{ $shipment->delivered_at?->format('d M Y') ?? translate('N/A') }}</div>
                                <div class="fs-12">{{ translate('Collected') }}: {{ $shipment->cod_collected_at?->format('d M Y') ?? translate('N/A') }}</div>
                                <div class="fs-12">{{ translate('Settled') }}: {{ $shipment->settlement_paid_at?->format('d M Y') ?? translate('N/A') }}</div>
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="10" class="text-center py-4">{{ translate('No courier parcel found') }}</td></tr>
                    @endforelse
                    </tbody>
                </table>
            </div>
            @if($shipments->hasPages())
                <div class="card-footer">{!! $shipments->links() !!}</div>
            @endif
        </div>
    </div>
@endsection
