@extends('layouts.app')

@section('content')
    @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);
        };

        $normalizeUnit = function ($unit) {
            $unit = strtolower(trim((string) $unit));

            return match ($unit) {
                'm2', 'm�' => 'm2',
                'meter', 'm' => 'meter',
                'pcs', 'pc', 'piece', 'lembar' => 'lembar',
                default => $unit !== '' ? $unit : 'lembar',
            };
        };

        $formatQty = function ($value, $decimals = 2) {
            $formatted = number_format((float) $value, $decimals, ',', '.');
            $formatted = rtrim($formatted, '0');
            $formatted = rtrim($formatted, ',');

            return $formatted === '' ? '0' : $formatted;
        };

        $isItemCancelled = function ($item) {
            if (method_exists($item, 'isCancelled')) {
                return $item->isCancelled();
            }

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

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

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

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

            if (!preg_match('/^\s*(\d+(?:\.\d+)?)\s*x\s*(\d+(?:\.\d+)?)\s*$/', $description, $matches)) {
                return 1;
            }

            $a = (float) $matches[1];
            $b = (float) $matches[2];

            if ($a >= 10 || $b >= 10) {
                $a = $a / 100;
                $b = $b / 100;
            }

            return round($a * $b, 4);
        };

        $calculateItemSubtotal = function ($item) use ($__itemDisplaySubtotal) {
            return round($__itemDisplaySubtotal($item), 2);
        };
    @endphp

    <x-common.page-breadcrumb pageTitle="{{ $title ?? 'Riwayat Pembayaran' }}" />

    {{-- AI Guidance --}}
    <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: Riwayat Pembayaran
                    </span>
                </div>

                <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                    Halaman ini dipakai untuk melihat order yang sudah dibayar, membuka bukti transaksi, memperbaiki data pembayaran, melakukan refund,
                    atau mencetak beberapa nota sekaligus dengan sistem checklist.
                </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">Checklist Invoice</div>
                        <div>
                            Centang invoice yang ingin digabung. Bisa juga klik <span class="font-semibold">nama customer</span> untuk memilih semua invoice customer itu.
                        </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">Cetak Gabungan</div>
                        <div>
                            Setelah memilih beberapa invoice, klik <span class="font-semibold">Cetak Gabungan</span> untuk membuat satu nota print.
                        </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">Refund / Edit</div>
                        <div>
                            Tetap bisa digunakan untuk <span class="font-semibold">edit pembayaran</span> atau <span class="font-semibold">refund</span> seperti sebelumnya.
                        </div>
                    </div>
                </div>

                <div class="mt-3 inline-flex items-start gap-2 rounded-xl bg-warning-50 px-3 py-2 text-xs font-medium text-warning-800 ring-1 ring-warning-200 dark:bg-warning-500/10 dark:text-warning-200 dark:ring-warning-900/30">
                    <svg class="mt-0.5 size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M12 8v4m0 4h.01M4.93 19h14.14c1.54 0 2.5-1.67 1.73-2.5L13.73 4c-.77-.83-1.96-.83-2.73 0L3.2 16.5c-.77.83.19 2.5 1.73 2.5z"/>
                    </svg>
                    <div>
                        <span class="font-semibold">Perhatian:</span> Cetak gabungan hanya menggabungkan invoice yang sedang dicentang.
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
        <x-posgraf.stat-card
            title="Pendapatan Hari Ini"
            value="Rp {{ number_format($todayRevenue ?? 0, 0, ',', '.') }}"
            color="success"
            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="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" /></svg>'
        />
    </div>

    @php
        $allOrdersJson = $orders->map(function ($order) use ($calculateItemSubtotal, $isItemCancelled) {
            $orderItems = method_exists($order, 'items')
                ? ($order->relationLoaded('items') ? $order->items : $order->items()->get())
                : collect();

            $activeItems = $orderItems->filter(fn ($item) => !$isItemCancelled($item))->values();

            $displayTotal = $activeItems->isNotEmpty()
                ? $activeItems->sum(fn ($item) => $calculateItemSubtotal($item))
                : (float) $__orderDisplayTotal($order);

            return [
                'id' => $order->id,
                'invoice' => $order->invoice_number,
                'customer' => $order->customer_name,
                'total' => (float) $displayTotal,
            ];
        })->values();
    @endphp

    <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]" x-data="paymentHistoryBatch()">
        <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
            <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Riwayat Pembayaran</h3>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Daftar order yang sudah pernah dibayar. Gunakan checklist untuk cetak nota gabungan.
                    </p>
                </div>

                <a href="{{ route('kasir.index') }}"
                   class="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600">
                    <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
                    </svg>
                    Tagihan Pending
                </a>
            </div>
        </div>

        <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
            <form method="GET" class="flex flex-wrap items-end gap-4">
                <div class="flex-1">
                    <x-form.input
                        name="search"
                        label="Cari"
                        placeholder="Invoice atau nama pelanggan..."
                        :value="request('search')"
                    />
                </div>
                <div class="w-full sm:w-auto">
                    <x-form.date-picker
                        name="date"
                        label="Tanggal"
                        placeholder="Pilih tanggal"
                        :defaultDate="request('date')"
                    />
                </div>
                <button type="submit" class="h-11 rounded-lg bg-gray-100 px-4 text-sm font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                    Filter
                </button>
            </form>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full">
                <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-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Invoice</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Pelanggan</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Total</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Kasir</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Waktu Bayar</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Aksi</th>
                    </tr>
                </thead>

                <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                    @forelse($orders as $order)
                        @php
                            $orderItems = method_exists($order, 'items')
                                ? ($order->relationLoaded('items') ? $order->items : $order->items()->get())
                                : collect();

                            $activeItems = $orderItems->filter(fn ($item) => !$isItemCancelled($item))->values();
                            $summaryItem = $activeItems->first() ?? $orderItems->first();

                            $summaryFileName = $summaryItem->file_name ?? $order->file_name ?? '-';
                            $summaryQty = $summaryItem->qty ?? $order->qty ?? null;
                            $summaryUnit = $normalizeUnit($summaryItem->size_unit ?? ($order->size_unit ?? ''));
                            $summarySizeDescription = $summaryItem->size_description ?? $order->size ?? null;
                            $summarySizeValue = $summaryItem->size_value ?? $order->size_value ?? null;

                            $displayTotal = $activeItems->isNotEmpty()
                                ? $activeItems->sum(fn ($item) => $calculateItemSubtotal($item))
                                : (float) $__orderDisplayTotal($order);

                            $hasM2Item = $activeItems->contains(function ($item) use ($normalizeUnit) {
                                return $normalizeUnit($item->size_unit ?? '') === 'm2';
                            });

                            $summaryText = '-';
                            if ($summaryItem) {
                                $unitLabel = $summaryUnit === 'm2' ? 'm2' : $summaryUnit;
                                $summaryText = trim($summaryFileName);

                                if (!empty($summarySizeDescription)) {
                                    $summaryText .= ' - ' . $summarySizeDescription;
                                }

                                if (!is_null($summaryQty) && $summaryQty !== '') {
                                    $summaryText .= ' - ' . $formatQty($summaryQty) . ' ' . $unitLabel;
                                }

                                if (($summaryUnit === 'm2' || $summaryUnit === 'meter') && !empty($summarySizeValue)) {
                                    $summaryText .= ' - nilai ' . $formatQty($summarySizeValue);
                                }
                            }

                            $paymentsJson = optional($order->payments)->map(function ($p) {
                                return [
                                    'id' => $p->id,
                                    'date' => optional($p->created_at)->format('d/m/Y H:i'),
                                    'amount' => (float) ($p->amount ?? 0),
                                    'method' => (string) ($p->payment_method ?? ''),
                                    'notes' => (string) ($p->notes ?? ''),
                                    'proof' => $p->proof_path ? asset('storage/' . $p->proof_path) : null,
                                    'cashier' => (string) ($p->cashier->name ?? '-'),
                                ];
                            })->values()->toJson();
                        @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-4 text-center">
                                <input type="checkbox"
                                    :checked="isSelected({{ $order->id }})"
                                    @change="toggleOrder({{ $order->id }}, @js($order->invoice_number), {{ (float) $displayTotal }}, @js($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-5 py-4 text-sm font-medium text-gray-800 dark:text-white/90">
                                <a href="{{ route('orders.show', $order) }}" class="text-brand-600 hover:text-brand-700 hover:underline">
                                    {{ $order->invoice_number }}
                                </a>
                            </td>

                            <td class="px-5 py-4 text-sm text-gray-800 dark:text-white/90">
                                <button type="button"
                                    @click="selectByCustomer(@js($order->customer_name))"
                                    class="text-left hover:text-brand-600 hover:underline dark:hover:text-brand-400">
                                    {{ $order->customer_name }}
                                </button>
                                <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    {{ $summaryText }}
                                </div>
                            </td>

                            <td class="px-5 py-4 text-sm">
                                <div class="font-bold text-gray-800 dark:text-white/90">
                                    Rp {{ number_format($displayTotal, 0, ',', '.') }}
                                </div>

                                @if($hasM2Item)
                                    <div class="mt-1 text-[11px] text-brand-600 dark:text-brand-400">
                                        Total dihitung dari ukuran x harga/m2
                                    </div>
                                @endif
                            </td>

                            <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">
                                {{ $order->cashier->name ?? '-' }}
                            </td>

                            <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">
                                {{ $order->paid_at?->format('d M Y H:i') ?? '-' }}
                            </td>

                            <td class="px-5 py-4">
                                <div class="flex min-w-max flex-nowrap items-center justify-end gap-1.5 whitespace-nowrap">
                                    <button
                                        type="button"
                                        class="inline-flex h-8 items-center justify-center rounded-md bg-warning-500 px-2.5 text-[11px] font-semibold text-white shadow-sm transition hover:bg-warning-600 focus:outline-none focus:ring-2 focus:ring-warning-300"
                                        onclick="openPaymentManager({{ $paymentsJson }}, @js($order->invoice_number), @js($order->customer_name))"
                                        title="Kelola pembayaran"
                                    >
                                        Kelola
                                    </button>

                                    @if(\Illuminate\Support\Facades\Route::has('orders.invoice-print'))
                                        <a href="{{ route('orders.invoice-print', ['order' => $order, 'paper' => 'a4']) }}"
                                           target="_blank"
                                           style="display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 10px;border-radius:6px;background:#dc2626 !important;color:#ffffff !important;font-size:11px;font-weight:700;line-height:1;box-shadow:0 1px 2px rgba(0,0,0,.08);white-space:nowrap;text-decoration:none;"
                                           title="Cetak invoice A4">
                                            Cetak A4
                                        </a>

                                        <a href="{{ route('orders.invoice-print', ['order' => $order, 'paper' => 'a5']) }}"
                                           target="_blank"
                                           style="display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 10px;border-radius:6px;background:#dc2626 !important;color:#ffffff !important;font-size:11px;font-weight:700;line-height:1;box-shadow:0 1px 2px rgba(0,0,0,.08);white-space:nowrap;text-decoration:none;"
                                           title="Cetak invoice A5">
                                            Cetak A5
                                        </a>

                                        <a href="{{ route('orders.invoice-print', ['order' => $order, 'paper' => '215x165']) }}"
                                           target="_blank"
                                           style="display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 10px;border-radius:6px;background:#dc2626 !important;color:#ffffff !important;font-size:11px;font-weight:700;line-height:1;box-shadow:0 1px 2px rgba(0,0,0,.08);white-space:nowrap;text-decoration:none;"
                                           title="Cetak invoice 21,5 × 16,5">
                                            21,5×16,5
                                        </a>
                                    @endif

                                    @if(\Illuminate\Support\Facades\Route::has('kasir.receipt'))
                                        <a href="{{ route('kasir.receipt', $order) }}"
                                           target="_blank"
                                           style="display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 10px;border-radius:6px;background:#dc2626 !important;color:#ffffff !important;font-size:11px;font-weight:700;line-height:1;box-shadow:0 1px 2px rgba(0,0,0,.08);white-space:nowrap;text-decoration:none;"
                                           title="Cetak nota POS 80">
                                            POS 80
                                        </a>
                                    @elseif(\Illuminate\Support\Facades\Route::has('print.nota'))
                                        <a href="{{ route('print.nota', $order) }}"
                                           target="_blank"
                                           style="display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 10px;border-radius:6px;background:#dc2626 !important;color:#ffffff !important;font-size:11px;font-weight:700;line-height:1;box-shadow:0 1px 2px rgba(0,0,0,.08);white-space:nowrap;text-decoration:none;"
                                           title="Cetak nota POS 80">
                                            POS 80
                                        </a>
                                    @endif
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="7" class="px-5 py-8 text-center text-sm text-gray-500 dark:text-gray-400">Tidak ada data</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

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

        <template x-if="selectedOrders.length > 0">
            <div class="fixed bottom-6 left-1/2 z-40 -translate-x-1/2">
                <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> invoice 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">
                        <button type="button" @click="printSelected()"
                            class="flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600 transition-colors">
                            <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>

                        <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>
    </div>

    {{-- MODAL: PAYMENT MANAGER --}}
    <div id="paymentManagerModal" class="fixed inset-0 hidden justify-center overflow-y-auto bg-black/60 p-4 backdrop-blur-sm" style="z-index:2147483000; display:none; align-items:flex-start;">
        <div class="relative mt-6 w-full max-w-2xl rounded-2xl bg-white shadow-2xl ring-1 ring-black/10 dark:bg-gray-800 dark:ring-white/10">
            <div class="flex items-start justify-between gap-3 border-b border-gray-200 px-5 py-4 dark:border-gray-700">
                <div>
                    <h3 class="text-base font-semibold text-gray-800 dark:text-white">Kelola Pembayaran</h3>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                        Invoice: <span class="font-semibold" id="pmInvoice">-</span> •
                        Customer: <span class="font-semibold" id="pmCustomer">-</span>
                    </p>
                </div>
                <button type="button" onclick="closePaymentManager()" 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>

            <div class="p-5">
                <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">
                    <div class="mb-1 font-semibold">Cara pakai menu ini</div>
                    <ul class="space-y-1">
                        <li>• <span class="font-semibold">Edit</span> = memperbaiki nominal, metode, atau catatan pembayaran.</li>
                        <li>• <span class="font-semibold">Refund</span> = menghapus pembayaran dari order.</li>
                        <li>• Setelah refund, order bisa pindah kembali ke <span class="font-semibold">Tagihan Pending</span> kalau belum lunas.</li>
                    </ul>
                </div>

                <div class="mb-3 rounded-lg border border-warning-200 bg-warning-50 px-4 py-3 text-xs text-warning-800 dark:border-warning-500/20 dark:bg-warning-500/10 dark:text-warning-200">
                    <b>Catatan:</b> Refund akan <b>menghapus</b> pembayaran. Pastikan kasir sudah cek invoice dan nominal sebelum lanjut.
                </div>

                <div id="pmList" class="space-y-3"></div>

                <div id="pmEmpty" class="hidden py-10 text-center text-sm text-gray-500 dark:text-gray-400">
                    Tidak ada data pembayaran pada order ini.
                </div>

                <div class="mt-5 flex justify-end gap-2">
                    <button type="button" onclick="closePaymentManager()"
                            class="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700">
                        Tutup
                    </button>
                </div>
            </div>
        </div>
    </div>

    {{-- MODAL: EDIT PAYMENT --}}
    <div id="paymentEditModal" class="fixed inset-0 hidden justify-center overflow-y-auto bg-black/70 p-4 backdrop-blur-sm" style="z-index:2147483100; display:none; align-items:flex-start;">
        <div class="relative mt-6 w-full max-w-md rounded-2xl bg-white shadow-2xl ring-1 ring-black/10 dark:bg-gray-800 dark:ring-white/10">
            <div class="flex items-start justify-between gap-3 border-b border-gray-200 px-5 py-4 dark:border-gray-700">
                <div>
                    <h3 class="text-base font-semibold text-gray-800 dark:text-white">Edit Pembayaran</h3>
                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400" id="peMeta">-</p>
                </div>
                <button type="button" onclick="closePaymentEdit()" 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="paymentUpdateForm" method="POST" enctype="multipart/form-data" class="p-5 space-y-4">
                @csrf
                @method('PUT')

                <div class="rounded-xl border border-gray-200 bg-gray-50 px-4 py-3 text-xs text-gray-600 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-300">
                    Gunakan form ini hanya untuk memperbaiki data pembayaran yang sudah tercatat. Kalau transaksi sebenarnya dibatalkan, gunakan <span class="font-semibold">Refund</span>, bukan edit.
                </div>

                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-200">Jumlah</label>
                    <input type="number" name="amount" id="peAmount" min="1"
                           class="h-10 w-full rounded-lg border border-gray-300 bg-transparent px-3 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200/40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90">
                </div>

                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-200">Metode</label>
                    <select name="payment_method" id="peMethod"
                            class="h-10 w-full rounded-lg border border-gray-300 bg-transparent px-3 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200/40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90">
                        <option value="cash">Cash</option>
                        <option value="transfer">Transfer</option>
                        <option value="ewallet">E-Wallet</option>
                    </select>
                    <p class="mt-1 text-[11px] text-gray-500 dark:text-gray-400">
                        Pilih sesuai pembayaran asli yang diterima dari customer.
                    </p>
                </div>

                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-200">Catatan</label>
                    <textarea name="notes" id="peNotes" rows="3"
                              class="w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200/40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90"></textarea>
                </div>

                <div>
                    <label class="mb-1 block text-sm font-medium text-gray-700 dark:text-gray-200">Bukti (opsional)</label>
                    <input type="file" name="proof" accept="image/*"
                           class="block w-full text-sm text-gray-500 file:mr-3 file:rounded-lg file:border-0 file:bg-brand-50 file:px-3 file:py-2 file:text-xs file:font-medium file:text-brand-700 hover:file:bg-brand-100 dark:text-gray-300 dark:file:bg-brand-500/20 dark:file:text-brand-300">
                </div>

                <div class="flex justify-end gap-2 pt-2">
                    <button type="button" onclick="closePaymentEdit()"
                            class="rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:bg-gray-700">
                        Batal
                    </button>
                    <button type="submit"
                            class="rounded-lg bg-brand-500 px-4 py-2 text-sm font-semibold text-white hover:bg-brand-600">
                        Simpan Perubahan
                    </button>
                </div>
            </form>

            <form id="paymentDeleteForm" method="POST" class="hidden">
                @csrf
                @method('DELETE')
            </form>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    function rupiah(num) {
        const n = Math.floor(Number(num || 0));
        return 'Rp ' + n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    }

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

    function methodLabel(method) {
        if (method === 'cash') return 'Tunai';
        if (method === 'transfer') return 'Transfer';
        if (method === 'ewallet') return 'E-Wallet';
        return method || '-';
    }

    function badgeClass(method) {
        if (method === 'cash') return 'bg-success-100 text-success-700 dark:bg-success-500/20 dark:text-success-300';
        if (method === 'transfer') return 'bg-brand-100 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300';
        return 'bg-purple-100 text-purple-700 dark:bg-purple-500/20 dark:text-purple-300';
    }


    function bringPaymentModalToFront(modal) {
        if (!modal) return;

        // Pindahkan modal ke body saat dibuka agar tidak ketutup wrapper/table/overflow.
        if (modal.parentElement !== document.body) {
            document.body.appendChild(modal);
        }

        modal.classList.remove('hidden');
        modal.classList.add('flex');

        modal.style.setProperty('display', 'flex', 'important');
        modal.style.setProperty('position', 'fixed', 'important');
        modal.style.setProperty('inset', '0', 'important');
        modal.style.setProperty('align-items', 'flex-start', 'important');
        modal.style.setProperty('justify-content', 'center', 'important');
        modal.style.setProperty('visibility', 'visible', 'important');
        modal.style.setProperty('opacity', '1', 'important');
        modal.style.setProperty('z-index', modal.id === 'paymentEditModal' ? '2147483100' : '2147483000', 'important');

        modal.scrollTop = 0;
        document.documentElement.classList.add('overflow-hidden');
        document.body.classList.add('overflow-hidden');
    }

    function hidePaymentModalFront(modal) {
        if (!modal) return;

        modal.classList.add('hidden');
        modal.classList.remove('flex');
        modal.style.setProperty('display', 'none', 'important');

        const managerModal = document.getElementById('paymentManagerModal');
        const editModal = document.getElementById('paymentEditModal');

        const managerOpen = managerModal && !managerModal.classList.contains('hidden');
        const editOpen = editModal && !editModal.classList.contains('hidden');

        if (!managerOpen && !editOpen) {
            document.documentElement.classList.remove('overflow-hidden');
            document.body.classList.remove('overflow-hidden');
        }
    }

    function openPaymentManager(payments, invoice, customer) {
        const modal = document.getElementById('paymentManagerModal');
        const list = document.getElementById('pmList');
        const empty = document.getElementById('pmEmpty');
        const pmInvoice = document.getElementById('pmInvoice');
        const pmCustomer = document.getElementById('pmCustomer');

        if (!modal || !list || !empty || !pmInvoice || !pmCustomer) {
            alert('Popup Kelola Pembayaran belum terbaca. Coba clear cache view lalu refresh.');
            return;
        }

        pmInvoice.textContent = invoice || '-';
        pmCustomer.textContent = customer || '-';

        list.innerHTML = '';

        if (!payments || payments.length === 0) {
            empty.classList.remove('hidden');
        } else {
            empty.classList.add('hidden');

            const total = payments.reduce((s, p) => s + (Number(p.amount) || 0), 0);

            payments.forEach((p, idx) => {
                const proofLink = p.proof
                    ? `<a href="${p.proof}" target="_blank" class="text-brand-600 hover:underline dark:text-brand-300">Lihat Bukti</a>`
                    : `<span class="text-gray-400">Tidak ada bukti</span>`;

                list.innerHTML += `
                    <div class="rounded-xl border border-gray-200 p-4 dark:border-gray-700">
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0">
                                <div class="flex flex-wrap items-center gap-2">
                                    <span class="inline-flex h-6 w-6 items-center justify-center rounded-full bg-gray-100 text-xs font-bold text-gray-700 dark:bg-gray-700 dark:text-gray-200">${idx + 1}</span>
                                    <span class="text-sm font-semibold text-gray-800 dark:text-white">${rupiah(p.amount)}</span>
                                    <span class="inline-flex rounded px-2 py-0.5 text-[10px] font-semibold ${badgeClass(p.method)}">${methodLabel(p.method)}</span>
                                </div>
                                <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                    ${p.date || '-'} • Kasir: <b>${p.cashier || '-'}</b>
                                </div>
                                ${p.notes ? `<div class="mt-2 text-xs text-gray-500 dark:text-gray-300 italic">"${p.notes}"</div>` : ''}
                                <div class="mt-2 text-xs">${proofLink}</div>
                            </div>

                            <div class="flex shrink-0 flex-col gap-2">
                                <button type="button"
                                    class="inline-flex items-center justify-center rounded-lg bg-warning-500 px-3 py-2 text-xs font-semibold text-white hover:bg-warning-600"
                                    onclick='openPaymentEdit(${JSON.stringify(p).replace(/'/g, "&apos;")})'>
                                    Edit
                                </button>
                                <button type="button"
                                    class="inline-flex items-center justify-center rounded-lg bg-error-500 px-3 py-2 text-xs font-semibold text-white hover:bg-error-600"
                                    onclick="refundPayment(${p.id})">
                                    Refund
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });

            list.innerHTML += `
                <div class="rounded-xl bg-gray-50 p-4 text-sm dark:bg-gray-900">
                    <div class="flex items-center justify-between">
                        <span class="text-xs font-semibold text-gray-600 dark:text-gray-300">Total pembayaran (${payments.length}x)</span>
                        <span class="text-sm font-bold text-success-600 dark:text-success-300">${rupiah(total)}</span>
                    </div>
                </div>
            `;
        }

        bringPaymentModalToFront(modal);
    }

    function closePaymentManager() {
        const modal = document.getElementById('paymentManagerModal');
        hidePaymentModalFront(modal);
    }

    function openPaymentEdit(payment) {
        closePaymentManager();

        const modal = document.getElementById('paymentEditModal');
        const form = document.getElementById('paymentUpdateForm');

        document.getElementById('peMeta').textContent = `ID #${payment.id} • ${payment.date || '-'}`;
        document.getElementById('peAmount').value = payment.amount || 0;
        document.getElementById('peMethod').value = payment.method || 'cash';
        document.getElementById('peNotes').value = payment.notes || '';

        form.action = `{{ url('/kasir/pembayaran') }}/${payment.id}/update`;

        bringPaymentModalToFront(modal);
    }

    function closePaymentEdit() {
        const modal = document.getElementById('paymentEditModal');
        hidePaymentModalFront(modal);
    }

    function refundPayment(paymentId) {
        const ok = confirm(
            'Refund akan menghapus pembayaran ini.\n\nJika setelah refund order belum lunas, order akan kembali ke daftar Tagihan Pending.\n\nLanjutkan?'
        );

        if (!ok) return;

        const form = document.getElementById('paymentDeleteForm');
        form.action = `{{ url('/kasir/pembayaran') }}/${paymentId}`;
        form.submit();
    }

    document.addEventListener('DOMContentLoaded', function () {
        document.getElementById('paymentManagerModal')?.addEventListener('click', function(e) {
            if (e.target === this) closePaymentManager();
        });

        document.getElementById('paymentEditModal')?.addEventListener('click', function(e) {
            if (e.target === this) closePaymentEdit();
        });
    });

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closePaymentManager();
            closePaymentEdit();
        }
    });

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

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

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

            toggleOrder(id, invoice, total, customer) {
                const idx = this.selectedOrders.findIndex(o => o.id === id);

                if (idx > -1) {
                    this.selectedOrders.splice(idx, 1);
                } else {
                    this.selectedOrders.push({ id, invoice, total, 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);
            },

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