@extends('layouts.app')

@section('content')
    @php
        $normalizeUnit = function ($unit) {
            $unit = strtolower(trim((string) $unit));

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

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

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

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

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

        $applyMinimumAndRounding = function ($amount) {
            $amount = max((float) $amount, 0);
            $minimumOrder = 10000;
            $roundTo = 1000;

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

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

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

        $calculateItemSubtotal = function ($item) use ($normalizeUnit, $applyMinimumAndRounding) {
            $unit = $normalizeUnit($item->size_unit ?? 'lembar');
            $qty = max((float) ($item->qty ?? 1), 0);
            $basePrice = max((float) ($item->base_price ?? 0), 0);
            $sizeValue = max((float) ($item->size_value ?? 1), 0);
            $storedSubtotal = max((float) ($item->subtotal ?? 0), 0);

            // Wajib utamakan subtotal final yang tersimpan.
            // Setelah ada minimal order + pembulatan, angka tampilan juga dipaksa rapi:
            // minimal Rp 10.000 dan pembulatan ke atas Rp 1.000.
            if ($storedSubtotal > 0) {
                return round($applyMinimumAndRounding($storedSubtotal), 2);
            }

            if (in_array($unit, ['m2', 'meter'], true)) {
                return round($applyMinimumAndRounding($basePrice * $sizeValue * $qty), 2);
            }

            return round($applyMinimumAndRounding($basePrice * $qty), 2);
        };

        $activeFilters = collect([
            'search' => request('search'),
            'status' => request('status'),
            'production' => request('production'),
            'pickup' => request('pickup'),
            'date' => request('date'),
        ])->filter(fn ($v) => filled($v));

        $filtersCount = $activeFilters->count();

        $hint = $filtersCount > 0
            ? "Saat ini ada {$filtersCount} filter aktif. Untuk hasil lebih spesifik, kombinasikan filter seperti Status Bayar + Produksi + Tanggal."
            : "Belum ada filter aktif. Untuk memecah data lebih cepat, mulai dari Status Bayar atau Tanggal lalu tambah filter Produksi/Pengambilan.";
    @endphp

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

    @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

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

    <div class="mb-5 rounded-2xl border border-brand-200 bg-brand-50 p-5 dark:border-brand-900/40 dark:bg-brand-900/10">
        <div class="flex items-start gap-4">
            <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-500 text-white">
                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
                </svg>
            </div>

            <div class="flex-1">
                <div class="flex flex-wrap items-center gap-2">
                    <h4 class="text-sm font-semibold text-gray-900 dark:text-white/90">AI Smart Insight</h4>

                    @if($filtersCount > 0)
                        <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">
                            Filter aktif: {{ $filtersCount }}
                        </span>
                    @else
                        <span class="rounded-full bg-white/80 px-2 py-0.5 text-xs font-medium text-gray-700 dark:bg-white/10 dark:text-white/70">
                            Mode: Semua Order
                        </span>
                    @endif
                </div>

                <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                    {{ $hint }}
                </p>

                <div class="mt-3 flex flex-wrap items-center gap-2">
                    <span class="inline-flex items-center rounded-lg bg-white px-2.5 py-1 text-xs font-medium text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                        Tip cepat: cari <span class="mx-1 font-semibold">invoice</span> / <span class="mx-1 font-semibold">nama instansi / pelanggan</span> di kolom “Cari”.
                    </span>

                    @if($filtersCount === 0)
                        <span class="inline-flex items-center rounded-lg bg-warning-50 px-2.5 py-1 text-xs font-medium text-warning-700 ring-1 ring-warning-200 dark:bg-warning-900/20 dark:text-warning-200 dark:ring-warning-900/40">
                            Saranku: pilih “Status Bayar” dulu untuk memecah data.
                        </span>
                    @endif
                </div>
            </div>
        </div>
    </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 flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Daftar Order</h3>

                <a href="{{ route('orders.create') }}"
                    class="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600">
                    <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                    </svg>
                    Buat Order
                </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="w-full sm:w-auto sm:min-w-48">
                    <x-form.input
                        name="search"
                        label="Cari"
                        placeholder="Invoice/Instansi/Pelanggan/File..."
                        :value="request('search')"
                    />
                </div>

                <div class="w-full sm:w-auto sm:min-w-36">
                    <x-form.select
                        name="status"
                        label="Status Bayar"
                        placeholder="Semua"
                        :value="request('status')"
                        :options="['unpaid' => 'Belum Bayar', 'partial' => 'Cicilan', 'paid' => 'Lunas']"
                    />
                </div>

                <div class="w-full sm:w-auto sm:min-w-36">
                    <x-form.select
                        name="production"
                        label="Status Produksi"
                        placeholder="Semua"
                        :value="request('production')"
                        :options="['pending' => 'Pending', 'proses_cetak' => 'Proses Cetak', 'finishing' => 'Finishing', 'selesai' => 'Selesai']"
                    />
                </div>

                <div class="w-full sm:w-auto sm:min-w-36">
                    <x-form.select
                        name="pickup"
                        label="Pengambilan"
                        placeholder="Semua"
                        :value="request('pickup')"
                        :options="['not_picked_up' => 'Belum Diambil', 'picked_up' => 'Sudah Diambil']"
                    />
                </div>

                <div class="w-full sm:w-auto">
                    <x-form.date-picker
                        name="date"
                        label="Tanggal"
                        placeholder="Pilih tanggal"
                        :defaultDate="request('date')"
                    />
                </div>

                <button type="submit"
                    class="h-11 rounded-lg bg-gray-100 px-4 text-sm font-medium text-gray-700 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                    Filter
                </button>

                <a href="{{ route('orders.index') }}"
                    class="flex h-11 items-center rounded-lg border border-gray-300 px-4 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800">
                    Reset
                </a>
            </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">Instansi / Pelanggan</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Ringkasan 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">Pembayaran</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Produksi</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Pengambilan</th>
                        <th class="px-5 py-3 text-left text-sm font-medium text-gray-500 dark:text-gray-400">Aksi</th>
                    </tr>
                </thead>

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

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

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

                            $extraItemsCount = max($activeItems->count() - 1, 0);

                            $sizeText = $summarySizeDescription ?: '-';

                            $qtyText = '-';
                            if (!is_null($summaryQty) && $summaryQty !== '') {
                                $qtyText = $formatQty($summaryQty);
                                if (!empty($summaryUnit)) {
                                    $qtyText .= ' ' . ($summaryUnit === 'm2' ? 'm²' : $summaryUnit);
                                }
                            } elseif (!empty($order->qty)) {
                                $qtyText = $formatQty($order->qty);
                            }

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

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

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

                        <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">
                                    <a href="{{ route('orders.show', $order) }}"
                                        class="text-sm font-medium text-brand-600 hover:text-brand-700 hover:underline dark:text-brand-400 dark:hover:text-brand-300">
                                        {{ $order->invoice_number }}
                                    </a>

                                    @if($order->is_credit)
                                        <span class="inline-flex rounded-full px-2 py-0.5 text-xs font-medium bg-warning-100 text-warning-700 dark:bg-warning-500/20 dark:text-warning-400">
                                            Piutang
                                        </span>
                                    @endif
                                </div>

                                <span class="text-xs text-gray-500">
                                    {{ $order->designer->name ?? '-' }}
                                </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">
                                <span class="text-sm font-medium text-gray-800 dark:text-white/90">
                                    {{ $summaryFileName }}
                                </span>

                                <br>
                                <span class="text-xs text-gray-500">
                                    {{ $sizeText }} @if($qtyText !== '-') | {{ $qtyText }} @endif
                                </span>

                                @if($extraItemsCount > 0)
                                    <br>
                                    <span class="inline-flex mt-1 rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-700 dark:bg-gray-800 dark:text-gray-300">
                                        +{{ $extraItemsCount }} item lagi
                                    </span>
                                @endif
                            </td>

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

                                @if($hasM2Item)
                                    <br>
                                    <span class="text-[11px] text-brand-600 dark:text-brand-400">
                                        hitung ukuran × harga/m²
                                    </span>
                                @endif
                            </td>

                            <td class="px-5 py-4">
                                <span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium {{ $order->getPaymentStatusBadgeClass() }}">
                                    {{ $order->getPaymentStatusLabel() }}
                                </span>
                            </td>

                            <td class="px-5 py-4">
                                <span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium {{ $order->getProductionStatusBadgeClass() }}">
                                    {{ $order->getProductionStatusLabel() }}
                                </span>
                            </td>

                            <td class="px-5 py-4">
                                <span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium {{ $order->getPickupStatusBadgeClass() }}">
                                    {{ $order->getPickupStatusLabel() }}
                                </span>
                            </td>

                            <td class="px-5 py-4">
                                <div class="relative" x-data="{ open: false }">
                                    <button
                                        @click="open = !open"
                                        @click.outside="open = false"
                                        class="inline-flex items-center gap-1.5 rounded-lg border border-gray-300 bg-white px-3 py-1.5 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">
                                        <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 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
                                        </svg>
                                        Aksi
                                        <svg class="size-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                                        </svg>
                                    </button>

                                    <div
                                        x-show="open"
                                        x-transition
                                        class="absolute right-0 z-50 mt-1 w-48 rounded-lg border border-gray-200 bg-white py-1 shadow-lg dark:border-gray-700 dark:bg-gray-800"
                                        style="display:none;"
                                    >
                                        <a href="{{ route('orders.show', $order) }}"
                                            class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700">
                                            <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>
                                            Lihat Detail
                                        </a>

                                        @if($order->isUnpaid())
                                            <a href="{{ route('orders.edit', $order) }}"
                                                class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700">
                                                <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                </svg>
                                                Edit Order
                                            </a>
                                        @endif

                                        <div class="my-1 border-t border-gray-200 dark:border-gray-700"></div>

                                        @if($order->canPrintSPK())
                                            <a href="{{ route('print.spk', $order) }}" target="_blank"
                                                class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700">
                                                <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>
                                                Cetak SPK
                                            </a>
                                        @endif

                                        @if($order->isPaid())
                                            <a href="{{ route('print.nota', $order) }}" target="_blank"
                                                class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700">
                                                <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>
                                                Cetak Nota
                                            </a>

                                            <a href="{{ route('print.faktur', $order) }}" target="_blank"
                                                class="flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 dark:text-gray-300 dark:hover:bg-gray-700">
                                                <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 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>
                                                Cetak Faktur
                                            </a>
                                        @endif

                                        @if($order->canMarkAsPickedUp())
                                            <div class="my-1 border-t border-gray-200 dark:border-gray-700"></div>
                                            <form action="{{ route('orders.mark-picked-up', $order) }}" method="POST">
                                                @csrf
                                                <button type="submit"
                                                    class="flex w-full items-center gap-2 px-4 py-2 text-sm text-success-600 hover:bg-success-50 dark:text-success-400 dark:hover:bg-success-500/10">
                                                    <svg class="size-4" 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>
                                                    Tandai Sudah Diambil
                                                </button>
                                            </form>
                                        @endif
                                    </div>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="8" class="px-5 py-8 text-center text-sm text-gray-500 dark:text-gray-400">
                                Tidak ada data order
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

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