@extends('layouts.app')

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

    @php
        $selectedCustomer = request('customer');
        $hasCustomerSelected = filled($selectedCustomer);

        /*
         |--------------------------------------------------------------------------
         | Helper sinkron total piutang
         |--------------------------------------------------------------------------
         | Disamakan dengan aturan order:
         | - Minimal per item Rp 10.000
         | - Pembulatan ke atas Rp 1.000
         | - PPN tetap dipisah dari subtotal dasar
         */
        $__piutangRoundOnlyAmount = function ($amount) {
            $amount = max((float) $amount, 0);
            $roundTo = 1000;

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

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

        $__piutangMeterMinRoundAmount = function ($amount) use ($__piutangRoundOnlyAmount) {
            $amount = max((float) $amount, 0);
            $minimumOrder = 10000;

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

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

            return $__piutangRoundOnlyAmount($amount);
        };

        $__piutangNormalizeUnit = 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';
        };

        $__piutangParseM2FromDescription = 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;
        };

        $__piutangItemDisplaySubtotal = function ($item) use ($__piutangRoundOnlyAmount, $__piutangMeterMinRoundAmount, $__piutangNormalizeUnit, $__piutangParseM2FromDescription) {
            $unit = $__piutangNormalizeUnit($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)
                    ? $__piutangMeterMinRoundAmount($storedSubtotal)
                    : $__piutangRoundOnlyAmount($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 = $__piutangParseM2FromDescription($item->size_description ?? $item->size ?? '');
                }

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

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

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

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

        $__piutangOrderSubtotalBeforePpn = function ($order) use ($__piutangItemDisplaySubtotal, $__piutangRoundOnlyAmount) {
            $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) => $__piutangItemDisplaySubtotal($item));
            }

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

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

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

            return $__piutangRoundOnlyAmount($total);
        };

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

            return $subtotalBeforePpn + $ppn;
        };

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

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

        $displayTotalReceivables = collect($orders->items() ?? $orders)
            ->sum(fn ($order) => $__piutangOrderDisplayRemaining($order));
    @endphp

    {{-- Stat Cards --}}
    <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($displayTotalReceivables ?? ($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="flex flex-col gap-4 border-b border-gray-200 px-5 py-4 dark:border-gray-800 xl:flex-row xl:items-center xl:justify-between">
            <div class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Laporan Piutang</h3>

                {{-- Customer Filter: native select biar pasti jalan --}}
                <form id="customerFilterForm" method="GET" class="min-w-[260px]">
                    <select
                        name="customer"
                        id="customerFilter"
                        onchange="document.getElementById('customerFilterForm').submit()"
                        class="h-[38px] w-full rounded-lg border border-gray-300 bg-white px-3 text-sm text-gray-700 focus:border-brand-500 focus:outline-none focus:ring-2 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200"
                    >
                        <option value="">Semua Customer</option>
                        @foreach($allCustomers as $customerName)
                            <option value="{{ $customerName }}" {{ $selectedCustomer === $customerName ? 'selected' : '' }}>
                                {{ $customerName }}
                            </option>
                        @endforeach
                    </select>
                </form>

                @if($hasCustomerSelected)
                    <span class="inline-flex items-center rounded-full bg-brand-50 px-3 py-1 text-xs font-medium text-brand-700 dark:bg-brand-500/10 dark:text-brand-300">
                        Customer aktif: {{ $selectedCustomer }}
                    </span>

                    <span id="selectedInfoBadge" class="inline-flex items-center rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700 dark:bg-gray-800 dark:text-gray-300">
                        0 transaksi dipilih
                    </span>
                @endif
            </div>

            <div class="flex flex-wrap items-center justify-end gap-2">
                @if($hasCustomerSelected)
                    <button
                        type="button"
                        id="printSelectedBtn"
                        disabled
                        onclick="printSelectedOrders()"
                        class="inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white transition-colors disabled:cursor-not-allowed disabled:opacity-50"
                        style="background:#dc2626;"
                        onmouseover="if(!this.disabled)this.style.background='#b91c1c'"
                        onmouseout="if(!this.disabled)this.style.background='#dc2626'"
                        title="Cetak transaksi yang dicentang"
                    >
                        <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M9 12l2 2 4-4m5 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        Print Transaksi Terpilih
                    </button>

                    <a
                        href="{{ route('print.piutang-customer', ['customer' => $selectedCustomer]) }}"
                        target="_blank"
                        class="inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white transition-colors"
                        style="background:#ef4444;"
                        onmouseover="this.style.background='#dc2626'"
                        onmouseout="this.style.background='#ef4444'"
                        title="Cetak semua piutang untuk customer terpilih"
                    >
                        <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>
                        Print Semua Customer
                    </a>
                @else
                    <span
                        class="inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium"
                        style="background:#f3f4f6; color:#6b7280; cursor:not-allowed;"
                        title="Pilih customer dulu untuk memilih transaksi / print"
                    >
                        <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>
                        Pilih Customer Dulu
                    </span>
                @endif

                <button
                    type="button"
                    onclick="openMonthDialog()"
                    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 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 2v4h10z"/>
                    </svg>
                    Print Per Bulan
                </button>

                <a
                    href="{{ route('print.piutang-all') }}"
                    target="_blank"
                    class="inline-flex items-center gap-2 rounded-lg bg-gray-800 px-4 py-2 text-sm font-medium text-white hover:bg-gray-900 dark:bg-gray-700 dark:hover:bg-gray-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 2v4h10z"/>
                    </svg>
                    Print Semua
                </a>
            </div>
        </div>

        @if($hasCustomerSelected)
            <div class="border-b border-gray-200 bg-brand-50/60 px-5 py-3 text-sm text-brand-700 dark:border-gray-800 dark:bg-brand-500/10 dark:text-brand-300">
                Pilih transaksi yang ingin dicetak. Bisa satu transaksi saja, beberapa transaksi, atau semua transaksi customer ini.
            </div>
        @endif

        <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">
                        @if($hasCustomerSelected)
                            <th class="px-4 py-3 text-center text-xs font-semibold uppercase text-gray-500">
                                <div class="flex items-center justify-center">
                                    <input
                                        type="checkbox"
                                        id="selectAllOrders"
                                        class="h-4 w-4 rounded border-gray-300 text-brand-600 focus:ring-brand-500"
                                        onchange="toggleSelectAll(this)"
                                    >
                                </div>
                            </th>
                        @endif
                        <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">Jatuh Tempo</th>
                        <th class="px-4 py-3 text-center text-xs font-semibold uppercase text-gray-500">Detail</th>
                    </tr>
                </thead>

                <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                    @forelse($orders as $order)
                        @php
                            $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');

                            $displayTotal = $__piutangOrderDisplayTotal($order);
                            $totalPaid = $order->getTotalPaid();
                            $remaining = $__piutangOrderDisplayRemaining($order);

                            $dueDate = $order->due_date ? \Carbon\Carbon::parse($order->due_date) : null;
                            $isOverdue = $dueDate && $remaining > 0 && $dueDate->isPast();
                            $dueDateClass = $isOverdue
                                ? 'text-error-600 bg-error-50 dark:bg-error-500/10 dark:text-error-400'
                                : 'text-gray-600 bg-gray-100 dark:bg-gray-800 dark:text-gray-300';
                        @endphp

                        <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                            @if($hasCustomerSelected)
                                <td class="px-4 py-3 text-center">
                                    <input
                                        type="checkbox"
                                        class="order-checkbox h-4 w-4 rounded border-gray-300 text-brand-600 focus:ring-brand-500"
                                        value="{{ $order->id }}"
                                        onchange="updateSelectedOrders()"
                                    >
                                </td>
                            @endif

                            <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 text-sm text-gray-800 dark:text-white/90">{{ $order->customer_name }}</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">
                                @if($dueDate)
                                    <div class="inline-flex flex-col items-center rounded-lg px-2 py-1 text-xs font-medium {{ $dueDateClass }}">
                                        <span>{{ $dueDate->format('d/m/Y') }}</span>
                                        @if($isOverdue)
                                            <span class="mt-0.5 text-[10px] font-semibold">Lewat tempo</span>
                                        @endif
                                    </div>
                                @else
                                    <span class="text-xs text-gray-400">-</span>
                                @endif
                            </td>

                            <td class="px-4 py-3 text-center">
                                <a href="{{ route('orders.show', $order) }}" class="text-gray-500 hover:text-brand-500" title="Lihat Detail">
                                    <svg class="size-4 mx-auto" 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>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="{{ $hasCustomerSelected ? 10 : 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 font-medium text-success-600 dark:text-success-400">Tidak ada piutang.</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="{{ $hasCustomerSelected ? 7 : 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($displayTotalReceivables ?? ($summary['total_receivables'] ?? 0), 0, ',', '.') }}
                            </td>
                            <td colspan="3"></td>
                        </tr>
                    </tfoot>
                @endif
            </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>

    {{-- Month Selection Dialog --}}
    <div id="monthDialog" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/50 backdrop-blur-sm">
        <div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-xl dark:bg-gray-800">
            <div class="mb-4 flex items-center justify-between">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white">Pilih Bulan</h3>
                <button type="button" onclick="closeMonthDialog()" 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="mb-6">
                <label for="printMonth" class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">Bulan Piutang</label>
                <input
                    type="month"
                    id="printMonth"
                    value="{{ now()->format('Y-m') }}"
                    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"
                >
            </div>

            <div class="flex gap-3">
                <button
                    type="button"
                    onclick="closeMonthDialog()"
                    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="button"
                    onclick="printByMonth()"
                    class="flex-1 rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-600"
                >
                    Cetak
                </button>
            </div>
        </div>
    </div>

    {{-- Payment History Dialog --}}
    <div id="historyDialog" class="fixed inset-0 z-50 hidden items-center justify-center bg-black/50 backdrop-blur-sm">
        <div class="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-[50vh] overflow-y-auto p-4">
                <div id="historyContent" class="space-y-2"></div>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
<script>
    function openMonthDialog() {
        const modal = document.getElementById('monthDialog');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closeMonthDialog() {
        const modal = document.getElementById('monthDialog');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    function printByMonth() {
        const month = document.getElementById('printMonth').value;
        if (!month) return;

        window.open(`{{ route('print.piutang') }}?month=${month}`, '_blank');
        closeMonthDialog();
    }

    function getOrderCheckboxes() {
        return Array.from(document.querySelectorAll('.order-checkbox'));
    }

    function updateSelectedOrders() {
        const printSelectedBtn = document.getElementById('printSelectedBtn');
        const selectAllCheckbox = document.getElementById('selectAllOrders');
        const selectedInfoBadge = document.getElementById('selectedInfoBadge');
        const checkboxes = getOrderCheckboxes();
        const checked = checkboxes.filter(el => el.checked);

        if (printSelectedBtn) {
            printSelectedBtn.disabled = checked.length === 0;
            printSelectedBtn.innerHTML = `
                <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>
                Print Transaksi Terpilih${checked.length > 0 ? ` (${checked.length})` : ''}
            `;
        }

        if (selectedInfoBadge) {
            selectedInfoBadge.textContent = `${checked.length} transaksi dipilih`;
        }

        if (selectAllCheckbox) {
            const allChecked = checkboxes.length > 0 && checkboxes.every(el => el.checked);
            selectAllCheckbox.checked = allChecked;
            selectAllCheckbox.indeterminate = checked.length > 0 && !allChecked;
        }
    }

    function toggleSelectAll(source) {
        getOrderCheckboxes().forEach(el => {
            el.checked = source.checked;
        });
        updateSelectedOrders();
    }

    function printSelectedOrders() {
        const checked = getOrderCheckboxes().filter(el => el.checked).map(el => el.value);

        if (!checked.length) {
            alert('Pilih minimal 1 transaksi yang mau dicetak.');
            return;
        }

        const url = new URL(@json(route('print.piutang-customer')), window.location.origin);
        url.searchParams.set('customer', @json($selectedCustomer));

        checked.forEach(id => {
            url.searchParams.append('order_ids[]', id);
        });

        window.open(url.toString(), '_blank');
    }

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

    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 p-3 dark:border-gray-700">
                    <div class="mb-1 flex items-center justify-between">
                        <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>&bull; ${p.cashier}</span>
                        ${p.proof ? `<a href="${p.proof}" target="_blank" class="text-brand-600 hover:underline dark:text-brand-400">Bukti</a>` : ''}
                    </div>
                    ${p.notes ? `<p class="mt-1 text-xs italic text-gray-400">"${p.notes}"</p>` : ''}
                </div>
            `;
        });

        html += `
            <div class="mt-2 rounded-lg bg-gray-100 p-3 dark:bg-gray-700">
                <div class="flex items-center justify-between">
                    <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');
        document.getElementById('historyDialog').classList.add('flex');
    }

    function closeHistoryDialog() {
        const modal = document.getElementById('historyDialog');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    document.addEventListener('DOMContentLoaded', function() {
        updateSelectedOrders();

        const monthDialog = document.getElementById('monthDialog');
        if (monthDialog) {
            monthDialog.addEventListener('click', function(e) {
                if (e.target === this) closeMonthDialog();
            });
        }

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

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeMonthDialog();
            closeHistoryDialog();
        }
    });
</script>
@endpush
