@extends('layouts.app')

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

    @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);
        };

        $isCredit = $order->is_credit;
        $isPartialPaid = $order->isPartiallyPaid();
        $totalPaid = $order->getTotalPaid();
        $displayOrderTotal = $__orderDisplayTotal($order);
        $displaySubtotalBeforePpn = $__orderDisplaySubtotalBeforePpn($order);
        $remainingBalance = $__orderDisplayRemaining($order);
        $taxSetting = $taxSetting ?? null;
        $ppnRate = (float) old('ppn_rate', $order->ppn_rate ?: ($taxSetting->rate ?? 11));
        $totalBeforePpn = (float) $displaySubtotalBeforePpn;
        $canChoosePpn = ((float) $totalPaid <= 0);
        $defaultUsePpn = in_array(old('use_ppn', '0'), ['1', 1, true, 'on', 'yes'], true);
        $baseRemainingForPayment = $canChoosePpn ? $totalBeforePpn : (float) $remainingBalance;
        $previewPpnAmount = $defaultUsePpn && $canChoosePpn ? round($baseRemainingForPayment * ($ppnRate / 100)) : 0;
        $previewRemainingBalance = $canChoosePpn ? ($baseRemainingForPayment + $previewPpnAmount) : (float) $remainingBalance;
    @endphp

    <div class="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {{-- Order Details --}}
        <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 px-5 py-4 dark:border-gray-800">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Detail Order</h3>
                    @if($isCredit)
                    <span class="inline-flex items-center gap-1.5 rounded-full bg-amber-100 px-3 py-1 text-xs font-semibold text-amber-700 dark:bg-amber-500/15 dark:text-amber-400">
                        <svg class="size-3.5" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                        </svg>
                        PIUTANG
                    </span>
                    @endif
                </div>
            </div>
            <div class="p-5">
                <dl class="space-y-4">
                    <div class="flex justify-between">
                        <dt class="text-sm text-gray-500 dark:text-gray-400">No. Invoice</dt>
                        <dd class="text-sm font-semibold text-gray-800 dark:text-white/90">{{ $order->invoice_number }}</dd>
                    </div>
                    <div class="flex justify-between">
                        <dt class="text-sm text-gray-500 dark:text-gray-400">Pelanggan</dt>
                        <dd class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $order->customer_name }}</dd>
                    </div>

                    @if($isPartialPaid || ($isCredit && $totalPaid > 0))
                    <div class="rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-800 dark:bg-blue-900/20">
                        <div class="mb-2 flex items-center gap-2">
                            <svg class="size-5 text-blue-500" 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>
                            <span class="text-sm font-semibold text-blue-700 dark:text-blue-400">Pembayaran Cicilan</span>
                        </div>
                        <div class="grid grid-cols-2 gap-2 text-sm">
                            <div>
                                <span class="text-blue-600 dark:text-blue-400">Sudah Dibayar:</span>
                                <span class="font-semibold text-blue-700 dark:text-blue-300">Rp {{ number_format($totalPaid, 0, ',', '.') }}</span>
                            </div>
                            <div>
                                <span class="text-blue-600 dark:text-blue-400">Sisa:</span>
                                <span class="font-bold text-blue-700 dark:text-blue-300">Rp {{ number_format($remainingBalance, 0, ',', '.') }}</span>
                            </div>
                        </div>
                    </div>
                    @endif

                    <hr class="border-gray-200 dark:border-gray-700">

                    <div>
                        <dt class="mb-2 text-sm font-medium text-gray-700 dark:text-gray-300">Item Order ({{ $order->items->count() }})</dt>
                        <dd class="space-y-2">
                            @foreach($order->items as $item)
                            <div class="rounded-lg bg-gray-50 p-3 dark:bg-gray-800">
                                <div class="flex items-start justify-between">
                                    <div>
                                        <span class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $item->product_name }}</span>
                                        <p class="text-xs text-gray-500">{{ $item->file_name }} • {{ $item->size_description }}</p>
                                        @if($item->material_name)
                                        <p class="text-xs text-gray-500">Bahan: {{ $item->material_name }}</p>
                                        @endif
                                    </div>
                                    <span class="text-sm font-bold text-gray-800 dark:text-white/90">Rp {{ number_format($__itemDisplaySubtotal($item), 0, ',', '.') }}</span>
                                </div>
                                <div class="mt-1 text-xs text-gray-500">
                                    {{ $item->qty }} pcs × Rp {{ number_format($item->calculated_price, 0, ',', '.') }}
                                </div>
                            </div>
                            @endforeach
                        </dd>
                    </div>

                    <hr class="border-gray-200 dark:border-gray-700">
                    <div class="flex items-center justify-between">
                        <dt class="text-lg font-semibold text-gray-800 dark:text-white/90">TOTAL</dt>
                        <dd class="text-2xl font-bold text-brand-500">Rp {{ number_format($displayOrderTotal, 0, ',', '.') }}</dd>
                    </div>
                    @if($remainingBalance < $displayOrderTotal)
                    <div class="flex items-center justify-between text-success-600 dark:text-success-400">
                        <dt class="text-sm font-medium">Sisa Tagihan</dt>
                        <dd class="text-xl font-bold">Rp {{ number_format($remainingBalance, 0, ',', '.') }}</dd>
                    </div>
                    @endif
                </dl>
            </div>
        </div>

        {{-- Payment Form --}}
        <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 px-5 py-4 dark:border-gray-800">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Pembayaran</h3>
            </div>
            <div class="p-5">
                <form action="{{ route('kasir.process', $order) }}" method="POST" x-data="paymentForm()">
                    @csrf
                    <div class="space-y-5">
                        <div class="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
                            <p class="text-sm text-gray-500 dark:text-gray-400">
                                {{ $remainingBalance < $displayOrderTotal ? 'Sisa Tagihan' : 'Total Tagihan' }}
                            </p>
                            <p class="text-3xl font-bold text-gray-800 dark:text-white/90" x-text="'Rp ' + remaining.toLocaleString('id-ID')">
                                Rp {{ number_format($previewRemainingBalance, 0, ',', '.') }}
                            </p>

                            @if($canChoosePpn)
                                <div class="mt-4 rounded-xl border border-blue-200 bg-blue-50 p-4 dark:border-blue-500/30 dark:bg-blue-500/10">
                                    <label class="flex cursor-pointer items-start gap-3">
                                                                                <input type="hidden" name="use_ppn" value="0">
