@extends('layouts.admin.app')

@section('title', 'Customer Advance Receive')

@push('css_or_js')
    <style>
        .advance-summary-card {
            height: 100%;
            border: 1px solid #e7eaf3;
            border-radius: 6px;
            padding: 18px;
            background: #fff;
        }
        .advance-summary-card .label {
            color: #71869d;
            font-size: 12px;
            margin-bottom: 8px;
        }
        .advance-summary-card .value {
            color: #1e2022;
            font-size: 20px;
            font-weight: 700;
            line-height: 1.2;
        }
        .advance-summary-card.is-due .value,
        .advance-summary-card.is-cod .value {
            color: #00a65a;
        }
        .advance-customer-meta {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px 24px;
        }
        @media (max-width: 575.98px) {
            .advance-customer-meta {
                grid-template-columns: 1fr;
            }
        }
    </style>
@endpush

@section('content')
    <div class="content container-fluid">
        <div class="page-header d-flex flex-wrap align-items-center justify-content-between gap-2">
            <h1 class="page-header-title mb-0">
                <span class="page-header-icon">
                    <i class="tio-wallet-outlined"></i>
                </span>
                Customer Advance Receive
            </h1>
            @if($order)
                <div class="d-flex flex-wrap gap-2">
                    <a class="btn btn-outline-primary" href="{{ route('admin.order.details', $order->id) }}">
                        <i class="tio-visible-outlined mr-1"></i> View Order
                    </a>
                    <a class="btn btn-outline-secondary" href="{{ route('admin.order.generate-invoice', $order->id) }}" target="_blank">
                        <i class="tio-receipt-outlined mr-1"></i> Invoice
                    </a>
                </div>
            @endif
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" action="{{ route('admin.order.customer-advance.index') }}">
                    <label class="form-label" for="invoice-number">Invoice Number</label>
                    <div class="input-group">
                        <input id="invoice-number" class="form-control" type="search" name="invoice_number"
                               value="{{ $invoiceNumber }}" placeholder="Example: 100002" required autofocus>
                        <div class="input-group-append">
                            <button class="btn btn--primary" type="submit">
                                <i class="tio-search mr-1"></i> Search Invoice
                            </button>
                        </div>
                    </div>
                    @if($searchError)
                        <div class="text-danger mt-2">{{ $searchError }}</div>
                    @endif
                </form>
            </div>
        </div>

        @if($order)
            @php($advanceReceipts = $order->receipts->where('account_type', \App\Models\OrderReceipt::ACCOUNT_TYPE_CUSTOMER_ADVANCE))
            <div class="card mb-4">
                <div class="card-header">
                    <div>
                        <h4 class="mb-1">Invoice #{{ $order->id }}</h4>
                        <span class="text-muted">Customer and delivery details</span>
                    </div>
                    <span class="badge badge-soft-info text-capitalize">{{ str_replace('_', ' ', $order->order_status) }}</span>
                </div>
                <div class="card-body advance-customer-meta">
                    <div><span class="text-muted">Customer Name:</span> <strong>{{ $customer['name'] }}</strong></div>
                    <div><span class="text-muted">Mobile:</span> <strong>{{ $customer['mobile'] }}</strong></div>
                    <div><span class="text-muted">District:</span> <strong>{{ $customer['district'] }}</strong></div>
                    <div><span class="text-muted">Thana:</span> <strong>{{ $customer['thana'] }}</strong></div>
                </div>
            </div>

            <div class="row g-3 mb-4">
                <div class="col-sm-6 col-xl-3 mb-3 mb-xl-0">
                    <div class="advance-summary-card">
                        <div class="label">Order Total</div>
                        <div class="value">{{ \App\CentralLogics\Helpers::format_currency($summary['adjusted_total']) }}</div>
                    </div>
                </div>
                <div class="col-sm-6 col-xl-3 mb-3 mb-xl-0">
                    <div class="advance-summary-card">
                        <div class="label">Previous Advance</div>
                        <div class="value">{{ \App\CentralLogics\Helpers::format_currency($summary['advance_received']) }}</div>
                    </div>
                </div>
                <div class="col-sm-6 col-xl-3 mb-3 mb-sm-0">
                    <div class="advance-summary-card is-due">
                        <div class="label">Current Due</div>
                        <div class="value">{{ \App\CentralLogics\Helpers::format_currency($summary['remaining_due']) }}</div>
                    </div>
                </div>
                <div class="col-sm-6 col-xl-3">
                    <div class="advance-summary-card is-cod">
                        <div class="label">Courier COD Amount</div>
                        <div class="value">{{ \App\CentralLogics\Helpers::format_currency($summary['courier_collectable']) }}</div>
                    </div>
                </div>
            </div>

            @if($courierLocked)
                <div class="alert alert-warning">
                    <i class="tio-warning-outlined mr-1"></i>
                    This order is already booked with a courier. Advance changes are locked to prevent a COD mismatch.
                </div>
            @elseif($advanceReceiveBlocked)
                <div class="alert alert-warning">
                    <i class="tio-warning-outlined mr-1"></i>
                    A new advance cannot be received or edited for this order status. A posted advance can still be cancelled when accounting permits it.
                </div>
            @endif

            <div class="row">
                <div class="col-xl-5 mb-4 mb-xl-0">
                    <div class="card h-100">
                        <div class="card-header">
                            <h4 class="mb-0">Receive Advance</h4>
                        </div>
                        <div class="card-body">
                            @if(isset($errors) && $errors->any())
                                <div class="alert alert-danger">
                                    {{ $errors->first() }}
                                </div>
                            @endif

                            <form method="POST" action="{{ route('admin.order.customer-advance.store') }}">
                                @csrf
                                <input type="hidden" name="order_id" value="{{ $order->id }}">
                                <input type="hidden" name="idempotency_key" value="{{ old('idempotency_key', (string) \Illuminate\Support\Str::uuid()) }}">

                                <div class="form-group">
                                    <label class="form-label" for="advance-amount">Amount</label>
                                    <input id="advance-amount" class="form-control" type="number" name="amount"
                                           value="{{ old('amount') }}" min="0.001" max="{{ $summary['remaining_due'] }}" step="0.001" required
                                           {{ $advanceReceiveBlocked || $summary['remaining_due'] <= 0 ? 'disabled' : '' }}>
                                    <small class="text-muted">Maximum: {{ \App\CentralLogics\Helpers::format_currency($summary['remaining_due']) }}</small>
                                </div>

                                <div class="form-row">
                                    <div class="form-group col-md-6">
                                        <label class="form-label" for="payment-method">Payment Method</label>
                                        <select id="payment-method" class="form-control" name="payment_method" required
                                                {{ $advanceReceiveBlocked || $summary['remaining_due'] <= 0 ? 'disabled' : '' }}>
                                            @foreach(['cash' => 'Cash', 'bank_transfer' => 'Bank Transfer', 'bkash' => 'bKash', 'nagad' => 'Nagad', 'card' => 'Card'] as $value => $label)
                                                <option value="{{ $value }}" @selected(old('payment_method', 'cash') === $value)>{{ $label }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="form-group col-md-6">
                                        <label class="form-label" for="received-date">Date</label>
                                        <input id="received-date" class="form-control" type="date" name="received_at"
                                               value="{{ old('received_at', now()->toDateString()) }}" required
                                               {{ $advanceReceiveBlocked || $summary['remaining_due'] <= 0 ? 'disabled' : '' }}>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="form-label" for="advance-account">Account / Cashbox</label>
                                    <select id="advance-account" class="form-control" name="account_id" required
                                            {{ $advanceReceiveBlocked || $summary['remaining_due'] <= 0 ? 'disabled' : '' }}>
                                        @foreach($accounts as $account)
                                            <option value="{{ $account->id }}" @selected((string) old('account_id', $accounts->first()?->id) === (string) $account->id)>
                                                {{ $account->code }} - {{ $account->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label class="form-label" for="transaction-ref">Transaction Reference</label>
                                    <input id="transaction-ref" class="form-control" type="text" name="transaction_ref"
                                           value="{{ old('transaction_ref') }}" maxlength="120" placeholder="Optional for cash"
                                           {{ $advanceReceiveBlocked || $summary['remaining_due'] <= 0 ? 'disabled' : '' }}>
                                </div>

                                <div class="form-group">
                                    <label class="form-label" for="advance-note">Note</label>
                                    <textarea id="advance-note" class="form-control" name="notes" rows="3" maxlength="1000"
                                              {{ $advanceReceiveBlocked || $summary['remaining_due'] <= 0 ? 'disabled' : '' }}>{{ old('notes') }}</textarea>
                                </div>

                                <button class="btn btn--primary btn-block" type="submit"
                                        {{ $advanceReceiveBlocked || $summary['remaining_due'] <= 0 || $accounts->isEmpty() ? 'disabled' : '' }}>
                                    <i class="tio-save mr-1"></i> Save Advance
                                </button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-xl-7">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h4 class="mb-0">Advance History</h4>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-borderless table-thead-bordered table-nowrap table-align-middle">
                                <thead class="thead-light">
                                <tr>
                                    <th>Receipt</th>
                                    <th>Date</th>
                                    <th>Method / Account</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th class="text-right">Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse($advanceReceipts as $receipt)
                                    <tr>
                                        <td>
                                            <a href="{{ route('admin.order.financial.receipt.voucher', $receipt->id) }}" target="_blank">
                                                {{ $receipt->voucher_no }}
                                            </a>
                                        </td>
                                        <td>{{ optional($receipt->received_at)->format('d M Y') }}</td>
                                        <td>
                                            <div class="text-capitalize">{{ str_replace('_', ' ', $receipt->payment_method) }}</div>
                                            <small class="text-muted">{{ $receipt->account?->name ?: 'N/A' }}</small>
                                        </td>
                                        <td>{{ \App\CentralLogics\Helpers::format_currency($receipt->amount) }}</td>
                                        <td>
                                            <span class="badge {{ $receipt->receipt_status === 'posted' ? 'badge-soft-success' : 'badge-soft-danger' }} text-capitalize">
                                                {{ $receipt->receipt_status }}
                                            </span>
                                        </td>
                                        <td class="text-right">
                                            @if($receipt->receipt_status === 'posted')
                                                <button class="btn btn-sm btn-outline-primary" type="button" data-toggle="modal"
                                                        data-target="#edit-advance-{{ $receipt->id }}" {{ $advanceReceiveBlocked ? 'disabled' : '' }}>
                                                    <i class="tio-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-outline-danger" type="button" data-toggle="modal"
                                                        data-target="#cancel-advance-{{ $receipt->id }}" {{ $courierLocked ? 'disabled' : '' }}>
                                                    <i class="tio-delete-outlined"></i>
                                                </button>
                                            @else
                                                <span class="text-muted">No action</span>
                                            @endif
                                        </td>
                                    </tr>
                                @empty
                                    <tr><td colspan="6" class="text-center text-muted py-5">No advance has been received for this invoice.</td></tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-header">
                            <h4 class="mb-0">Customer Ledger</h4>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-borderless table-thead-bordered table-nowrap table-align-middle mb-0">
                                <thead class="thead-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Entry</th>
                                    <th>Debit</th>
                                    <th>Credit</th>
                                    <th>Balance</th>
                                    <th>Status</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td>{{ optional($order->created_at)->format('d M Y') }}</td>
                                    <td>Invoice #{{ $order->id }}</td>
                                    <td>{{ \App\CentralLogics\Helpers::format_currency($summary['adjusted_total']) }}</td>
                                    <td>{{ \App\CentralLogics\Helpers::format_currency(0) }}</td>
                                    <td>{{ \App\CentralLogics\Helpers::format_currency($summary['adjusted_total']) }}</td>
                                    <td><span class="badge badge-soft-info">Posted</span></td>
                                </tr>
                                @php($non_advance_paid = (float) $order->payments->where('payment_status', 'paid')->whereNull('order_receipt_id')->sum('amount'))
                                @if($non_advance_paid > 0)
                                    <tr>
                                        <td>{{ optional($order->created_at)->format('d M Y') }}</td>
                                        <td>Existing Payment</td>
                                        <td>{{ \App\CentralLogics\Helpers::format_currency(0) }}</td>
                                        <td>{{ \App\CentralLogics\Helpers::format_currency($non_advance_paid) }}</td>
                                        <td>{{ \App\CentralLogics\Helpers::format_currency(max($summary['adjusted_total'] - $non_advance_paid, 0)) }}</td>
                                        <td><span class="badge badge-soft-success">Posted</span></td>
                                    </tr>
                                @endif
                                @foreach($order->customerLedgerEntries->sortBy('entry_date') as $entry)
                                    <tr>
                                        <td>{{ optional($entry->entry_date)->format('d M Y') }}</td>
                                        <td>{{ $entry->entry_type === 'advance_payment' ? 'Customer Advance' : str_replace('_', ' ', $entry->entry_type) }}</td>
                                        <td>{{ \App\CentralLogics\Helpers::format_currency($entry->debit) }}</td>
                                        <td>{{ \App\CentralLogics\Helpers::format_currency($entry->credit) }}</td>
                                        <td>{{ \App\CentralLogics\Helpers::format_currency($entry->balance_after) }}</td>
                                        <td>
                                            <span class="badge {{ $entry->status === 'posted' ? 'badge-soft-success' : 'badge-soft-danger' }} text-capitalize">
                                                {{ $entry->status }}
                                            </span>
                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            @foreach($advanceReceipts->where('receipt_status', 'posted') as $receipt)
                <div class="modal fade" id="edit-advance-{{ $receipt->id }}" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document">
                        <div class="modal-content">
                            <form method="POST" action="{{ route('admin.order.customer-advance.update', $receipt->id) }}">
                                @csrf
                                @method('PUT')
                                <div class="modal-header">
                                    <h5 class="modal-title">Edit {{ $receipt->voucher_no }}</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                </div>
                                <div class="modal-body">
                                    <div class="form-group">
                                        <label class="form-label">Amount</label>
                                        <input class="form-control" type="number" name="amount" value="{{ $receipt->amount }}"
                                               min="0.001" max="{{ $summary['remaining_due'] + $receipt->amount }}" step="0.001" required>
                                    </div>
                                    <div class="form-row">
                                        <div class="form-group col-md-6">
                                            <label class="form-label">Payment Method</label>
                                            <select class="form-control" name="payment_method" required>
                                                @foreach(['cash' => 'Cash', 'bank_transfer' => 'Bank Transfer', 'bkash' => 'bKash', 'nagad' => 'Nagad', 'card' => 'Card'] as $value => $label)
                                                    <option value="{{ $value }}" @selected($receipt->payment_method === $value)>{{ $label }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div class="form-group col-md-6">
                                            <label class="form-label">Date</label>
                                            <input class="form-control" type="date" name="received_at" value="{{ optional($receipt->received_at)->toDateString() }}" required>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Account / Cashbox</label>
                                        <select class="form-control" name="account_id" required>
                                            @foreach($accounts as $account)
                                                <option value="{{ $account->id }}" @selected((int) $receipt->account_id === (int) $account->id)>
                                                    {{ $account->code }} - {{ $account->name }}
                                                </option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">Transaction Reference</label>
                                        <input class="form-control" type="text" name="transaction_ref" value="{{ $receipt->transaction_ref }}" maxlength="120">
                                    </div>
                                    <div class="form-group mb-0">
                                        <label class="form-label">Note</label>
                                        <textarea class="form-control" name="notes" rows="3" maxlength="1000">{{ $receipt->notes }}</textarea>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
                                    <button type="submit" class="btn btn--primary">Update Advance</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="modal fade" id="cancel-advance-{{ $receipt->id }}" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document">
                        <div class="modal-content">
                            <form method="POST" action="{{ route('admin.order.customer-advance.void', $receipt->id) }}">
                                @csrf
                                <div class="modal-header">
                                    <h5 class="modal-title">Cancel {{ $receipt->voucher_no }}</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                                </div>
                                <div class="modal-body">
                                    <p>This reverses the receipt, invoice due, customer ledger and courier COD amount.</p>
                                    <label class="form-label">Cancellation Reason</label>
                                    <textarea class="form-control" name="reason" rows="3" maxlength="500" required></textarea>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-white" data-dismiss="modal">Keep Advance</button>
                                    <button type="submit" class="btn btn-danger">Cancel Advance</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            @endforeach
        @endif
    </div>
@endsection
