@php
    $financialSummary = $order->financialSummary();
    $courierAmountLocked = $order->courierShipment?->hasSuccessfulBooking() ?? false;
    $advanceReceiveBlocked = $courierAmountLocked || ! $order->canReceiveAdvance();
    $advanceVoidBlocked = $courierAmountLocked || in_array($order->order_status, ['delivered', 'refunded'], true);
    $exchangeBlocked = $courierAmountLocked && $order->order_status !== 'delivered';
    $money = fn ($amount) => \App\CentralLogics\Helpers::format_currency($amount);
    $advanceReceipts = $order->receipts->where(
        'account_type',
        \App\Models\OrderReceipt::ACCOUNT_TYPE_CUSTOMER_ADVANCE
    );
@endphp

<div class="card mt-2" id="order-financial-workflow">
    <div class="card-body">
        <h5 class="card-title text-dark mb-3 d-flex align-items-center">
            <span class="card-header-icon"><i class="tio-receipt"></i></span>
            <span>Payment &amp; Exchange</span>
        </h5>

        <div class="table-responsive mb-3">
            <table class="table table-sm table-borderless mb-0">
                <tbody>
                <tr>
                    <th class="pl-0">Invoice Total</th>
                    <td class="text-right pr-0 font-weight-bold">{{ $money($financialSummary['invoice_total']) }}</td>
                </tr>
                @if (abs($financialSummary['exchange_adjustment']) > 0.0005)
                    <tr>
                        <th class="pl-0">Exchange Adjustment</th>
                        <td class="text-right pr-0 {{ $financialSummary['exchange_adjustment'] < 0 ? 'text-success' : 'text-warning' }}">
                            {{ $financialSummary['exchange_adjustment'] > 0 ? '+' : '' }}{{ $money($financialSummary['exchange_adjustment']) }}
                        </td>
                    </tr>
                @endif
                <tr>
                    <th class="pl-0">Advance Received</th>
                    <td class="text-right pr-0 text-success">{{ $money($financialSummary['advance_received']) }}</td>
                </tr>
                <tr>
                    <th class="pl-0">Paid Amount</th>
                    <td class="text-right pr-0">{{ $money($financialSummary['paid_amount']) }}</td>
                </tr>
                <tr class="border-top">
                    <th class="pl-0 pt-2">Remaining Due</th>
                    <td class="text-right pr-0 pt-2 font-weight-bold">{{ $money($financialSummary['remaining_due']) }}</td>
                </tr>
                <tr>
                    <th class="pl-0">Courier COD Amount</th>
                    <td class="text-right pr-0 font-weight-bold text-primary">{{ $money($financialSummary['courier_collectable']) }}</td>
                </tr>
                @if ($financialSummary['customer_credit'] > 0.0005)
                    <tr>
                        <th class="pl-0">Customer Credit</th>
                        <td class="text-right pr-0 text-success">{{ $money($financialSummary['customer_credit']) }}</td>
                    </tr>
                @endif
                </tbody>
            </table>
        </div>

        @if ($courierAmountLocked)
            <div class="alert alert-warning py-2 px-3 mb-3">
                Courier COD is locked because this order already has a successful booking.
            </div>
        @endif

        <ul class="nav nav-tabs mb-3" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" data-toggle="tab" href="#advance-{{ $order->id }}" role="tab">Advance</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-toggle="tab" href="#exchange-{{ $order->id }}" role="tab">Exchange</a>
            </li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="advance-{{ $order->id }}" role="tabpanel">
                <form action="{{ route('admin.order.financial.advance', $order) }}" method="post" class="mb-3">
                    @csrf
                    <input type="hidden" name="idempotency_key" value="{{ (string) \Illuminate\Support\Str::uuid() }}">
                    <div class="form-row">
                        <div class="form-group col-sm-6">
                            <label>Amount</label>
                            <input type="number" name="amount" class="form-control" min="0.001" max="{{ $financialSummary['remaining_due'] }}" step="0.001" required {{ $advanceReceiveBlocked ? 'disabled' : '' }}>
                        </div>
                        <div class="form-group col-sm-6">
                            <label>Payment Method</label>
                            <select name="payment_method" class="form-control" required {{ $advanceReceiveBlocked ? 'disabled' : '' }}>
                                <option value="cash">Cash</option>
                                <option value="bkash">bKash</option>
                                <option value="nagad">Nagad</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="card">Card</option>
                                <option value="other">Other</option>
                            </select>
                        </div>
                        <div class="form-group col-12">
                            <label>Transaction Reference</label>
                            <input type="text" name="transaction_ref" class="form-control" maxlength="120" {{ $advanceReceiveBlocked ? 'disabled' : '' }}>
                        </div>
                        <div class="form-group col-12">
                            <label>Notes</label>
                            <textarea name="notes" class="form-control" rows="2" maxlength="1000" {{ $advanceReceiveBlocked ? 'disabled' : '' }}></textarea>
                        </div>
                    </div>
                    <button type="submit" class="btn btn--primary btn-block" {{ $advanceReceiveBlocked || $financialSummary['remaining_due'] <= 0.0005 ? 'disabled' : '' }}>
                        <i class="tio-receipt-outlined mr-1"></i> Receive Advance
                    </button>
                </form>

                @if ($advanceReceipts->isNotEmpty())
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead><tr><th>Voucher</th><th>Amount</th><th>Status</th><th></th></tr></thead>
                            <tbody>
                            @foreach ($advanceReceipts as $receipt)
                                <tr>
                                    <td>
                                        <a href="{{ route('admin.order.financial.receipt.voucher', $receipt) }}" target="_blank">{{ $receipt->voucher_no }}</a>
                                        <small class="d-block text-muted">{{ optional($receipt->received_at)->format('d M Y, h:i A') }}</small>
                                    </td>
                                    <td>{{ $money($receipt->amount) }}</td>
                                    <td><span class="badge badge-{{ $receipt->receipt_status === 'posted' ? 'success' : 'secondary' }}">{{ ucfirst($receipt->receipt_status) }}</span></td>
                                    <td class="text-right">
                                        @if ($receipt->receipt_status === 'posted' && ! $advanceVoidBlocked)
                                            <form method="post" action="{{ route('admin.order.financial.receipt.void', $receipt) }}" onsubmit="return confirm('Void this receipt and restore the order due?')">
                                                @csrf
                                                <button type="submit" class="btn btn-sm btn-outline-danger" title="Void receipt"><i class="tio-clear"></i></button>
                                            </form>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif
            </div>

            <div class="tab-pane fade" id="exchange-{{ $order->id }}" role="tabpanel">
                <form action="{{ route('admin.order.financial.exchange', $order) }}" method="post" class="mb-3 js-order-exchange-form">
                    @csrf
                    <input type="hidden" name="idempotency_key" value="{{ (string) \Illuminate\Support\Str::uuid() }}">
                    <div class="form-group">
                        <label>Returned Product</label>
                        <select name="order_detail_id" class="form-control js-returned-detail" required {{ $exchangeBlocked ? 'disabled' : '' }}>
                            <option value="">Select ordered product</option>
                            @foreach ($order->details as $detail)
                                <option value="{{ $detail->id }}" data-max="{{ $detail->display_quantity }}">
                                    {{ $detail->display_item_name }} ({{ $detail->display_quantity }} ordered)
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-sm-6">
                            <label>Return Quantity</label>
                            <input type="number" name="return_quantity" class="form-control js-return-quantity" min="1" value="1" required {{ $exchangeBlocked ? 'disabled' : '' }}>
                        </div>
                        <div class="form-group col-sm-6">
                            <label>Replacement Quantity</label>
                            <input type="number" name="replacement_quantity" class="form-control" min="1" value="1" required {{ $exchangeBlocked ? 'disabled' : '' }}>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Replacement Product</label>
                        <select name="replacement_item_id" class="form-control js-financial-replacement-item" data-url="{{ route('admin.order.financial.replacement-items', $order) }}" required {{ $exchangeBlocked ? 'disabled' : '' }}></select>
                    </div>
                    <div class="form-group">
                        <label>Replacement Unit Price</label>
                        <input type="number" name="replacement_unit_price" class="form-control js-replacement-price" min="0" step="0.001" required {{ $exchangeBlocked ? 'disabled' : '' }}>
                    </div>
                    <div class="form-group">
                        <label>Notes</label>
                        <textarea name="notes" class="form-control" rows="2" maxlength="1000" {{ $exchangeBlocked ? 'disabled' : '' }}></textarea>
                    </div>
                    <button type="submit" class="btn btn--primary btn-block" {{ $exchangeBlocked ? 'disabled' : '' }}>
                        <i class="tio-swap-horizontal mr-1"></i> Post Exchange
                    </button>
                </form>

                @if ($order->exchanges->isNotEmpty())
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead><tr><th>Exchange</th><th>Difference</th><th>Status</th><th></th></tr></thead>
                            <tbody>
                            @foreach ($order->exchanges as $exchange)
                                <tr>
                                    <td>
                                        {{ $exchange->exchange_no }}
                                        <small class="d-block text-muted">
                                            {{ optional($exchange->items->firstWhere('direction', 'returned'))->item_name }}
                                            &rarr; {{ optional($exchange->items->firstWhere('direction', 'replacement'))->item_name }}
                                        </small>
                                    </td>
                                    <td>{{ $exchange->difference_amount > 0 ? '+' : '' }}{{ $money($exchange->difference_amount) }}</td>
                                    <td><span class="badge badge-{{ $exchange->exchange_status === 'posted' ? 'success' : 'secondary' }}">{{ ucfirst($exchange->exchange_status) }}</span></td>
                                    <td class="text-right">
                                        @if ($exchange->exchange_status === 'posted' && (! $exchange->affects_collectable || ! $courierAmountLocked))
                                            <form method="post" action="{{ route('admin.order.financial.exchange.void', $exchange) }}" onsubmit="return confirm('Void this exchange and recalculate the balances?')">
                                                @csrf
                                                <button type="submit" class="btn btn-sm btn-outline-danger" title="Void exchange"><i class="tio-clear"></i></button>
                                            </form>
                                        @endif
                                    </td>
                                </tr>
                            @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>

@push('script_2')
<script>
    'use strict';
    $(document).ready(function () {
        const $exchangeForm = $('.js-order-exchange-form');
        const $item = $exchangeForm.find('.js-financial-replacement-item');

        if ($item.length && $.fn.select2) {
            $item.select2({
                width: '100%',
                placeholder: 'Search replacement product',
                minimumInputLength: 1,
                ajax: {
                    url: $item.data('url'),
                    dataType: 'json',
                    delay: 250,
                    data: params => ({q: params.term || ''}),
                    processResults: data => data
                }
            });

            $item.on('select2:select', function (event) {
                $exchangeForm.find('.js-replacement-price').val(event.params.data.price);
            });
        }

        $exchangeForm.find('.js-returned-detail').on('change', function () {
            const max = $(this).find(':selected').data('max') || 1;
            $exchangeForm.find('.js-return-quantity').attr('max', max).val(1);
        });
    });
</script>
@endpush