<input type="checkbox"
                                               name="use_ppn"
                                               value="1"
                                               x-model="usePpn"
                                               @change="updatePpnTotal()"
                                               class="mt-1 rounded border-gray-300 text-brand-500 focus:ring-brand-500">
                                        <span>
                                            <span class="block text-sm font-bold text-blue-800 dark:text-blue-200">Gunakan PPN {{ rtrim(rtrim(number_format($ppnRate, 2, ',', '.'), '0'), ',') }}%</span>
                                            <span class="block text-xs text-blue-700 dark:text-blue-300">PPN akan disimpan ke data order saat pembayaran diproses.</span>
                                        </span>
                                    </label>

                                    <input type="hidden" name="ppn_rate" value="{{ $ppnRate }}">

                                    <div class="mt-3 space-y-1 text-sm" x-show="usePpn">
                                        <div class="flex justify-between">
                                            <span class="text-blue-700 dark:text-blue-300">Subtotal sebelum PPN</span>
                                            <span class="font-semibold text-blue-900 dark:text-blue-100" x-text="'Rp ' + baseRemaining.toLocaleString('id-ID')"></span>
                                        </div>
                                        <div class="flex justify-between">
                                            <span class="text-blue-700 dark:text-blue-300">PPN</span>
                                            <span class="font-semibold text-blue-900 dark:text-blue-100" x-text="'Rp ' + ppnAmount.toLocaleString('id-ID')"></span>
                                        </div>
                                    </div>
                                </div>
                            @elseif(($order->use_ppn ?? false))
                                <div class="mt-3 rounded-lg border border-blue-200 bg-blue-50 p-3 text-sm text-blue-800 dark:border-blue-500/30 dark:bg-blue-500/10 dark:text-blue-200">
                                    Order ini menggunakan PPN {{ rtrim(rtrim(number_format((float) ($order->ppn_rate ?? $ppnRate), 2, ',', '.'), '0'), ',') }}%. PPN sudah tersimpan di data order.
                                </div>
                            @endif
                        </div>

                        @if($isCredit)
                        <div>
                            <label class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-400">
                                Jenis Pembayaran <span class="text-error-500">*</span>
                            </label>
                            <div class="grid grid-cols-2 gap-4">
                                <div @click="paymentType = 'full'; updateTotalFromType()"
                                    class="relative cursor-pointer rounded-xl border-2 p-5 transition-all duration-200"
                                    :class="paymentType === 'full'
                                        ? 'border-brand-500 bg-brand-500/10 dark:bg-brand-500/20 shadow-lg shadow-brand-500/20'
                                        : 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 hover:border-brand-300 dark:hover:border-brand-600'">
                                    <div class="absolute right-3 top-3 flex h-5 w-5 items-center justify-center rounded-full border-[1.5px]"
                                        :class="paymentType === 'full'
                                            ? 'border-brand-500 bg-brand-500'
                                            : 'border-gray-300 dark:border-gray-600 bg-transparent'">
                                        <span class="h-2 w-2 rounded-full bg-white" x-show="paymentType === 'full'"></span>
                                    </div>
                                    <div class="flex flex-col items-center gap-2 text-center">
                                        <div class="flex h-12 w-12 items-center justify-center rounded-full"
                                            :class="paymentType === 'full' ? 'bg-brand-500 text-white' : 'bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400'">
                                            <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                            </svg>
                                        </div>
                                        <span class="text-sm font-semibold" :class="paymentType === 'full' ? 'text-brand-600 dark:text-brand-400' : 'text-gray-700 dark:text-gray-300'">Bayar Lunas</span>
                                    </div>
                                </div>

                                <div @click="paymentType = 'dp'; updateTotalFromType()"
                                    class="relative cursor-pointer rounded-xl border-2 p-5 transition-all duration-200"
                                    :class="paymentType === 'dp'
                                        ? 'border-warning-500 bg-warning-500/10 dark:bg-warning-500/20 shadow-lg shadow-warning-500/20'
                                        : 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 hover:border-warning-300 dark:hover:border-warning-600'">
                                    <div class="absolute right-3 top-3 flex h-5 w-5 items-center justify-center rounded-full border-[1.5px]"
                                        :class="paymentType === 'dp'
                                            ? 'border-warning-500 bg-warning-500'
                                            : 'border-gray-300 dark:border-gray-600 bg-transparent'">
                                        <span class="h-2 w-2 rounded-full bg-white" x-show="paymentType === 'dp'"></span>
                                    </div>
                                    <div class="flex flex-col items-center gap-2 text-center">
                                        <div class="flex h-12 w-12 items-center justify-center rounded-full"
                                            :class="paymentType === 'dp' ? 'bg-warning-500 text-white' : 'bg-gray-100 dark:bg-gray-800 text-gray-500 dark:text-gray-400'">
                                            <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" 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>
                                        </div>
                                        <span class="text-sm font-semibold" :class="paymentType === 'dp' ? 'text-warning-600 dark:text-warning-400' : 'text-gray-700 dark:text-gray-300'">DP / Cicilan</span>
                                    </div>
                                </div>
                            </div>
                            <input type="hidden" name="payment_type" :value="paymentType">
                        </div>

                        <div x-show="paymentType === 'dp'" x-cloak class="rounded-xl border border-warning-200 bg-warning-50 p-4 dark:border-warning-500/20 dark:bg-warning-500/10">
                            <label class="mb-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                                Tanggal Jatuh Tempo <span class="text-error-500">*</span>
                            </label>
                            <input
                                type="date"
                                name="due_date"
                                x-model="dueDate"
                                :required="paymentType === 'dp'"
                                :min="minDueDate"
                                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"
                            >
                            <p class="mt-2 text-xs text-gray-600 dark:text-gray-400">
                                Kolom ini hanya muncul saat pembayaran <span class="font-semibold">DP / Cicilan</span>.
                            </p>
                        </div>
                        @else
                        <input type="hidden" name="payment_type" value="full">
                        @endif

                        <div>
                            <div class="mb-2 flex items-center justify-between">
                                <label class="text-sm font-medium text-gray-700 dark:text-gray-400">
                                    Detail Pembayaran
                                </label>
                                <button type="button" @click="addPayment()"
                                    class="flex items-center gap-1 text-xs font-medium text-brand-600 hover:text-brand-700 dark:text-brand-400">
                                    <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>
                                                <div class="relative">
                                                    <select :name="'payments[' + index + '][method]'" x-model="payment.method"
                                                        class="h-11 w-full appearance-none rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 pr-11 text-sm text-gray-800 shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800">
                                                        <option value="cash">💵 Tunai</option>
                                                        <option value="transfer">🏦 Transfer Bank</option>
                                                        <option value="ewallet">📱 E-Wallet</option>
                                                    </select>
                                                    <span class="pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-400">
                                                        <svg class="stroke-current" width="20" height="20" viewBox="0 0 20 20" fill="none">
                                                            <path d="M4.79175 7.396L10.0001 12.6043L15.2084 7.396" stroke="" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
                                                        </svg>
                                                    </span>
                                                </div>
                                            </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 shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800">
                                                </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 appearance-none rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90">
                                                <option value="">Pilih Rekening</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 appearance-none rounded-lg border border-gray-300 bg-transparent px-4 py-2.5 text-sm text-gray-800 shadow-theme-xs focus:border-brand-300 focus:outline-hidden focus:ring-3 focus:ring-brand-500/20 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90">
                                                <option value="">Pilih E-Wallet</option>
                                                @foreach($ewalletAccounts ?? [] as $account)
                                                <option value="{{ $account->id }}">{{ $account->getFullLabel() }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                </template>
                            </div>

                            @error('payments')
                                <p class="mt-1 text-sm text-error-500">{{ $message }}</p>
                            @enderror
                        </div>

                        <div x-show="payments.length === 1">
                            <div class="mb-2 grid grid-cols-4 gap-2">
                                @foreach([10000, 20000, 50000, 100000] as $amount)
                                <button type="button" @click="payments[0].amount = remaining + {{ $amount }}; updateTotal()"
                                    class="rounded-lg border border-gray-300 bg-white px-2 py-2 text-xs font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                                    +{{ number_format($amount / 1000) }}rb
                                </button>
                                @endforeach
                            </div>
                            <button type="button" @click="setExactAmount()"
                                class="w-full rounded-lg border border-brand-500 bg-brand-50 px-4 py-2 text-sm font-medium text-brand-600 hover:bg-brand-100 dark:bg-brand-500/10 dark:text-brand-400 dark:hover:bg-brand-500/20">
                                Uang Pas
                            </button>
                        </div>

                        <div class="rounded-xl border-2 p-5"
                            :class="getSummaryClass()">
                            <div class="space-y-3">
                                <div class="flex justify-between text-sm">
                                    <span class="text-gray-600 dark:text-gray-400">Total Pembayaran</span>
                                    <span class="font-bold text-gray-800 dark:text-white/90" x-text="'Rp ' + totalPaidAmount.toLocaleString('id-ID')"></span>
                                </div>
                                @if($isCredit)
                                <div x-show="paymentType === 'dp' && dueDate" class="flex justify-between text-sm">
                                    <span class="text-gray-600 dark:text-gray-400">Jatuh Tempo</span>
                                    <span class="font-semibold text-gray-800 dark:text-white/90" x-text="formatDate(dueDate)"></span>
                                </div>
                                @endif
                                <hr class="border-gray-200 dark:border-gray-600">
                                <div class="flex items-center justify-between">
                                    <span class="font-semibold" :class="getBalanceLabel().class" x-text="getBalanceLabel().text"></span>
                                    <span class="text-2xl font-bold" :class="getBalanceLabel().class" x-text="'Rp ' + Math.abs(balance).toLocaleString('id-ID')"></span>
                                </div>
                            </div>
                        </div>

                        <button type="submit" :disabled="!canSubmit()"
                            class="flex w-full items-center justify-center gap-2 rounded-xl px-5 py-4 text-lg font-bold text-white shadow-lg transition-all disabled:cursor-not-allowed disabled:opacity-50"
                            :class="getButtonClass()">
                            <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                            </svg>
                            <span x-text="getSubmitText()"></span>
                        </button>

                        <a href="{{ route('kasir.index') }}" class="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-300 bg-white px-4 py-3 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                            Batal
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function paymentForm() {
            const today = new Date();
            const nextWeek = new Date(today);
            nextWeek.setDate(today.getDate() + 7);

            return {
                baseRemaining: {{ (int) round($baseRemainingForPayment) }},
                remaining: {{ (int) round($previewRemainingBalance) }},
                usePpn: {{ $defaultUsePpn ? 'true' : 'false' }},
                ppnRate: {{ $ppnRate }},
                ppnAmount: {{ (int) round($previewPpnAmount) }},
                canChoosePpn: {{ $canChoosePpn ? 'true' : 'false' }},
                isCredit: {{ $isCredit ? 'true' : 'false' }},
                paymentType: '{{ $isCredit ? "full" : "full" }}',
                dueDate: '{{ old('due_date', '') }}' || nextWeek.toISOString().split('T')[0],
                minDueDate: today.toISOString().split('T')[0],
                payments: [
                    { method: 'cash', amount: {{ (int) round($previewRemainingBalance) }}, account_id: '' }
                ],
                totalPaidAmount: {{ (int) round($previewRemainingBalance) }},
                balance: 0,

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

                updatePpnTotal() {
                    if (this.canChoosePpn) {
                        this.ppnAmount = this.usePpn ? Math.round(this.baseRemaining * (this.ppnRate / 100)) : 0;
                        this.remaining = this.baseRemaining + this.ppnAmount;

                        if (this.paymentType === 'full' && this.payments.length === 1) {
                            this.payments[0].amount = this.remaining;
                        }
                    }

                    this.updateTotal();
                },

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

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

                updateTotal() {
                    this.totalPaidAmount = this.payments.reduce((sum, p) => sum + (parseFloat(p.amount) || 0), 0);
                    this.balance = this.totalPaidAmount - this.remaining;
                },

                updateTotalFromType() {
                    if (this.paymentType === 'full') {
                        this.payments = [{ method: 'cash', amount: this.remaining, account_id: '' }];
                    } else {
                        this.payments = [{ method: 'cash', amount: Math.round(this.remaining / 2), account_id: '' }];
                        if (!this.dueDate) {
                            this.dueDate = nextWeek.toISOString().split('T')[0];
                        }
                    }
                    this.updateTotal();
                },

                setExactAmount() {
                    this.payments[0].amount = this.remaining;
                    this.updateTotal();
                },

                formatDate(dateString) {
                    if (!dateString) return '-';
                    const date = new Date(dateString + 'T00:00:00');
                    return date.toLocaleDateString('id-ID', {
                        day: '2-digit',
                        month: 'long',
                        year: 'numeric'
                    });
                },

                getSummaryClass() {
                    if (this.balance >= 0) {
                        return 'border-success-500 bg-success-500/10 dark:bg-success-500/20';
                    } else if (this.isCredit && this.paymentType === 'dp') {
                        return 'border-warning-500 bg-warning-500/10 dark:bg-warning-500/20';
                    }
                    return 'border-error-500 bg-error-500/10 dark:bg-error-500/20';
                },

                getBalanceLabel() {
                    if (this.balance >= 0) {
                        return { text: 'Kembalian', class: 'text-success-600 dark:text-success-400' };
                    } else if (this.isCredit && this.paymentType === 'dp') {
                        return { text: 'Sisa Piutang', class: 'text-warning-600 dark:text-warning-400' };
                    }
                    return { text: 'Kurang', class: 'text-error-600 dark:text-error-400' };
                },

                getButtonClass() {
                    if (this.balance >= 0) {
                        return 'bg-success-500 hover:bg-success-600 shadow-success-500/30';
                    } else if (this.isCredit && this.paymentType === 'dp') {
                        return 'bg-warning-500 hover:bg-warning-600 shadow-warning-500/30';
                    }
                    return 'bg-gray-400 dark:bg-gray-600 cursor-not-allowed';
                },

                canSubmit() {
                    if (this.totalPaidAmount <= 0) return false;
                    if (this.isCredit && this.paymentType === 'dp' && !this.dueDate) return false;
                    if (this.balance >= 0) return true;
                    if (this.isCredit && this.paymentType === 'dp') return true;
                    return false;
                },

                getSubmitText() {
                    if (this.balance >= 0) {
                        return 'Proses Pembayaran (Lunas)';
                    } else if (this.isCredit && this.paymentType === 'dp') {
                        return 'Proses DP / Cicilan';
                    }
                    return 'Jumlah Kurang';
                }
            }
        }
    </script>
@endsection
