@extends('layouts.app')

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

    @php
        $paymentMethod = $batchPaymentInfo['payment_method'] ?? 'cash';
        $paymentMethodLabel = $batchPaymentInfo['payment_method_label'] ?? match ($paymentMethod) {
            'cash' => 'Tunai',
            'transfer' => 'Transfer Bank',
            'ewallet' => 'E-Wallet',
            'split' => 'Split Payment',
            default => ucfirst($paymentMethod),
        };

        $isSplitPayment = (bool) ($batchPaymentInfo['is_split_payment'] ?? false);
        $splitSummary = collect($batchPaymentInfo['split_summary'] ?? []);
        $splitTotal = (float) ($batchPaymentInfo['split_total'] ?? $splitSummary->sum('amount'));

        $paidAmount = (float) ($batchPaymentInfo['paid_amount'] ?? 0);
        $cashReceived = (float) ($batchPaymentInfo['cash_received'] ?? 0);
        $changeAmount = (float) ($batchPaymentInfo['change_amount'] ?? 0);

        $grandTotal = (float) $orders->sum('total_price');
        $grandPaidNow = $paidAmount > 0 ? $paidAmount : ($isSplitPayment ? $splitTotal : $grandTotal);
        $grandRemaining = (float) $orders->sum(fn ($order) => method_exists($order, 'getRemainingBalance') ? $order->getRemainingBalance() : 0);

        $printUrl = route('kasir.pelunasan.printBatch', [
            'order_ids' => $orders->pluck('id')->implode(','),
            'paid_amount' => $paidAmount,
            'cash_received' => $cashReceived,
            'change_amount' => $changeAmount,
            'payment_method' => $paymentMethod,
            'split_summary' => $isSplitPayment ? base64_encode(json_encode($splitSummary->values()->all())) : null,
        ]);
    @endphp

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

    <div class="mb-6 rounded-2xl border border-brand-200 bg-brand-50 p-5 dark:border-brand-900/40 dark:bg-brand-900/10">
        <div class="flex items-start gap-4">
            <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-500 text-white">
                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                </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">Struk Batch Siap Dicetak</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">
                        {{ $orders->count() }} order diproses
                    </span>
                    @if($isSplitPayment)
                        <span class="rounded-full bg-white/80 px-2 py-0.5 text-xs font-medium text-brand-700 dark:bg-white/10 dark:text-brand-300">
                            Split Payment
                        </span>
                    @endif
                </div>

                <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                    Pembayaran batch sudah dicatat. Ringkasan di bawah sudah sinkron untuk pembayaran tunggal maupun split payment.
                </p>
            </div>
        </div>
    </div>

    <div class="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
        <x-posgraf.stat-card
            title="Jumlah Order"
            value="{{ $orders->count() }}"
            color="brand"
        />
        <x-posgraf.stat-card
            title="Total Tagihan"
            value="Rp {{ number_format($grandTotal, 0, ',', '.') }}"
            color="warning"
        />
        <x-posgraf.stat-card
            title="Jumlah Dibayar"
            value="Rp {{ number_format($grandPaidNow, 0, ',', '.') }}"
            color="success"
        />
        <x-posgraf.stat-card
            title="Sisa Setelah Pembayaran"
            value="Rp {{ number_format($grandRemaining, 0, ',', '.') }}"
            color="error"
        />
    </div>

    <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
            <div class="flex items-center justify-between gap-3">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Pembayaran Berhasil Dicatat</h3>
                <span class="inline-flex rounded-full bg-success-50 px-3 py-1 text-sm font-medium text-success-700 dark:bg-success-500/15 dark:text-success-500">
                    {{ $orders->count() }} Order Diproses
                </span>
            </div>
        </div>

        <div class="p-5">
            <div class="mx-auto max-w-4xl">
                <div class="mb-6 rounded-xl border border-gray-200 bg-gray-50 p-4 dark:border-gray-700 dark:bg-gray-800/50">
                    <div class="mb-3 flex items-center justify-between">
                        <h4 class="text-sm font-semibold text-gray-800 dark:text-white">Ringkasan Pembayaran</h4>
                        <span class="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700 ring-1 ring-gray-200 dark:bg-gray-900 dark:text-gray-300 dark:ring-gray-700">
                            {{ $paymentMethodLabel }}
                        </span>
                    </div>

                    @if($isSplitPayment)
                        <div class="mb-4 rounded-lg border border-brand-200 bg-white p-4 dark:border-brand-900/40 dark:bg-gray-900">
                            <div class="mb-3 text-sm font-semibold text-gray-800 dark:text-white">Detail Split Payment</div>
                            <div class="space-y-2">
                                @foreach($splitSummary as $split)
                                    <div class="flex items-center justify-between rounded-lg bg-gray-50 px-3 py-2 text-sm dark:bg-gray-800/70">
                                        <div>
                                            <div class="font-medium text-gray-800 dark:text-white">{{ $split['method_label'] ?? '-' }}</div>
                                            @if(!empty($split['account_label']))
                                                <div class="text-xs text-gray-500 dark:text-gray-400">{{ $split['account_label'] }}</div>
                                            @endif
                                        </div>
                                        <div class="font-semibold text-gray-900 dark:text-white">
                                            Rp {{ number_format((float) ($split['amount'] ?? 0), 0, ',', '.') }}
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                            <div class="mt-3 flex items-center justify-between border-t border-dashed border-gray-200 pt-3 text-sm dark:border-gray-700">
                                <span class="font-semibold text-gray-700 dark:text-gray-300">Total Split</span>
                                <span class="text-base font-bold text-brand-600 dark:text-brand-400">
                                    Rp {{ number_format($splitTotal, 0, ',', '.') }}
                                </span>
                            </div>
                        </div>
                    @endif

                    <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
                        <div class="space-y-2 text-sm">
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Metode Bayar</span>
                                <span class="font-medium text-gray-800 dark:text-white">{{ $paymentMethodLabel }}</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-gray-500 dark:text-gray-400">Jumlah Dibayar</span>
                                <span class="font-medium text-gray-800 dark:text-white">Rp {{ number_format($grandPaidNow, 0, ',', '.') }}</span>
                            </div>
                        </div>

                        <div class="space-y-2 text-sm">
                            @if(!$isSplitPayment && $paymentMethod === 'cash')
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-500 dark:text-gray-400">Uang Diterima</span>
                                    <span class="font-medium text-gray-800 dark:text-white">
                                        Rp {{ number_format($cashReceived > 0 ? $cashReceived : $grandPaidNow, 0, ',', '.') }}
                                    </span>
                                </div>
                                <div class="flex items-center justify-between border-t border-dashed border-gray-200 pt-2 dark:border-gray-700">
                                    <span class="font-semibold text-gray-700 dark:text-gray-300">Kembalian</span>
                                    <span class="text-base font-bold text-success-600 dark:text-success-400">
                                        Rp {{ number_format($changeAmount, 0, ',', '.') }}
                                    </span>
                                </div>
                            @else
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-500 dark:text-gray-400">Status</span>
                                    <span class="font-medium text-gray-800 dark:text-white">
                                        {{ $isSplitPayment ? 'Gabungan beberapa metode pembayaran' : 'Non-tunai / tanpa kembalian' }}
                                    </span>
                                </div>
                                @if($changeAmount > 0)
                                    <div class="flex items-center justify-between border-t border-dashed border-gray-200 pt-2 dark:border-gray-700">
                                        <span class="font-semibold text-gray-700 dark:text-gray-300">Kembalian</span>
                                        <span class="text-base font-bold text-success-600 dark:text-success-400">
                                            Rp {{ number_format($changeAmount, 0, ',', '.') }}
                                        </span>
                                    </div>
                                @endif
                            @endif
                        </div>
                    </div>
                </div>

                <div class="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700">
                    <table class="w-full text-left">
                        <thead class="bg-gray-50 dark:bg-gray-800/50">
                            <tr>
                                <th class="px-4 py-3 text-xs font-semibold uppercase text-gray-500">Invoice</th>
                                <th class="px-4 py-3 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">Sisa</th>
                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase text-gray-500">Status</th>
                                <th class="px-4 py-3 text-center text-xs font-semibold uppercase text-gray-500">Aksi</th>
                            </tr>
                        </thead>

                        <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                            @foreach($orders as $order)
                                @php
                                    $remaining = method_exists($order, 'getRemainingBalance') ? (float) $order->getRemainingBalance() : 0;
                                    $isPaid = method_exists($order, 'isPaid') ? $order->isPaid() : ($remaining <= 0);
                                @endphp
                                <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                                    <td class="px-4 py-3 text-sm font-medium text-brand-600">
                                        {{ $order->invoice_number }}
                                    </td>
                                    <td class="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">
                                        {{ $order->customer_name }}
                                    </td>
                                    <td class="px-4 py-3 text-right text-sm font-semibold text-gray-900 dark:text-white">
                                        Rp {{ number_format($order->total_price, 0, ',', '.') }}
                                    </td>
                                    <td class="px-4 py-3 text-right text-sm font-semibold {{ $remaining > 0 ? 'text-error-600 dark:text-error-400' : 'text-success-600 dark:text-success-400' }}">
                                        Rp {{ number_format($remaining, 0, ',', '.') }}
                                    </td>
                                    <td class="px-4 py-3 text-center">
                                        @if($isPaid)
                                            <span class="inline-flex rounded-full bg-success-50 px-2.5 py-1 text-xs font-medium text-success-700 dark:bg-success-500/15 dark:text-success-400">
                                                Lunas
                                            </span>
                                        @elseif($remaining < (float) $order->total_price)
                                            <span class="inline-flex rounded-full bg-warning-50 px-2.5 py-1 text-xs font-medium text-warning-700 dark:bg-warning-500/15 dark:text-warning-400">
                                                Sebagian
                                            </span>
                                        @else
                                            <span class="inline-flex rounded-full bg-error-50 px-2.5 py-1 text-xs font-medium text-error-700 dark:bg-error-500/15 dark:text-error-400">
                                                Belum Bayar
                                            </span>
                                        @endif
                                    </td>
                                    <td class="px-4 py-3 text-center">
                                        <div class="flex items-center justify-center gap-2">
                                            <a href="{{ route('print.nota', $order) }}" target="_blank" class="text-gray-400 hover:text-brand-500" title="Cetak Nota">
                                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z" />
                                                </svg>
                                            </a>
                                            <a href="{{ route('orders.show', $order) }}" class="text-gray-400 hover:text-brand-500" title="Lihat Detail">
                                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                                </svg>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>

                        <tfoot class="bg-gray-50 dark:bg-gray-800/50">
                            <tr>
                                <td colspan="2" class="px-4 py-3 text-sm font-bold text-gray-900 dark:text-white">TOTAL GABUNGAN</td>
                                <td class="px-4 py-3 text-right text-base font-bold text-brand-600">
                                    Rp {{ number_format($grandTotal, 0, ',', '.') }}
                                </td>
                                <td class="px-4 py-3 text-right text-base font-bold {{ $grandRemaining > 0 ? 'text-error-600 dark:text-error-400' : 'text-success-600 dark:text-success-400' }}">
                                    Rp {{ number_format($grandRemaining, 0, ',', '.') }}
                                </td>
                                <td colspan="2"></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="mt-8 grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <a href="{{ $printUrl }}" target="_blank" class="flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-6 py-4 text-base font-bold text-white shadow-lg shadow-brand-500/20 transition-all hover:-translate-y-0.5 hover:bg-brand-600">
                        <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 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 Nota Gabungan (80mm)
                    </a>

                    <a href="{{ route('kasir.pelunasan') }}" class="flex items-center justify-center gap-2 rounded-xl border border-gray-200 bg-white px-6 py-4 text-base font-medium text-gray-700 transition-all hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                        Kembali ke Pelunasan
                    </a>
                </div>

                <p class="mt-6 text-center text-sm text-gray-500">
                    Nota gabungan akan mencetak semua rincian item dari {{ $orders->count() }} order beserta ringkasan pembayaran batch yang sudah sinkron.
                </p>
            </div>
        </div>
    </div>
@endsection
