@extends('layouts.app')

@section('content')
    <x-common.page-breadcrumb pageTitle="{{ $title ?? 'Pelunasan' }}" />

    @if(session('success'))
        <div class="mb-4 rounded-lg bg-success-50 p-4 text-success-700 dark:bg-success-500/15 dark:text-success-400">
            {{ session('success') }}
        </div>
    @endif

    @if(session('error'))
        <div class="mb-4 rounded-lg bg-error-50 p-4 text-error-700 dark:bg-error-500/15 dark:text-error-400">
            {{ session('error') }}
        </div>
    @endif

    <div class="mb-6 rounded-2xl border border-brand-200 bg-brand-50 p-5 dark:border-brand-900/40 dark:bg-brand-900/10">
        <div class="flex items-start gap-4">
            <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-500 text-white">
                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                </svg>
            </div>

            <div class="flex-1">
                <div class="flex flex-wrap items-center gap-2">
                    <h4 class="text-sm font-semibold text-gray-900 dark:text-white/90">Kasir Guidance</h4>
                    <span class="rounded-full bg-white/80 px-2 py-0.5 text-xs font-medium text-gray-700 dark:bg-white/10 dark:text-white/70">
                        Mode Pelunasan
                    </span>
                </div>

                <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                    Halaman ini dipakai untuk melunasi tagihan satuan atau beberapa order sekaligus.
                    Split payment bisa dipakai untuk invoice tunggal maupun batch.
                </p>

                <div class="mt-3 grid grid-cols-1 gap-2 md:grid-cols-3">
                    <div class="rounded-xl bg-white/70 p-3 text-xs text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                        <div class="mb-1 font-semibold">Bayar Satuan</div>
                        <div>Klik tombol <span class="font-semibold">Bayar</span> pada satu invoice untuk pelunasan single invoice.</div>
                    </div>
                    <div class="rounded-xl bg-white/70 p-3 text-xs text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                        <div class="mb-1 font-semibold">Split Payment</div>
                        <div>Bisa gabungan tunai, transfer, dan e-wallet untuk invoice tunggal maupun batch.</div>
                    </div>
                    <div class="rounded-xl bg-white/70 p-3 text-xs text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                        <div class="mb-1 font-semibold">Aman untuk Transaksi Lama</div>
                        <div>Flow lama tetap aman karena backend masih menerima format single payment sebagai fallback.</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2">
        <x-posgraf.stat-card
            title="Total Order Belum Lunas"
            value="{{ $summary['total_orders'] ?? 0 }}"
            color="warning"
        >
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            </x-slot>
        </x-posgraf.stat-card>

        <x-posgraf.stat-card
            title="Total Piutang"
            value="Rp {{ number_format($summary['total_receivables'] ?? 0, 0, ',', '.') }}"
            color="error"
        >
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            </x-slot>
        </x-posgraf.stat-card>
    </div>

    <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="border-b border-gray-200 dark:border-gray-800">
            <div class="flex px-5">
                <a href="{{ route('kasir.pelunasan', ['tab' => 'active', 'type' => $currentType]) }}"
                   class="border-b-2 px-6 py-4 text-sm font-medium transition-colors {{ ($currentTab ?? 'active') === 'active' ? 'border-brand-500 text-brand-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">
                    Tagihan Aktif
                </a>
                <a href="{{ route('kasir.pelunasan', ['tab' => 'history', 'type' => $currentType]) }}"
                   class="border-b-2 px-6 py-4 text-sm font-medium transition-colors {{ ($currentTab ?? 'active') === 'history' ? 'border-brand-500 text-brand-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">
                    Riwayat Pelunasan
                </a>
            </div>
        </div>

        <div class="flex flex-col justify-between gap-3 border-b border-gray-200 px-5 py-4 dark:border-gray-800 sm:flex-row sm:items-center">
            <div class="flex items-center gap-3">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">
                    {{ ($currentTab ?? 'active') === 'history' ? 'Daftar Pembayaran Lunas' : 'Daftar Tagihan' }}
                </h3>

                <div class="relative flex min-w-[220px] items-center">
                    <div class="relative w-full">
                        <x-form.select
                            name="customer_filter"
                            placeholder="Semua Customer"
                            :options="['' => 'Semua Customer'] + $allCustomers->mapWithKeys(fn($c) => [$c => $c])->toArray()"
                            :searchable="true"
                            :value="request('customer')"
                            class="!h-[34px] !py-0 flex items-center"
                            x-init="$watch('value', value => filterByCustomer(value))"
                        />
                    </div>
                </div>
            </div>

            <div class="flex items-center gap-2">
                <div class="flex rounded-lg bg-gray-100 p-1 dark:bg-gray-800">
                    <a href="{{ route('kasir.pelunasan', ['type' => 'credit', 'tab' => $currentTab ?? 'active']) }}"
                        class="rounded-md px-3 py-1.5 text-xs font-medium transition-colors {{ $currentType === 'credit' ? 'bg-white text-gray-900 shadow-sm dark:bg-gray-700 dark:text-white' : 'text-gray-500 hover:text-gray-700' }}">
                        Piutang
                    </a>
                    <a href="{{ route('kasir.pelunasan', ['type' => 'non_credit', 'tab' => $currentTab ?? 'active']) }}"
                        class="rounded-md px-3 py-1.5 text-xs font-medium transition-colors {{ $currentType === 'non_credit' ? 'bg-white text-gray-900 shadow-sm dark:bg-gray-700 dark:text-white' : 'text-gray-500 hover:text-gray-700' }}">
                        Non-Piutang
                    </a>
                </div>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full" x-data="batchPayment()">
                <thead>
                    <tr class="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-900/50">
                        <th class="px-3 py-3 text-center">
                            <input type="checkbox" x-model="selectAll" @change="toggleSelectAll()"
                                class="size-4 rounded border-gray-300 text-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:bg-gray-700">
                        </th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-gray-500">Tanggal</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-gray-500">Invoice</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold uppercase text-gray-500">Pelanggan</th>
                        <th class="px-4 py-3 text-right text-xs font-semibold uppercase text-gray-500">Total</th>
                        <th class="px-4 py-3 text-right text-xs font-semibold uppercase text-gray-500 whitespace-nowrap" style="min-width: 120px;">Dibayar</th>
                        <th class="px-4 py-3 text-right text-xs font-semibold uppercase text-gray-500">Sisa</th>
                        <th class="px-4 py-3 text-center text-xs font-semibold uppercase text-gray-500">Umur</th>
                        <th class="px-4 py-3 text-center text-xs font-semibold uppercase text-gray-500">Aksi</th>
                    </tr>
                </thead>

                <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                    @forelse($orders as $order)
                        @php
        $__roundOnlyAmount = function ($amount) {
            $amount = max((float) $amount, 0);
            $roundTo = 1000;

            if ($amount <= 0) {
                return 0;
            }

            return (float) (ceil($amount / $roundTo) * $roundTo);
        };

        $__meterMinRoundAmount = function ($amount) use ($__roundOnlyAmount) {
            $amount = max((float) $amount, 0);
            $minimumOrder = 10000;

            if ($amount <= 0) {
                return 0;
            }

            if ($amount < $minimumOrder) {
                $amount = $minimumOrder;
            }

            return $__roundOnlyAmount($amount);
        };

        $__normalizeUnit = function ($unit) {
            $unit = strtolower(trim((string) $unit));
            $unit = str_replace(['²', '�'], ['2', '2'], $unit);

            if (in_array($unit, ['m2', 'meter2', 'meter persegi', 'per meter persegi'], true)) {
                return 'm2';
            }

            if (in_array($unit, ['meter', 'm', 'per meter'], true)) {
                return 'meter';
            }

            return $unit ?: 'lembar';
        };

        $__parseM2FromDescription = function ($description) {
            $description = strtolower(trim((string) $description));

            if ($description === '') {
                return 0;
            }

            $description = str_replace(['²', '�', '*'], ['2', '2', 'x'], $description);

            if (preg_match('/([0-9]+(?:[\.,][0-9]+)?)\s*[x×]\s*([0-9]+(?:[\.,][0-9]+)?)/i', $description, $matches)) {
                $width = (float) str_replace(',', '.', $matches[1]);
                $height = (float) str_replace(',', '.', $matches[2]);

                if ($width > 0 && $height > 0) {
                    if ($width >= 10 || $height >= 10) {
                        $width = $width / 100;
                        $height = $height / 100;
                    }

                    return round($width * $height, 4);
                }
            }

            return 0;
        };

        $__itemDisplaySubtotal = function ($item) use ($__roundOnlyAmount, $__meterMinRoundAmount, $__normalizeUnit, $__parseM2FromDescription) {
            $unit = $__normalizeUnit($item->size_unit ?? $item->unit ?? 'lembar');
            $storedSubtotal = max((float) ($item->subtotal ?? $item->total_price ?? 0), 0);

            if ($storedSubtotal > 0) {
                return in_array($unit, ['m2', 'meter'], true)
                    ? $__meterMinRoundAmount($storedSubtotal)
                    : $__roundOnlyAmount($storedSubtotal);
            }

            $qty = max((float) ($item->qty ?? 1), 0);
            $basePrice = max((float) ($item->base_price ?? $item->calculated_price ?? $item->price ?? 0), 0);
            $sizeValue = max((float) ($item->size_value ?? 0), 0);

            if ($unit === 'm2') {
                if ($sizeValue <= 0) {
                    $sizeValue = $__parseM2FromDescription($item->size_description ?? $item->size ?? '');
                }

                if ($sizeValue <= 0) {
                    $sizeValue = 1;
                }

                return $__meterMinRoundAmount($basePrice * $sizeValue * $qty);
            }

            if ($unit === 'meter') {
                $sizeValue = $sizeValue > 0 ? $sizeValue : 1;
                return $__meterMinRoundAmount($basePrice * $sizeValue * $qty);
            }

            return $__roundOnlyAmount($basePrice * $qty);
        };

        $__orderDisplaySubtotalBeforePpn = function ($order) use ($__itemDisplaySubtotal, $__roundOnlyAmount) {
            $items = method_exists($order, 'items')
                ? ($order->relationLoaded('items') ? $order->items : $order->items()->get())
                : collect();

            $activeItems = $items->filter(function ($item) {
                if (method_exists($item, 'isCancelled')) {
                    return !$item->isCancelled();
                }

                return !(bool) ($item->is_cancelled ?? false);
            });

            if ($activeItems->isNotEmpty()) {
                return (float) $activeItems->sum(fn ($item) => $__itemDisplaySubtotal($item));
            }

            $subtotalBeforePpn = (float) ($order->subtotal_before_ppn ?? 0);
            if ($subtotalBeforePpn > 0) {
                return $__roundOnlyAmount($subtotalBeforePpn);
            }

            $total = (float) ($order->total_price ?? 0);
            $ppn = (float) ($order->ppn_amount ?? 0);

            if ((bool) ($order->use_ppn ?? false) && $ppn > 0 && $total > $ppn) {
                return $__roundOnlyAmount($total - $ppn);
            }

            return $__roundOnlyAmount($total);
        };

        $__orderDisplayTotal = function ($order) use ($__orderDisplaySubtotalBeforePpn) {
            $subtotal = $__orderDisplaySubtotalBeforePpn($order);
            $ppn = ((bool) ($order->use_ppn ?? false) || (float) ($order->ppn_amount ?? 0) > 0)
                ? (float) ($order->ppn_amount ?? 0)
                : 0;

            return (float) ($subtotal + $ppn);
        };

        $__orderDisplayRemaining = function ($order) use ($__orderDisplayTotal) {
            $paid = method_exists($order, 'getTotalPaid') ? (float) $order->getTotalPaid() : (float) ($order->paid_amount ?? 0);

            return max((float) $__orderDisplayTotal($order) - $paid, 0);
        };

                            $age = (int) floor($order->created_at->diffInDays(now()));
                            $ageClass = $age > 30 ? 'text-error-600 bg-error-50' : ($age > 7 ? 'text-warning-600 bg-warning-50' : 'text-gray-600 bg-gray-100');
                            $totalPaid = $order->getTotalPaid();
                            $displayTotal = $__orderDisplayTotal($order);
                            $remaining = $__orderDisplayRemaining($order);
                        @endphp

                        <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]" :class="isSelected({{ $order->id }}) && 'bg-brand-50 dark:bg-brand-500/10'">
                            <td class="px-3 py-3 text-center">
                                <input type="checkbox"
                                    :checked="isSelected({{ $order->id }})"
                                    @change="toggleOrder({{ $order->id }}, '{{ $order->invoice_number }}', {{ $remaining }}, '{{ addslashes($order->customer_name) }}')"
                                    class="size-4 rounded border-gray-300 text-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:bg-gray-700">
                            </td>

                            <td class="px-4 py-3 text-sm text-gray-500">{{ $order->created_at->format('d/m/Y') }}</td>

                            <td class="px-4 py-3">
                                <a href="{{ route('orders.show', $order) }}" class="text-sm font-medium text-brand-600 hover:text-brand-700">
                                    {{ $order->invoice_number }}
                                </a>
                                @if($order->is_credit)
                                    <span class="ml-1 inline-flex items-center rounded-full bg-warning-50 px-1.5 py-0.5 text-[10px] font-medium text-warning-700 dark:bg-warning-500/20 dark:text-warning-400">Piutang</span>
                                @endif
                                @if($order->isPartiallyPaid())
                                    <span class="ml-1 inline-flex items-center rounded-full bg-blue-light-50 px-1.5 py-0.5 text-[10px] font-medium text-blue-light-700">Cicilan</span>
                                @endif
                            </td>

                            <td class="px-4 py-3">
                                <button type="button"
                                    @click="selectByCustomer('{{ addslashes($order->customer_name) }}')"
                                    class="cursor-pointer text-sm text-gray-800 hover:text-brand-600 hover:underline dark:text-white/90 dark:hover:text-brand-400"
                                    title="Klik untuk pilih semua order pelanggan ini">
                                    {{ $order->customer_name }}
                                </button>
                            </td>

                            <td class="px-4 py-3 text-right text-sm text-gray-700 dark:text-gray-300">
                                Rp {{ number_format($displayTotal, 0, ',', '.') }}
                            </td>

                            @if($order->payments->count() > 0)
                                @php
                                    $paymentData = $order->payments->map(fn($p) => [
                                        'id' => $p->id,
                                        'date' => $p->created_at->format('d/m/Y H:i'),
                                        'amount' => $p->amount,
                                        'method' => $p->payment_method,
                                        'proof' => $p->proof_path ? asset('storage/' . $p->proof_path) : null,
                                        'notes' => $p->notes,
                                        'cashier' => $p->cashier->name ?? '-'
                                    ])->values()->toJson();
                                @endphp
                                <td class="px-4 py-3 text-right whitespace-nowrap">
                                    <button type="button"
                                        data-payments="{{ $paymentData }}"
                                        data-invoice="{{ $order->invoice_number }}"
                                        onclick="openHistoryDialog(JSON.parse(this.dataset.payments), this.dataset.invoice)"
                                        class="inline-flex items-center gap-1 text-sm font-medium text-success-600 hover:text-success-700 dark:text-success-400 dark:hover:text-success-300 hover:underline cursor-pointer"
                                        title="Klik untuk lihat riwayat pembayaran">
                                        Rp {{ number_format($totalPaid, 0, ',', '.') }}
                                        <svg class="size-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                        </svg>
                                    </button>
                                </td>
                            @else
                                <td class="px-4 py-3 text-right text-sm text-gray-400">-</td>
                            @endif

                            <td class="px-4 py-3 text-right text-sm font-semibold text-error-600 dark:text-error-400">
                                Rp {{ number_format($remaining, 0, ',', '.') }}
                            </td>

                            <td class="px-4 py-3 text-center">
                                <span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium {{ $ageClass }}">
                                    {{ $age }} hari
                                </span>
                            </td>

                            <td class="px-4 py-3 text-center">
                                <div class="flex items-center justify-center gap-2">
                                    @if(($currentTab ?? 'active') === 'active')
                                        <button
                                            type="button"
                                            onclick="openPaymentDialog({{ $order->id }}, '{{ $order->invoice_number }}', {{ $remaining }})"
                                            class="inline-flex items-center gap-1 rounded-lg bg-success-500 px-3 py-1.5 text-xs font-medium text-white hover:bg-success-600 transition-colors"
                                        >
                                            <svg class="size-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                            </svg>
                                            Bayar
                                        </button>
                                    @else
                                        <a href="{{ route('print.nota', $order) }}" target="_blank" class="text-gray-400 hover:text-brand-500" title="Cetak Nota">
                                            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                                            </svg>
                                        </a>
                                    @endif

                                    <a href="{{ route('orders.show', $order) }}" class="text-gray-500 hover:text-brand-500" title="Lihat Detail">
                                        <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                        </svg>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="9" class="px-5 py-12 text-center">
                                <div class="flex flex-col items-center">
                                    <svg class="mb-3 h-12 w-12 text-success-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                    <p class="text-sm text-success-600 dark:text-success-400 font-medium">Tidak ada tagihan</p>
                                </div>
                            </td>
                        </tr>
                    @endforelse
                </tbody>

                @if($orders->count() > 0)
                    <tfoot class="border-t-2 border-gray-300 bg-gray-50 dark:border-gray-700 dark:bg-gray-900/50">
                        <tr>
                            <td colspan="6" class="px-4 py-4 text-sm font-semibold text-gray-800 dark:text-white/90">Total Piutang</td>
                            <td class="px-4 py-4 text-right text-base font-bold text-error-600 dark:text-error-400">
                                Rp {{ number_format($orders->sum(fn ($o) => $__orderDisplayRemaining($o)), 0, ',', '.') }}
                            </td>
                            <td colspan="2"></td>
                        </tr>
                    </tfoot>
                @endif

                <template x-if="selectedOrders.length > 0">
                    <div class="fixed bottom-6 left-1/2 -translate-x-1/2 z-40">
                        <div class="flex items-center gap-4 rounded-xl bg-gray-900 px-5 py-3 shadow-xl dark:bg-gray-700">
                            <div class="text-white">
                                <span class="font-semibold" x-text="selectedOrders.length"></span> order dipilih
                                <span class="mx-2 text-gray-400">•</span>
                                <span class="text-success-400">Rp <span x-text="formatRupiah(totalSelected)"></span></span>
                            </div>

                            <div class="flex items-center gap-2">
                                @if(($currentTab ?? 'active') === 'history')
                                    <button type="button" @click="printSelected()"
                                        class="rounded-lg bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600 transition-colors flex items-center gap-2">
                                        <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                                        </svg>
                                        Cetak Gabungan
                                    </button>
                                @endif

                                @if(($currentTab ?? 'active') === 'active')
                                    <button type="button" @click="openBatchDialog()"
                                        class="rounded-lg bg-success-500 px-4 py-2 text-sm font-semibold text-white hover:bg-success-600 transition-colors">
                                        Bayar Terpilih
                                    </button>
                                @endif

                                <button type="button" @click="clearSelection()"
                                    class="rounded-lg bg-gray-700 px-3 py-2 text-sm text-gray-300 hover:bg-gray-600 transition-colors dark:bg-gray-600 dark:hover:bg-gray-500">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </template>
            </table>
        </div>

        @if($orders->hasPages())
            <div class="border-t border-gray-200 px-5 py-4 dark:border-gray-800">
                {{ $orders->links() }}
            </div>
        @endif
    </div>

    {{-- Payment Dialog --}}
    <div id="paymentDialog" class="fixed inset-0 z-50 hidden overflow-y-auto bg-black/50 p-4 backdrop-blur-sm">
        <div class="flex min-h-full items-start justify-center py-4">
            <div class="my-6 flex w-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-xl dark:bg-gray-800">
                <div class="flex items-center justify-between border-b border-gray-200 px-6 py-4 dark:border-gray-700">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-800 dark:text-white">Pelunasan</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Split payment untuk satu invoice</p>
                    </div>
                    <button type="button" onclick="closePaymentDialog()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>

                <form id="paymentForm" method="POST" enctype="multipart/form-data" class="flex min-h-0 flex-1 flex-col" x-data="singleSplitPaymentForm()">
                    @csrf

                    <div class="min-h-0 flex-1 overflow-y-auto p-6">
                        <div class="mb-4 rounded-lg bg-gray-50 p-3 dark:bg-gray-700/50">
                            <p class="text-sm text-gray-600 dark:text-gray-400">
                                Invoice: <span id="paymentInvoice" class="font-semibold text-gray-800 dark:text-white"></span>
                            </p>
                            <p class="text-sm text-gray-600 dark:text-gray-400">
                                Sisa Piutang: <span id="paymentRemaining" class="font-semibold text-error-600 dark:text-error-400"></span>
                            </p>
                        </div>

                        <div class="mb-4 rounded-xl border border-brand-200 bg-brand-50 px-4 py-3 text-xs text-brand-800 dark:border-brand-500/20 dark:bg-brand-500/10 dark:text-brand-200">
                            Kamu bisa pakai <span class="font-semibold">split payment</span> untuk pelunasan satu invoice.
                            Aman untuk transaksi lama karena backend tetap support format lama sebagai fallback.
                        </div>

                        <input type="hidden" name="amount" :value="totalPaidAmount">
                        <input type="hidden" name="payment_method" :value="legacyPaymentMethod()">
                        <input type="hidden" name="payment_account_id" :value="legacyAccountId()">
                        <input type="hidden" name="cash_received" :value="legacyCashReceived()">

                        <div class="mb-4 rounded-xl border border-gray-200 p-4 dark:border-gray-700">
                            <div class="mb-3 flex items-center justify-between">
                                <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                                    Detail Pembayaran
                                </label>
                                <button type="button" @click="addPayment()"
                                    class="text-xs text-brand-600 hover:text-brand-700 dark:text-brand-400 font-medium flex items-center gap-1">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
                                    </svg>
                                    Split Payment
                                </button>
                            </div>

                            <div class="space-y-3">
                                <template x-for="(payment, index) in payments" :key="index">
                                    <div class="rounded-lg border border-gray-200 p-4 dark:border-gray-700">
                                        <div class="mb-3 flex items-center justify-between" x-show="payments.length > 1">
                                            <span class="text-xs font-medium text-gray-500 dark:text-gray-400" x-text="'Pembayaran ' + (index + 1)"></span>
                                            <button type="button" @click="removePayment(index)" class="text-gray-400 hover:text-error-500">
                                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                                                </svg>
                                            </button>
                                        </div>

                                        <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                                            <div>
                                                <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Metode</label>
                                                <select
                                                    :name="'payments[' + index + '][method]'"
                                                    x-model="payment.method"
                                                    @change="onMethodChange(index)"
                                                    class="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                                >
                                                    <option value="cash">Tunai</option>
                                                    <option value="transfer">Transfer Bank</option>
                                                    <option value="ewallet">E-Wallet</option>
                                                </select>
                                            </div>

                                            <div>
                                                <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Jumlah</label>
                                                <div class="relative">
                                                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-sm text-gray-500 dark:text-gray-400">Rp</span>
                                                    <input
                                                        type="number"
                                                        :name="'payments[' + index + '][amount]'"
                                                        x-model.number="payment.amount"
                                                        @input="updateTotal()"
                                                        min="0"
                                                        step="1"
                                                        class="h-11 w-full rounded-lg border border-gray-300 bg-transparent pl-10 pr-4 text-right text-base font-semibold text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                                    >
                                                </div>
                                            </div>
                                        </div>

                                        <div x-show="payment.method === 'transfer'" x-cloak class="mt-3">
                                            <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Rekening Bank</label>
                                            <select
                                                :name="'payments[' + index + '][account_id]'"
                                                x-model="payment.account_id"
                                                :disabled="payment.method !== 'transfer'"
                                                class="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                            >
                                                <option value="">Pilih Rekening Bank</option>
                                                @foreach($bankAccounts ?? [] as $account)
                                                    <option value="{{ $account->id }}">{{ $account->getFullLabel() }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div x-show="payment.method === 'ewallet'" x-cloak class="mt-3">
                                            <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Akun E-Wallet</label>
                                            <select
                                                :name="'payments[' + index + '][account_id]'"
                                                x-model="payment.account_id"
                                                :disabled="payment.method !== 'ewallet'"
                                                class="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                            >
                                                <option value="">Pilih Akun E-Wallet</option>
                                                @foreach($ewalletAccounts ?? [] as $account)
                                                    <option value="{{ $account->id }}">{{ $account->getFullLabel() }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>

                        <div class="mb-4 rounded-xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
                            <div class="flex items-center justify-between text-sm">
                                <span class="text-gray-500 dark:text-gray-400">Total Split Payment</span>
                                <span class="font-semibold text-gray-800 dark:text-white" x-text="'Rp ' + formatRupiah(totalPaidAmount)"></span>
                            </div>
                            <div class="mt-3 border-t border-dashed border-gray-300 pt-3 dark:border-gray-700">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm font-medium" :class="balanceClass()" x-text="balanceLabel()"></span>
                                    <span class="text-lg font-bold" :class="balanceClass()" x-text="'Rp ' + formatRupiah(Math.abs(balance))"></span>
                                </div>
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Total pembayaran tidak boleh melebihi sisa piutang.
                                </p>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">Bukti Pembayaran</label>
                            <input
                                type="file"
                                name="proof"
                                accept="image/jpeg,image/png,image/webp"
                                class="w-full rounded-lg border border-gray-300 px-4 py-2 text-sm file:mr-4 file:rounded-lg file:border-0 file:bg-brand-50 file:px-4 file:py-2 file:text-sm file:font-medium file:text-brand-700 hover:file:bg-brand-100 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                            >
                            <p class="mt-1 text-xs text-gray-500">JPG, PNG, atau WebP. Maks 2MB</p>
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">Catatan</label>
                            <textarea
                                name="notes"
                                rows="2"
                                class="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                placeholder="Catatan pembayaran (opsional)"
                            ></textarea>
                        </div>
                    </div>

                    <div class="border-t border-gray-200 bg-white px-6 py-4 dark:border-gray-700 dark:bg-gray-800">
                        <div class="flex gap-3">
                            <button type="button" onclick="closePaymentDialog()" class="flex-1 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600">
                                Batal
                            </button>
                            <button type="submit"
                                :disabled="!canSubmit()"
                                class="flex-1 rounded-lg bg-success-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-success-600 disabled:opacity-50 disabled:cursor-not-allowed">
                                Simpan Pembayaran
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- Payment History Dialog --}}
    <div id="historyDialog" class="fixed inset-0 z-50 hidden overflow-y-auto bg-black/50 p-4 backdrop-blur-sm">
        <div class="flex min-h-full items-start justify-center py-4">
            <div class="my-6 w-full max-w-sm rounded-xl bg-white shadow-xl dark:bg-gray-800">
                <div class="flex items-center justify-between border-b border-gray-200 px-4 py-3 dark:border-gray-700">
                    <div>
                        <h3 class="text-sm font-semibold text-gray-800 dark:text-white">Riwayat Pembayaran</h3>
                        <p class="text-xs text-gray-500 dark:text-gray-400" id="historyInvoice"></p>
                    </div>
                    <button type="button" onclick="closeHistoryDialog()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>
                <div class="max-h-[65vh] overflow-y-auto p-4">
                    <div id="historyContent" class="space-y-2"></div>
                </div>
            </div>
        </div>
    </div>

    {{-- Batch Payment Dialog --}}
    <div id="batchPaymentDialog" class="fixed inset-0 z-50 hidden overflow-y-auto bg-black/50 p-4 backdrop-blur-sm">
        <div class="flex min-h-full items-start justify-center py-4">
            <div class="my-6 flex w-full max-w-2xl flex-col overflow-hidden rounded-2xl bg-white shadow-xl dark:bg-gray-800">
                <div class="flex items-center justify-between border-b border-gray-200 px-5 py-4 dark:border-gray-700">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-800 dark:text-white">Pembayaran Batch</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400" id="batchOrderCount"></p>
                    </div>
                    <button type="button" onclick="closeBatchDialog()" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300">
                        <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                        </svg>
                    </button>
                </div>

                <form id="batchPaymentForm" method="POST" action="{{ route('kasir.pelunasan.payBatch') }}" enctype="multipart/form-data" class="flex min-h-0 flex-1 flex-col" x-data="batchSplitPaymentForm()">
                    @csrf
                    <input type="hidden" name="order_ids" id="batchOrderIds">

                    <div class="min-h-0 flex-1 overflow-y-auto p-4">
                        <div class="mb-4 rounded-xl border border-gray-200 p-4 dark:border-gray-700">
                            <div id="batchOrderList" class="space-y-2"></div>

                            <div class="mt-3 rounded-lg bg-gray-100 p-3 dark:bg-gray-700">
                                <div class="flex justify-between items-center">
                                    <span class="text-sm font-medium text-gray-600 dark:text-gray-400">Total Sisa Piutang</span>
                                    <span class="text-lg font-bold text-error-600 dark:text-error-400" id="batchTotalRemaining"></span>
                                </div>
                            </div>
                        </div>

                        <div class="mb-4 rounded-xl border border-brand-200 bg-brand-50 px-4 py-3 text-xs text-brand-800 dark:border-brand-500/20 dark:bg-brand-500/10 dark:text-brand-200">
                            Kamu bisa pakai <span class="font-semibold">Split Payment</span> untuk gabungan tunai, transfer, dan e-wallet dalam satu transaksi batch.
                            Total semua split payment akan dibagikan ke order terpilih secara berurutan.
                        </div>

                        <div>
                            <div class="mb-2 flex items-center justify-between">
                                <label class="text-sm font-medium text-gray-700 dark:text-gray-300">
                                    Detail Pembayaran
                                </label>
                                <button type="button" @click="addPayment()"
                                    class="text-xs text-brand-600 hover:text-brand-700 dark:text-brand-400 font-medium flex items-center gap-1">
                                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"/>
                                    </svg>
                                    Split Payment
                                </button>
                            </div>

                            <div class="space-y-3">
                                <template x-for="(payment, index) in payments" :key="index">
                                    <div class="rounded-lg border border-gray-200 p-4 dark:border-gray-700">
                                        <div class="mb-3 flex items-center justify-between" x-show="payments.length > 1">
                                            <span class="text-xs font-medium text-gray-500 dark:text-gray-400" x-text="'Pembayaran ' + (index + 1)"></span>
                                            <button type="button" @click="removePayment(index)" class="text-gray-400 hover:text-error-500">
                                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                                                </svg>
                                            </button>
                                        </div>

                                        <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                                            <div>
                                                <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Metode</label>
                                                <select
                                                    :name="'payments[' + index + '][method]'"
                                                    x-model="payment.method"
                                                    @change="onMethodChange(index)"
                                                    class="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                                >
                                                    <option value="cash">Tunai</option>
                                                    <option value="transfer">Transfer Bank</option>
                                                    <option value="ewallet">E-Wallet</option>
                                                </select>
                                            </div>

                                            <div>
                                                <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Jumlah</label>
                                                <div class="relative">
                                                    <span class="absolute left-4 top-1/2 -translate-y-1/2 text-sm text-gray-500 dark:text-gray-400">Rp</span>
                                                    <input
                                                        type="number"
                                                        :name="'payments[' + index + '][amount]'"
                                                        x-model.number="payment.amount"
                                                        @input="updateTotal()"
                                                        min="0"
                                                        step="1"
                                                        class="h-11 w-full rounded-lg border border-gray-300 bg-transparent pl-10 pr-4 text-right text-base font-semibold text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                                    >
                                                </div>
                                            </div>
                                        </div>

                                        <div x-show="payment.method === 'transfer'" x-cloak class="mt-3">
                                            <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Rekening Bank</label>
                                            <select
                                                :name="'payments[' + index + '][account_id]'"
                                                x-model="payment.account_id"
                                                :disabled="payment.method !== 'transfer'"
                                                class="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                            >
                                                <option value="">Pilih Rekening Bank</option>
                                                @foreach($bankAccounts ?? [] as $account)
                                                    <option value="{{ $account->id }}">{{ $account->getFullLabel() }}</option>
                                                @endforeach
                                            </select>
                                        </div>

                                        <div x-show="payment.method === 'ewallet'" x-cloak class="mt-3">
                                            <label class="mb-1.5 block text-xs font-medium text-gray-600 dark:text-gray-500">Akun E-Wallet</label>
                                            <select
                                                :name="'payments[' + index + '][account_id]'"
                                                x-model="payment.account_id"
                                                :disabled="payment.method !== 'ewallet'"
                                                class="h-11 w-full rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 focus:border-brand-300 focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"
                                            >
                                                <option value="">Pilih Akun E-Wallet</option>
                                                @foreach($ewalletAccounts ?? [] as $account)
                                                    <option value="{{ $account->id }}">{{ $account->getFullLabel() }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>

                        <div class="mt-4 rounded-xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-900/40">
                            <div class="flex items-center justify-between text-sm">
                                <span class="text-gray-500 dark:text-gray-400">Total Split Payment</span>
                                <span class="font-semibold text-gray-800 dark:text-white" x-text="'Rp ' + formatRupiah(totalPaidAmount)"></span>
                            </div>
                            <div class="mt-3 border-t border-dashed border-gray-300 pt-3 dark:border-gray-700">
                                <div class="flex items-center justify-between">
                                    <span class="text-sm font-medium" :class="balanceClass()" x-text="balanceLabel()"></span>
                                    <span class="text-lg font-bold" :class="balanceClass()" x-text="'Rp ' + formatRupiah(Math.abs(balance))"></span>
                                </div>
                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    Kalau total pembayaran lebih besar dari total sisa piutang, selisih dianggap kembalian.
                                </p>
                            </div>
                        </div>

                        <div class="mt-4 mb-4">
                            <label class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">Bukti Pembayaran</label>
                            <input
                                type="file"
                                name="proof"
                                accept="image/jpeg,image/png,image/webp"
                                class="w-full rounded-lg border border-gray-300 px-4 py-2 text-sm file:mr-4 file:rounded-lg file:border-0 file:bg-brand-50 file:px-4 file:py-2 file:text-sm file:font-medium file:text-brand-700 hover:file:bg-brand-100 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                            >
                        </div>

                        <div>
                            <label class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">Catatan</label>
                            <textarea
                                name="notes"
                                rows="2"
                                class="w-full rounded-lg border border-gray-300 px-4 py-2.5 text-sm focus:border-brand-500 focus:ring-brand-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white"
                                placeholder="Catatan pembayaran batch (opsional)"
                            ></textarea>
                        </div>
                    </div>

                    <div class="border-t border-gray-200 bg-white px-4 py-4 dark:border-gray-700 dark:bg-gray-800">
                        <div class="flex gap-3">
                            <button type="button" onclick="closeBatchDialog()" class="flex-1 rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 dark:hover:bg-gray-600">
                                Batal
                            </button>
                            <button type="submit"
                                :disabled="!canSubmit()"
                                class="flex-1 rounded-lg bg-success-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-success-600 disabled:opacity-50 disabled:cursor-not-allowed">
                                Simpan Pembayaran
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    function filterByCustomer(customer) {
        const url = new URL(window.location.href);
        if (customer) {
            url.searchParams.set('customer', customer);
        } else {
            url.searchParams.delete('customer');
        }
        window.location.href = url.toString();
    }

    function formatRupiah(num) {
        return Math.floor(Number(num || 0)).toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    }

    function formatRupiahLabel(num) {
        return 'Rp ' + formatRupiah(num);
    }

    function singleSplitPaymentForm() {
        return {
            totalRemaining: 0,
            payments: [
                { method: 'cash', amount: 0, account_id: '' }
            ],
            totalPaidAmount: 0,
            balance: 0,

            init() {
                this.updateTotal();
            },

            addPayment() {
                this.payments.push({ method: 'cash', amount: 0, account_id: '' });
                this.updateTotal();
            },

            removePayment(index) {
                if (this.payments.length > 1) {
                    this.payments.splice(index, 1);
                    this.updateTotal();
                }
            },

            onMethodChange(index) {
                if (this.payments[index].method !== 'transfer' && this.payments[index].method !== 'ewallet') {
                    this.payments[index].account_id = '';
                }
                this.updateTotal();
            },

            updateTotal() {
                this.totalPaidAmount = this.payments.reduce((sum, item) => {
                    return sum + (parseFloat(item.amount) || 0);
                }, 0);

                this.balance = this.totalPaidAmount - this.totalRemaining;
            },

            formatRupiah(num) {
                return Math.floor(Number(num || 0)).toLocaleString('id-ID');
            },

            balanceLabel() {
                return this.balance >= 0 ? 'Lebih Bayar' : 'Kurang';
            },

            balanceClass() {
                return this.balance >= 0
                    ? 'text-success-600 dark:text-success-400'
                    : 'text-error-600 dark:text-error-400';
            },

            legacyPaymentMethod() {
                const first = this.payments[0] || {};
                return first.method || 'cash';
            },

            legacyAccountId() {
                const first = this.payments[0] || {};
                return first.account_id || '';
            },

            legacyCashReceived() {
                const first = this.payments[0] || {};
                if ((first.method || 'cash') === 'cash') {
                    return parseFloat(first.amount) || 0;
                }
                return this.totalPaidAmount;
            },

            canSubmit() {
                if (this.totalPaidAmount <= 0) return false;
                if (this.totalPaidAmount > this.totalRemaining) return false;

                const validAmounts = this.payments.every(item => (parseFloat(item.amount) || 0) > 0);
                if (!validAmounts) return false;

                const validAccounts = this.payments.every(item => {
                    if (item.method === 'transfer' || item.method === 'ewallet') {
                        return !!item.account_id;
                    }
                    return true;
                });

                if (!validAccounts) return false;

                return true;
            },

            resetState() {
                this.totalRemaining = 0;
                this.payments = [{ method: 'cash', amount: 0, account_id: '' }];
                this.updateTotal();
            },

            fillForSingleOrder(remaining) {
                this.totalRemaining = parseFloat(remaining || 0);
                this.payments = [{ method: 'cash', amount: parseFloat(remaining || 0), account_id: '' }];
                this.updateTotal();
            }
        }
    }

    function openPaymentDialog(orderId, invoice, remaining) {
        document.getElementById('paymentForm').action = `/kasir/pelunasan/${orderId}/pay`;
        document.getElementById('paymentInvoice').textContent = invoice;
        document.getElementById('paymentRemaining').textContent = 'Rp ' + Number(remaining).toLocaleString('id-ID');

        document.getElementById('paymentDialog').classList.remove('hidden');

        requestAnimationFrame(() => {
            const alpineRoot = document.getElementById('paymentForm');
            if (alpineRoot && alpineRoot._x_dataStack && alpineRoot._x_dataStack[0]) {
                const state = alpineRoot._x_dataStack[0];
                state.fillForSingleOrder(remaining);
            }
        });
    }

    function closePaymentDialog() {
        document.getElementById('paymentDialog').classList.add('hidden');
        document.getElementById('paymentForm').reset();

        const alpineRoot = document.getElementById('paymentForm');
        if (alpineRoot && alpineRoot._x_dataStack && alpineRoot._x_dataStack[0]) {
            const state = alpineRoot._x_dataStack[0];
            state.resetState();
        }
    }

    function openHistoryDialog(payments, invoice) {
        document.getElementById('historyInvoice').textContent = invoice;

        let html = '';
        let total = 0;

        payments.forEach((p) => {
            const amount = parseFloat(p.amount) || 0;
            total += amount;

            const methodLabel = p.method === 'cash'
                ? 'Tunai'
                : (p.method === 'transfer' ? 'Transfer' : 'E-Wallet');

            const methodBadge = p.method === 'cash'
                ? 'bg-success-100 text-success-700 dark:bg-success-500/20 dark:text-success-400'
                : (p.method === 'transfer'
                    ? 'bg-brand-100 text-brand-700 dark:bg-brand-500/20 dark:text-brand-400'
                    : 'bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-400');

            html += `
                <div class="rounded-lg border border-gray-200 dark:border-gray-700 p-3">
                    <div class="flex items-center justify-between mb-1">
                        <span class="text-xs text-gray-500 dark:text-gray-400">${p.date}</span>
                        <span class="text-sm font-bold text-gray-800 dark:text-white">Rp ${formatRupiah(amount)}</span>
                    </div>
                    <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                        <span class="inline-flex rounded px-1.5 py-0.5 text-[10px] font-medium ${methodBadge}">${methodLabel}</span>
                        <span>• ${p.cashier}</span>
                        ${p.proof ? `<a href="${p.proof}" target="_blank" class="text-brand-600 hover:underline dark:text-brand-400">Lihat Bukti</a>` : ''}
                    </div>
                    ${p.notes ? `<p class="mt-1 text-xs italic text-gray-400">"${p.notes}"</p>` : ''}
                </div>
            `;
        });

        html += `
            <div class="rounded-lg bg-gray-100 dark:bg-gray-700 p-3 mt-2">
                <div class="flex justify-between items-center">
                    <span class="text-xs font-medium text-gray-600 dark:text-gray-400">Total (${payments.length}x)</span>
                    <span class="text-base font-bold text-success-600 dark:text-success-400">Rp ${formatRupiah(total)}</span>
                </div>
            </div>
        `;

        document.getElementById('historyContent').innerHTML = html;
        document.getElementById('historyDialog').classList.remove('hidden');
    }

    function closeHistoryDialog() {
        document.getElementById('historyDialog').classList.add('hidden');
    }

    function closeBatchDialog() {
        document.getElementById('batchPaymentDialog').classList.add('hidden');
        document.getElementById('batchPaymentForm').reset();

        const alpineRoot = document.getElementById('batchPaymentForm');
        if (alpineRoot && alpineRoot._x_dataStack && alpineRoot._x_dataStack[0]) {
            const state = alpineRoot._x_dataStack[0];
            state.totalRemaining = 0;
            state.payments = [{ method: 'cash', amount: 0, account_id: '' }];
            state.updateTotal();
        }
    }

    function batchSplitPaymentForm() {
        return {
            totalRemaining: 0,
            payments: [
                { method: 'cash', amount: 0, account_id: '' }
            ],
            totalPaidAmount: 0,
            balance: 0,

            init() {
                this.updateTotal();
            },

            addPayment() {
                this.payments.push({ method: 'cash', amount: 0, account_id: '' });
                this.updateTotal();
            },

            removePayment(index) {
                if (this.payments.length > 1) {
                    this.payments.splice(index, 1);
                    this.updateTotal();
                }
            },

            onMethodChange(index) {
                if (this.payments[index].method !== 'transfer' && this.payments[index].method !== 'ewallet') {
                    this.payments[index].account_id = '';
                }
                this.updateTotal();
            },

            updateTotal() {
                this.totalPaidAmount = this.payments.reduce((sum, item) => {
                    return sum + (parseFloat(item.amount) || 0);
                }, 0);

                this.balance = this.totalPaidAmount - this.totalRemaining;
            },

            formatRupiah(num) {
                return Math.floor(Number(num || 0)).toLocaleString('id-ID');
            },

            balanceLabel() {
                return this.balance >= 0 ? 'Kembalian' : 'Kurang';
            },

            balanceClass() {
                return this.balance >= 0
                    ? 'text-success-600 dark:text-success-400'
                    : 'text-error-600 dark:text-error-400';
            },

            canSubmit() {
                if (this.totalPaidAmount <= 0) return false;

                const validAmounts = this.payments.every(item => (parseFloat(item.amount) || 0) > 0);
                if (!validAmounts) return false;

                const validAccounts = this.payments.every(item => {
                    if (item.method === 'transfer' || item.method === 'ewallet') {
                        return !!item.account_id;
                    }
                    return true;
                });

                if (!validAccounts) return false;

                return true;
            }
        }
    }

    document.getElementById('paymentDialog').addEventListener('click', function(e) {
        if (e.target === this) closePaymentDialog();
    });

    document.getElementById('historyDialog').addEventListener('click', function(e) {
        if (e.target === this) closeHistoryDialog();
    });

    document.getElementById('batchPaymentDialog').addEventListener('click', function(e) {
        if (e.target === this) closeBatchDialog();
    });

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closePaymentDialog();
            closeHistoryDialog();
            closeBatchDialog();
        }
    });

    @php
        /*
         |--------------------------------------------------------------------------
         | Helper total/sisa untuk data batch payment
         |--------------------------------------------------------------------------
         | Dibuat lokal di sini supaya tidak bergantung pada helper di dalam loop tabel.
         | Ini mencegah error Undefined variable $__orderDisplayRemaining.
         */
        $__batchRoundOnlyAmount = function ($amount) {
            $amount = max((float) $amount, 0);
            $roundTo = 1000;

            if ($amount <= 0) {
                return 0;
            }

            return (float) (ceil($amount / $roundTo) * $roundTo);
        };

        $__batchMeterMinRoundAmount = function ($amount) use ($__batchRoundOnlyAmount) {
            $amount = max((float) $amount, 0);
            $minimumOrder = 10000;

            if ($amount <= 0) {
                return 0;
            }

            if ($amount < $minimumOrder) {
                $amount = $minimumOrder;
            }

            return $__batchRoundOnlyAmount($amount);
        };

        $__batchNormalizeUnit = function ($unit) {
            $unit = strtolower(trim((string) $unit));
            $unit = str_replace(['²', '�'], ['2', '2'], $unit);

            if (in_array($unit, ['m2', 'meter2', 'meter persegi', 'per meter persegi'], true)) {
                return 'm2';
            }

            if (in_array($unit, ['meter', 'm', 'per meter'], true)) {
                return 'meter';
            }

            return $unit ?: 'lembar';
        };

        $__batchParseM2FromDescription = function ($description) {
            $description = strtolower(trim((string) $description));

            if ($description === '') {
                return 0;
            }

            $description = str_replace(['²', '�', '*'], ['2', '2', 'x'], $description);

            if (preg_match('/([0-9]+(?:[\.,][0-9]+)?)\s*[x×]\s*([0-9]+(?:[\.,][0-9]+)?)/i', $description, $matches)) {
                $width = (float) str_replace(',', '.', $matches[1]);
                $height = (float) str_replace(',', '.', $matches[2]);

                if ($width > 0 && $height > 0) {
                    if ($width >= 10 || $height >= 10) {
                        $width = $width / 100;
                        $height = $height / 100;
                    }

                    return round($width * $height, 4);
                }
            }

            return 0;
        };

        $__batchItemDisplaySubtotal = function ($item) use ($__batchRoundOnlyAmount, $__batchMeterMinRoundAmount, $__batchNormalizeUnit, $__batchParseM2FromDescription) {
            $unit = $__batchNormalizeUnit($item->size_unit ?? $item->unit ?? 'lembar');
            $storedSubtotal = max((float) ($item->subtotal ?? $item->total_price ?? 0), 0);

            if ($storedSubtotal > 0) {
                return in_array($unit, ['m2', 'meter'], true)
                    ? $__batchMeterMinRoundAmount($storedSubtotal)
                    : $__batchRoundOnlyAmount($storedSubtotal);
            }

            $qty = max((float) ($item->qty ?? 1), 0);
            $basePrice = max((float) ($item->base_price ?? $item->calculated_price ?? $item->price ?? 0), 0);
            $sizeValue = max((float) ($item->size_value ?? 0), 0);

            if ($unit === 'm2') {
                if ($sizeValue <= 0) {
                    $sizeValue = $__batchParseM2FromDescription($item->size_description ?? $item->size ?? '');
                }

                if ($sizeValue <= 0) {
                    $sizeValue = 1;
                }

                return $__batchMeterMinRoundAmount($basePrice * $sizeValue * $qty);
            }

            if ($unit === 'meter') {
                $sizeValue = $sizeValue > 0 ? $sizeValue : 1;
                return $__batchMeterMinRoundAmount($basePrice * $sizeValue * $qty);
            }

            return $__batchRoundOnlyAmount($basePrice * $qty);
        };

        $__batchOrderDisplaySubtotalBeforePpn = function ($order) use ($__batchItemDisplaySubtotal, $__batchRoundOnlyAmount) {
            $items = $order->relationLoaded('items') ? $order->items : ($order->items ?? collect());

            if ($items && $items->count() > 0) {
                $activeItems = $items->filter(function ($item) {
                    if (method_exists($item, 'isCancelled')) {
                        return !$item->isCancelled();
                    }

                    return !(bool) ($item->is_cancelled ?? false);
                });

                return (float) $activeItems->sum(fn ($item) => $__batchItemDisplaySubtotal($item));
            }

            $subtotalBeforePpn = (float) ($order->subtotal_before_ppn ?? 0);
            if ($subtotalBeforePpn > 0) {
                return $__batchRoundOnlyAmount($subtotalBeforePpn);
            }

            $total = (float) ($order->total_price ?? 0);
            $ppn = (float) ($order->ppn_amount ?? 0);

            if ((bool) ($order->use_ppn ?? false) && $ppn > 0 && $total > $ppn) {
                return $__batchRoundOnlyAmount($total - $ppn);
            }

            return $__batchRoundOnlyAmount($total);
        };

        $__batchOrderDisplayTotal = function ($order) use ($__batchOrderDisplaySubtotalBeforePpn) {
            $subtotalBeforePpn = (float) $__batchOrderDisplaySubtotalBeforePpn($order);
            $ppn = (bool) ($order->use_ppn ?? false) ? (float) ($order->ppn_amount ?? 0) : 0;

            return $subtotalBeforePpn + $ppn;
        };

        $__batchOrderDisplayRemaining = function ($order) use ($__batchOrderDisplayTotal) {
            $paid = method_exists($order, 'getTotalPaid')
                ? (float) $order->getTotalPaid()
                : (float) ($order->paid_amount ?? 0);

            return max((float) $__batchOrderDisplayTotal($order) - $paid, 0);
        };

        $allOrdersJson = $orders->map(function($o) use ($__batchOrderDisplayRemaining) {
            return [
                'id' => $o->id,
                'invoice' => $o->invoice_number,
                'customer' => $o->customer_name,
                'remaining' => $__batchOrderDisplayRemaining($o)
            ];
        })->values();
    @endphp

    document.addEventListener('alpine:init', () => {
        Alpine.data('batchPayment', () => ({
            selectedOrders: [],
            selectAll: false,
            allOrders: @json($allOrdersJson),

            get totalSelected() {
                return this.selectedOrders.reduce((sum, o) => sum + o.remaining, 0);
            },

            isSelected(id) {
                return this.selectedOrders.some(o => o.id === id);
            },

            toggleOrder(id, invoice, remaining, customer) {
                const idx = this.selectedOrders.findIndex(o => o.id === id);
                if (idx > -1) {
                    this.selectedOrders.splice(idx, 1);
                } else {
                    this.selectedOrders.push({ id, invoice, remaining, customer });
                }
                this.updateSelectAll();
            },

            toggleSelectAll() {
                if (this.selectAll) {
                    this.selectedOrders = this.allOrders.map(o => ({ ...o }));
                } else {
                    this.selectedOrders = [];
                }
            },

            updateSelectAll() {
                this.selectAll = this.selectedOrders.length === this.allOrders.length;
            },

            selectByCustomer(customerName) {
                const customerOrders = this.allOrders.filter(o => o.customer === customerName);
                const allSelected = customerOrders.every(o => this.isSelected(o.id));

                if (allSelected) {
                    this.selectedOrders = this.selectedOrders.filter(o => o.customer !== customerName);
                } else {
                    customerOrders.forEach(o => {
                        if (!this.isSelected(o.id)) {
                            this.selectedOrders.push({ ...o });
                        }
                    });
                }

                this.updateSelectAll();
            },

            clearSelection() {
                this.selectedOrders = [];
                this.selectAll = false;
            },

            formatRupiah(num) {
                return formatRupiah(num);
            },

            openBatchDialog() {
                document.getElementById('batchOrderCount').textContent = this.selectedOrders.length + ' order dipilih';
                document.getElementById('batchOrderIds').value = JSON.stringify(this.selectedOrders.map(o => o.id));
                document.getElementById('batchTotalRemaining').textContent = 'Rp ' + this.formatRupiah(this.totalSelected);

                let html = '';
                this.selectedOrders.forEach(o => {
                    html += `
                        <div class="flex justify-between items-center py-2 px-3 rounded-lg bg-gray-50 dark:bg-gray-700/50">
                            <div>
                                <span class="text-xs font-medium text-brand-600 dark:text-brand-400">${o.invoice}</span>
                                <span class="text-xs text-gray-500 dark:text-gray-400 ml-2">${o.customer}</span>
                            </div>
                            <span class="text-sm font-semibold text-error-600 dark:text-error-400">Rp ${this.formatRupiah(o.remaining)}</span>
                        </div>
                    `;
                });
                document.getElementById('batchOrderList').innerHTML = html;

                document.getElementById('batchPaymentDialog').classList.remove('hidden');

                requestAnimationFrame(() => {
                    const alpineRoot = document.getElementById('batchPaymentForm');
                    if (alpineRoot && alpineRoot._x_dataStack && alpineRoot._x_dataStack[0]) {
                        const state = alpineRoot._x_dataStack[0];
                        state.totalRemaining = this.totalSelected;
                        state.payments = [{ method: 'cash', amount: this.totalSelected, account_id: '' }];
                        state.updateTotal();
                    }
                });
            },

            printSelected() {
                const orderIds = this.selectedOrders.map(o => o.id).join(',');
                const url = `{{ route('kasir.pelunasan.printBatch') }}?order_ids=${orderIds}`;
                window.open(url, '_blank');
            }
        }));
    });
</script>
@endpush