@extends('layouts.app')

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

    @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="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 flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Tagihan Belum Dibayar</h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400">Klik tombol Bayar untuk memproses pembayaran</p>
                </div>
                <a href="{{ route('kasir.history') }}" class="inline-flex items-center gap-2 text-sm text-brand-500 hover:text-brand-600">
                    <svg class="size-5" 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>
                    Riwayat Pembayaran
                </a>
            </div>
        </div>

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

        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b border-gray-200 dark:border-gray-800">
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Invoice</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Pelanggan</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Item</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Total</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Aksi</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                    @forelse($orders as $order)
                    <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                        <td class="px-5 py-4">
                            <div class="flex items-center gap-2">
                                <span class="text-sm font-medium text-gray-800 dark:text-white/90">{{ $order->invoice_number }}</span>
                                @if($order->is_credit)
                                <span class="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-xs font-semibold text-amber-700 dark:bg-amber-500/15 dark:text-amber-400">Piutang</span>
                                @endif
                                @if($order->isPartiallyPaid())
                                <span class="inline-flex items-center rounded-full bg-blue-100 px-2 py-0.5 text-xs font-semibold text-blue-700 dark:bg-blue-500/15 dark:text-blue-400">Cicilan</span>
                                @endif
                            </div>
                            <span class="text-xs text-gray-500">{{ $order->created_at->format('d M Y') }}</span>
                        </td>
                        <td class="px-5 py-4">
                            <span class="text-sm text-gray-800 dark:text-white/90">{{ $order->customer_name }}</span>
                            @if($order->customer_phone)
                            <br><span class="text-xs text-gray-500">{{ $order->customer_phone }}</span>
                            @endif
                        </td>
                        <td class="px-5 py-4">
                            @if($order->items->count() > 0)
                                <div class="space-y-1">
                                    @foreach($order->items->take(2) as $item)
                                    <div class="text-sm">
                                        <span class="font-medium text-gray-800 dark:text-white/90">{{ $item->product_name }}</span>
                                        <span class="text-gray-500">× {{ $item->qty }}</span>
                                    </div>
                                    @endforeach
                                    @if($order->items->count() > 2)
                                    <span class="text-xs text-gray-500">+{{ $order->items->count() - 2 }} item lainnya</span>
                                    @endif
                                </div>
                            @else
                                <span class="text-gray-400 text-sm">-</span>
                            @endif
                        </td>
                        <td class="px-5 py-4">
                            @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) {
            // Prioritaskan unit item utama.
            // Tujuannya: minimal order Rp 10.000 hanya berlaku jika unit item memang meter/m2.
            // Contoh: jika item 1 pcs punya ukuran 50x30, tetap dihitung pcs, bukan dipaksa minimal meter/m2.
            $unit = $__normalizeUnit($item->unit ?? $item->size_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);
        };

                                $displayTotal = $__orderDisplayTotal($order);
                                $remaining = $__orderDisplayRemaining($order);
                                $isPartial = $order->isPartiallyPaid() || ($remaining > 0 && $remaining < $displayTotal);
                            @endphp
                            @if($isPartial)
                            <div>
                                <span class="text-xs text-gray-500 line-through">Rp {{ number_format($displayTotal, 0, ',', '.') }}</span>
                                <span class="text-lg font-bold text-amber-500">Rp {{ number_format($remaining, 0, ',', '.') }}</span>
                            </div>
                            @else
                            <span class="text-lg font-bold text-brand-500">Rp {{ number_format($displayTotal, 0, ',', '.') }}</span>
                            @endif
                        </td>
                        <td class="px-5 py-4">
                            <a href="{{ route('kasir.show', $order) }}" class="inline-flex items-center gap-1.5 rounded-lg px-4 py-2 text-sm font-medium text-white {{ $order->isPartiallyPaid() ? 'bg-amber-500 hover:bg-amber-600' : 'bg-success-500 hover:bg-success-600' }}">
                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                                {{ $order->isPartiallyPaid() ? 'Bayar Sisa' : 'Bayar' }}
                            </a>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="px-5 py-8 text-center text-sm text-gray-500 dark:text-gray-400">Tidak ada tagihan pending</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

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