@extends('layouts.app')

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

    @php
        /*
        |--------------------------------------------------------------------------
        | Sinkron Nominal Laporan Omset
        |--------------------------------------------------------------------------
        | Aturan:
        | - Minimal order/item Rp10.000 hanya untuk meter/m²
        | - Selain meter/m² hanya dibulatkan ke atas Rp1.000
        | - Omset bersih tidak termasuk PPN
        | - PPN tetap dipisah
        | - Tidak memakai total mentah jika data item tersedia
        */

        $minimumOrder = 10000;
        $roundTo = 1000;

        $syncRoundAmount = function ($amount, bool $applyMinimum = false) use ($minimumOrder, $roundTo) {
            $amount = (float) ($amount ?? 0);

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

            // Minimal Rp10.000 hanya berlaku untuk item meter/m².
            if ($applyMinimum && $amount < $minimumOrder) {
                $amount = $minimumOrder;
            }

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

        $syncNormalizeUnit = function ($unit) {
            $unit = strtolower(trim((string) $unit));

            if (in_array($unit, ['m2', 'm²', 'meter2', 'meter persegi', 'per meter persegi'], true)) {
                return 'm2';
            }

            if (in_array($unit, ['meter', 'm', 'per meter'], true)) {
                return 'meter';
            }

            return $unit ?: 'lembar';
        };

        $syncOrderItems = function ($order) {
            if (!$order) {
                return collect();
            }

            if (method_exists($order, 'relationLoaded') && $order->relationLoaded('items')) {
                return collect($order->items ?? []);
            }

            if (isset($order->items) && is_iterable($order->items)) {
                return collect($order->items);
            }

            return collect();
        };

        $syncItemSubtotal = function ($item) use ($syncRoundAmount, $syncNormalizeUnit) {
            if (!$item) {
                return 0;
            }

            $unit = $syncNormalizeUnit($item->size_unit ?? $item->unit ?? 'lembar');
            $isMeterItem = in_array($unit, ['m2', 'meter'], true);

            $rawSubtotal = $item->display_subtotal
                ?? $item->report_subtotal
                ?? $item->subtotal
                ?? null;

            if ($rawSubtotal === null) {
                $qty = max((float) ($item->qty ?? 1), 0);
                $price = max((float) ($item->price ?? $item->unit_price ?? 0), 0);
                $sizeValue = max((float) ($item->size_value ?? 0), 0);

                if ($isMeterItem) {
                    $rawSubtotal = $price * max($sizeValue, 1) * max($qty, 1);
                } else {
                    $rawSubtotal = $price * max($qty, 1);
                }
            }

            return $syncRoundAmount($rawSubtotal, $isMeterItem);
        };

        $syncOrderNetTotal = function ($order) use ($syncOrderItems, $syncItemSubtotal, $syncRoundAmount) {
            if (!$order) {
                return 0;
            }

            $items = $syncOrderItems($order);

            if ($items->count() > 0) {
                return (float) $items->sum(fn ($item) => $syncItemSubtotal($item));
            }

            $rawTotal = (float) (
                $order->display_total_price
                ?? $order->report_total_price
                ?? $order->total_before_ppn
                ?? $order->subtotal
                ?? $order->total_price
                ?? 0
            );

            $usePpn = (bool) ($order->use_ppn ?? false);
            $ppnAmount = (float) ($order->ppn_amount ?? 0);

            // Jika total lama sudah termasuk PPN, keluarkan dulu PPN agar omset bersih tidak ikut pajak.
            if ($usePpn && $ppnAmount > 0 && $rawTotal >= $ppnAmount) {
                $rawTotal -= $ppnAmount;
            }

            return $syncRoundAmount($rawTotal, false);
        };

        $syncOrderPpn = function ($order, $netTotal) {
            if (!$order || !(bool) ($order->use_ppn ?? false)) {
                return 0;
            }

            $storedPpn = (float) ($order->ppn_amount ?? 0);

            if ($storedPpn > 0) {
                return $storedPpn;
            }

            $rate = (float) ($order->ppn_rate ?? 0);

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

            return round(((float) $netTotal) * ($rate / 100));
        };

        $syncPaidAmount = function ($order) {
            if (!$order) {
                return 0;
            }

            if (method_exists($order, 'relationLoaded') && $order->relationLoaded('payments')) {
                return (float) collect($order->payments ?? [])->sum('amount');
            }

            if (isset($order->payments) && is_iterable($order->payments)) {
                return (float) collect($order->payments)->sum('amount');
            }

            return (float) ($order->paid_amount ?? 0);
        };

        $syncOrderDisplay = function ($order) use ($syncOrderNetTotal, $syncOrderPpn, $syncPaidAmount) {
            $netTotal = (float) $syncOrderNetTotal($order);
            $ppnAmount = (float) $syncOrderPpn($order, $netTotal);
            $invoiceTotal = $netTotal + $ppnAmount;
            $paidAmount = (float) $syncPaidAmount($order);
            $remaining = max($invoiceTotal - $paidAmount, 0);

            return [
                'net_total' => $netTotal,
                'ppn_amount' => $ppnAmount,
                'invoice_total' => $invoiceTotal,
                'paid_amount' => $paidAmount,
                'remaining' => $remaining,
                'is_receivable' => $remaining > 0,
                'revenue_amount' => $netTotal,
            ];
        };

        $dailyData = collect($dailyData ?? []);
        $orders = $orders ?? collect();
        $machines = collect($machines ?? []);
        $categories = collect($categories ?? []);

        $ordersCollection = method_exists($orders, 'getCollection')
            ? collect($orders->getCollection())
            : collect($orders ?? []);

        $canRebuildSummaryFromOrders = $ordersCollection->count() > 0
            && (!method_exists($orders, 'total') || (int) $orders->total() === (int) $ordersCollection->count());

        if ($canRebuildSummaryFromOrders) {
            $displayOrders = $ordersCollection->map(function ($order) use ($syncOrderDisplay) {
                $display = $syncOrderDisplay($order);

                return (object) [
                    'order' => $order,
                    'date' => $order->paid_at ?? $order->created_at ?? null,
                    'customer_name' => $order->customer_name ?? '-',
                    'net_total' => $display['net_total'],
                    'ppn_amount' => $display['ppn_amount'],
                    'invoice_total' => $display['invoice_total'],
                    'remaining' => $display['remaining'],
                    'is_receivable' => $display['is_receivable'],
                    'revenue_amount' => $display['revenue_amount'],
                    'qty' => (float) ($order->report_total_qty ?? $order->total_qty ?? 0),
                ];
            });

            $paidRows = $displayOrders->filter(fn ($row) => !$row->is_receivable);
            $receivableRows = $displayOrders->filter(fn ($row) => $row->is_receivable);

            $paidRevenue = (float) $paidRows->sum('net_total');
            $receivableRevenue = (float) $receivableRows->sum('net_total');
            $totalRevenue = $paidRevenue + $receivableRevenue;
            $totalPpn = (float) $displayOrders->sum('ppn_amount');
            $paidPpn = (float) $paidRows->sum('ppn_amount');
            $totalInvoice = (float) $displayOrders->sum('invoice_total');

            $totalOrders = (int) $displayOrders->count();
            $paidOrders = (int) $paidRows->count();
            $receivableOrders = (int) $receivableRows->count();
            $totalQty = (float) $displayOrders->sum('qty');

            $paidCustomers = $paidRows
                ->groupBy('customer_name')
                ->map(fn ($rows, $name) => [
                    'customer_name' => $name,
                    'total_orders' => collect($rows)->count(),
                    'total_amount' => collect($rows)->sum('net_total'),
                ])
                ->sortByDesc('total_amount')
                ->values();

            $receivableCustomers = $receivableRows
                ->groupBy('customer_name')
                ->map(fn ($rows, $name) => [
                    'customer_name' => $name,
                    'total_orders' => collect($rows)->count(),
                    'total_amount' => collect($rows)->sum('net_total'),
                ])
                ->sortByDesc('total_amount')
                ->values();

            $dailyData = $displayOrders
                ->groupBy(function ($row) {
                    return !empty($row->date)
                        ? \Carbon\Carbon::parse($row->date)->format('Y-m-d')
                        : 'unknown';
                })
                ->map(function ($rows, $date) {
                    return (object) [
                        'date' => $date === 'unknown' ? null : $date,
                        'total_revenue' => collect($rows)->sum('net_total'),
                        'total_orders' => collect($rows)->count(),
                    ];
                })
                ->sortByDesc('date')
                ->values();
        } else {
            $paidRevenue = (float) ($summary['paid_revenue'] ?? 0);
            $receivableRevenue = (float) ($summary['receivable_revenue'] ?? 0);
            $totalRevenue = (float) ($summary['total_revenue'] ?? 0);
            $totalPpn = (float) ($summary['total_ppn'] ?? 0);
            $paidPpn = (float) ($summary['paid_ppn'] ?? 0);
            $totalInvoice = (float) ($summary['total_invoice'] ?? ($totalRevenue + $totalPpn));

            $totalOrders = (int) ($summary['total_orders'] ?? 0);
            $paidOrders = (int) ($summary['paid_orders'] ?? 0);
            $receivableOrders = (int) ($summary['receivable_orders'] ?? 0);
            $totalQty = (float) ($summary['total_qty'] ?? 0);

            $paidCustomers = collect($paidCustomers ?? []);
            $receivableCustomers = collect($receivableCustomers ?? []);
        }

        $paidCustomers = collect($paidCustomers ?? []);
        $receivableCustomers = collect($receivableCustomers ?? []);

        $paidCustomersCount = (int) ($summary['paid_customers'] ?? $paidCustomers->count());
        $receivableCustomersCount = (int) ($summary['receivable_customers'] ?? $receivableCustomers->count());

        $paidPercent = $totalRevenue > 0 ? round(($paidRevenue / $totalRevenue) * 100, 1) : 0;
        $receivablePercent = $totalRevenue > 0 ? round(($receivableRevenue / $totalRevenue) * 100, 1) : 0;
        $avgOrderValue = $totalOrders > 0 ? $totalRevenue / $totalOrders : 0;

        $bestDay = $dailyData->sortByDesc(fn ($item) => (float) ($item->total_revenue ?? 0))->first();
        $bestDayLabel = $bestDay && !empty($bestDay->date)
            ? \Carbon\Carbon::parse($bestDay->date)->translatedFormat('d M Y')
            : '-';
        $bestDayRevenue = (float) ($bestDay->total_revenue ?? 0);
        $bestDayOrders = (int) ($bestDay->total_orders ?? 0);

        $monthlyData = $dailyData
            ->groupBy(function ($item) {
                return !empty($item->date)
                    ? \Carbon\Carbon::parse($item->date)->format('Y-m')
                    : 'unknown';
            })
            ->map(function ($items, $monthKey) {
                $totalRevenueMonth = collect($items)->sum(fn ($row) => (float) ($row->total_revenue ?? 0));
                $totalOrdersMonth = collect($items)->sum(fn ($row) => (int) ($row->total_orders ?? 0));
                $totalDaysMonth = collect($items)->count();

                return (object) [
                    'month_key' => $monthKey,
                    'month_label' => $monthKey !== 'unknown'
                        ? \Carbon\Carbon::createFromFormat('Y-m', $monthKey)->translatedFormat('F Y')
                        : '-',
                    'total_revenue' => $totalRevenueMonth,
                    'total_orders' => $totalOrdersMonth,
                    'total_days' => $totalDaysMonth,
                    'avg_daily_revenue' => $totalDaysMonth > 0 ? $totalRevenueMonth / $totalDaysMonth : 0,
                ];
            })
            ->sortByDesc('month_key')
            ->values();

        $bestMonth = $monthlyData->sortByDesc('total_revenue')->first();
        $bestMonthLabel = $bestMonth->month_label ?? '-';
        $bestMonthRevenue = (float) ($bestMonth->total_revenue ?? 0);

        $topPaidCustomer = $paidCustomers->first();
        $topPaidCustomerName = is_array($topPaidCustomer)
            ? ($topPaidCustomer['customer_name'] ?? '-')
            : ($topPaidCustomer->customer_name ?? '-');
        $topPaidCustomerAmount = (float) (
            is_array($topPaidCustomer)
                ? ($topPaidCustomer['total_amount'] ?? 0)
                : ($topPaidCustomer->total_amount ?? 0)
        );

        $topReceivableCustomer = $receivableCustomers->first();
        $topReceivableCustomerName = is_array($topReceivableCustomer)
            ? ($topReceivableCustomer['customer_name'] ?? '-')
            : ($topReceivableCustomer->customer_name ?? '-');
        $topReceivableCustomerAmount = (float) (
            is_array($topReceivableCustomer)
                ? ($topReceivableCustomer['total_amount'] ?? 0)
                : ($topReceivableCustomer->total_amount ?? 0)
        );
    @endphp    @endphp

    <style>
        .report-card {
            background: #fff;
            border: 1px solid rgba(17, 24, 39, .08);
            border-radius: 20px;
        }
        .dark .report-card {
            background: rgba(255,255,255,.03);
            border-color: rgba(255,255,255,.08);
        }
        .mini-card {
            background: linear-gradient(180deg, rgba(255,255,255,1) 0%, rgba(249,250,251,1) 100%);
            border: 1px solid rgba(17,24,39,.06);
            border-radius: 18px;
        }
        .dark .mini-card {
            background: rgba(255,255,255,.04);
            border-color: rgba(255,255,255,.06);
        }
        .soft-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            border-radius: 999px;
            padding: 6px 10px;
            font-size: 12px;
            font-weight: 700;
            background: rgba(99,102,241,.08);
            color: #4f46e5;
        }
        .dark .soft-badge {
            background: rgba(99,102,241,.14);
            color: #a5b4fc;
        }
        .progress-track {
            height: 10px;
            border-radius: 999px;
            overflow: hidden;
            background: rgba(148,163,184,.18);
        }
        .progress-paid {
            height: 100%;
            background: linear-gradient(90deg, #10b981, #34d399);
        }
        .progress-rec {
            height: 100%;
            background: linear-gradient(90deg, #f59e0b, #fbbf24);
        }
        .table-clean thead th {
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: .08em;
            font-weight: 700;
            color: #64748b;
        }
        .dark .table-clean thead th {
            color: #94a3b8;
        }
        .table-clean tbody tr:hover {
            background: rgba(99,102,241,.04);
        }
        .dark .table-clean tbody tr:hover {
            background: rgba(255,255,255,.03);
        }
        .status-paid {
            background: rgba(16,185,129,.12);
            color: #059669;
            border: 1px solid rgba(16,185,129,.22);
        }
        .status-rec {
            background: rgba(245,158,11,.12);
            color: #d97706;
            border: 1px solid rgba(245,158,11,.22);
        }
        .dark .status-paid {
            background: rgba(16,185,129,.12);
            color: #6ee7b7;
            border: 1px solid rgba(16,185,129,.24);
        }
        .dark .status-rec {
            background: rgba(245,158,11,.12);
            color: #fcd34d;
            border: 1px solid rgba(245,158,11,.24);
        }
    </style>

    <div class="space-y-6">
        {{-- Ringkasan utama --}}
        <div class="report-card p-5 md:p-6">
            <div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                <div>
                    <div class="soft-badge">Dashboard Omset Sinkron</div>
                    <h2 class="mt-3 text-2xl font-bold text-gray-900 dark:text-white">
                        Ringkasan Omset Periode
                    </h2>
                    <p class="mt-2 max-w-3xl text-sm leading-6 text-gray-600 dark:text-gray-400">
                        Nilai omset utama pada halaman ini sudah menjadi <span class="font-semibold">omset bersih tanpa PPN</span>.
                        PPN dipisahkan sebagai pajak keluaran agar laporan penjualan tidak tercampur pajak.
                    </p>
                </div>

                <div class="grid grid-cols-2 gap-3 sm:grid-cols-5">
                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Omset Bersih</div>
                        <div class="mt-2 text-xl font-extrabold text-gray-900 dark:text-white">
                            Rp {{ number_format($totalRevenue, 0, ',', '.') }}
                        </div>
                        <div class="mt-1 text-[11px] text-gray-500 dark:text-gray-400">Tidak termasuk PPN</div>
                    </div>

                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">PPN Keluaran</div>
                        <div class="mt-2 text-xl font-extrabold text-blue-600 dark:text-blue-400">
                            Rp {{ number_format($totalPpn, 0, ',', '.') }}
                        </div>
                        <div class="mt-1 text-[11px] text-gray-500 dark:text-gray-400">Dipisah dari omset</div>
                    </div>

                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Total Order</div>
                        <div class="mt-2 text-xl font-extrabold text-gray-900 dark:text-white">
                            {{ number_format($totalOrders, 0, ',', '.') }}
                        </div>
                    </div>

                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Total Qty</div>
                        <div class="mt-2 text-xl font-extrabold text-gray-900 dark:text-white">
                            {{ number_format($totalQty, 0, ',', '.') }}
                        </div>
                    </div>

                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Rata-rata / Order</div>
                        <div class="mt-2 text-xl font-extrabold text-gray-900 dark:text-white">
                            Rp {{ number_format($avgOrderValue, 0, ',', '.') }}
                        </div>
                        <div class="mt-1 text-[11px] text-gray-500 dark:text-gray-400">Bersih tanpa PPN</div>
                    </div>
                </div>
            </div>

            <div class="mt-6 grid grid-cols-1 gap-4 lg:grid-cols-2">
                <div class="mini-card p-4">
                    <div class="flex items-center justify-between gap-3">
                        <div>
                            <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Sudah Lunas</div>
                            <div class="mt-2 text-2xl font-bold text-emerald-600 dark:text-emerald-400">
                                Rp {{ number_format($paidRevenue, 0, ',', '.') }}
                            </div>
                            @if($paidPpn > 0)
                                <div class="mt-1 text-xs text-blue-600 dark:text-blue-400">
                                    PPN terpisah: Rp {{ number_format($paidPpn, 0, ',', '.') }}
                                </div>
                            @endif
                        </div>
                        <div class="text-right text-sm text-gray-500 dark:text-gray-400">
                            <div>{{ $paidOrders }} order</div>
                            <div>{{ $paidPercent }}%</div>
                        </div>
                    </div>

                    <div class="mt-4 progress-track">
                        <div class="progress-paid" style="width: {{ min($paidPercent, 100) }}%"></div>
                    </div>

                    <div class="mt-2 text-xs text-gray-500 dark:text-gray-400">
                        {{ $paidCustomersCount }} pelanggan
                    </div>
                </div>

                <div class="mini-card p-4">
                    <div class="flex items-center justify-between gap-3">
                        <div>
                            <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Piutang</div>
                            <div class="mt-2 text-2xl font-bold text-amber-600 dark:text-amber-400">
                                Rp {{ number_format($receivableRevenue, 0, ',', '.') }}
                            </div>
                        </div>
                        <div class="text-right text-sm text-gray-500 dark:text-gray-400">
                            <div>{{ $receivableOrders }} order</div>
                            <div>{{ $receivablePercent }}%</div>
                        </div>
                    </div>

                    <div class="mt-4 progress-track">
                        <div class="progress-rec" style="width: {{ min($receivablePercent, 100) }}%"></div>
                    </div>

                    <div class="mt-2 text-xs text-gray-500 dark:text-gray-400">
                        {{ $receivableCustomersCount }} pelanggan
                    </div>
                </div>
            </div>
        </div>

        {{-- Filter --}}
        <div class="report-card p-5 md:p-6">
            <div class="mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Filter Laporan</h3>
                <p class="text-sm text-gray-500 dark:text-gray-400">Saring data berdasarkan periode, mesin, dan kategori.</p>
            </div>

            <form method="GET" class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-5">
                <div>
                    <x-form.date-picker
                        name="start_date"
                        label="Dari Tanggal"
                        placeholder="Pilih tanggal"
                        :defaultDate="$startDate"
                    />
                </div>

                <div>
                    <x-form.date-picker
                        name="end_date"
                        label="Sampai Tanggal"
                        placeholder="Pilih tanggal"
                        :defaultDate="$endDate"
                    />
                </div>

                <div>
                    <x-form.select name="machine_id" label="Mesin" placeholder="Semua Mesin">
                        @foreach($machines as $machine)
                            <option value="{{ $machine->id }}" {{ request('machine_id') == $machine->id ? 'selected' : '' }}>
                                {{ $machine->name }}
                            </option>
                        @endforeach
                    </x-form.select>
                </div>

                <div>
                    <x-form.select name="category_id" label="Kategori" placeholder="Semua Kategori">
                        @foreach($categories as $category)
                            <option value="{{ $category->id }}" {{ request('category_id') == $category->id ? 'selected' : '' }}>
                                {{ $category->name }}
                            </option>
                        @endforeach
                    </x-form.select>
                </div>

                <div class="flex items-end gap-2">
                    <button type="submit" class="h-11 flex-1 rounded-xl bg-brand-500 px-5 text-sm font-bold text-white hover:bg-brand-600">
                        Terapkan
                    </button>
                    <a href="{{ route('reports.sales') }}"
                        class="h-11 flex items-center justify-center rounded-xl border border-gray-300 px-4 text-sm font-bold text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300">
                        Reset
                    </a>
                </div>
            </form>
        </div>

        {{-- Harian dan Bulanan --}}
        <div class="grid grid-cols-1 gap-6 xl:grid-cols-2">
            <div class="report-card p-5 md:p-6">
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Omset Harian</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Ringkasan omset per hari pada periode terpilih.</p>
                    </div>
                    <span class="soft-badge">{{ $dailyData->count() }} hari</span>
                </div>

                <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Hari Terbaik</div>
                        <div class="mt-2 text-lg font-bold text-gray-900 dark:text-white">{{ $bestDayLabel }}</div>
                        <div class="mt-1 text-sm font-semibold text-emerald-600 dark:text-emerald-400">
                            Rp {{ number_format($bestDayRevenue, 0, ',', '.') }}
                        </div>
                        <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                            {{ number_format($bestDayOrders, 0, ',', '.') }} order
                        </div>
                    </div>

                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Rata-rata Harian</div>
                        <div class="mt-2 text-lg font-bold text-gray-900 dark:text-white">
                            Rp {{ number_format($dailyData->count() > 0 ? $dailyData->avg(fn ($row) => (float) ($row->total_revenue ?? 0)) : 0, 0, ',', '.') }}
                        </div>
                    </div>
                </div>

                <div class="mt-5 overflow-x-auto">
                    <table class="table-clean w-full min-w-[520px]">
                        <thead>
                            <tr class="border-b border-gray-200 dark:border-gray-800">
                                <th class="py-3 text-left">Tanggal</th>
                                <th class="py-3 text-right">Order</th>
                                <th class="py-3 text-right">Omset Bersih</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                            @forelse($dailyData as $day)
                                <tr>
                                    <td class="py-3 text-sm font-medium text-gray-800 dark:text-white/90">
                                        {{ !empty($day->date) ? \Carbon\Carbon::parse($day->date)->translatedFormat('d M Y') : '-' }}
                                    </td>
                                    <td class="py-3 text-right text-sm text-gray-600 dark:text-gray-400">
                                        {{ (int) ($day->total_orders ?? 0) }}
                                    </td>
                                    <td class="py-3 text-right text-sm font-bold text-emerald-600 dark:text-emerald-400">
                                        Rp {{ number_format((float) ($day->total_revenue ?? 0), 0, ',', '.') }}
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="3" class="py-8 text-center text-sm text-gray-500 dark:text-gray-400">
                                        Tidak ada data harian.
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="report-card p-5 md:p-6">
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Omset Bulanan</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Rekap bulan dari data harian pada periode yang dipilih.</p>
                    </div>
                    <span class="soft-badge">{{ $monthlyData->count() }} bulan</span>
                </div>

                <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Bulan Terbaik</div>
                        <div class="mt-2 text-lg font-bold text-gray-900 dark:text-white">{{ $bestMonthLabel }}</div>
                        <div class="mt-1 text-sm font-semibold text-brand-600 dark:text-brand-400">
                            Rp {{ number_format($bestMonthRevenue, 0, ',', '.') }}
                        </div>
                    </div>

                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Rata-rata Bulanan</div>
                        <div class="mt-2 text-lg font-bold text-gray-900 dark:text-white">
                            Rp {{ number_format($monthlyData->count() > 0 ? $monthlyData->avg('total_revenue') : 0, 0, ',', '.') }}
                        </div>
                    </div>
                </div>

                <div class="mt-5 overflow-x-auto">
                    <table class="table-clean w-full min-w-[560px]">
                        <thead>
                            <tr class="border-b border-gray-200 dark:border-gray-800">
                                <th class="py-3 text-left">Bulan</th>
                                <th class="py-3 text-right">Hari</th>
                                <th class="py-3 text-right">Order</th>
                                <th class="py-3 text-right">Omset Bersih</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-800">
                            @forelse($monthlyData as $month)
                                <tr>
                                    <td class="py-3 text-sm font-medium text-gray-800 dark:text-white/90">
                                        {{ $month->month_label }}
                                    </td>
                                    <td class="py-3 text-right text-sm text-gray-600 dark:text-gray-400">
                                        {{ $month->total_days }}
                                    </td>
                                    <td class="py-3 text-right text-sm text-gray-600 dark:text-gray-400">
                                        {{ number_format($month->total_orders, 0, ',', '.') }}
                                    </td>
                                    <td class="py-3 text-right text-sm font-bold text-brand-600 dark:text-brand-400">
                                        Rp {{ number_format($month->total_revenue, 0, ',', '.') }}
                                    </td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="4" class="py-8 text-center text-sm text-gray-500 dark:text-gray-400">
                                        Tidak ada data bulanan.
                                    </td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        {{-- Insight pelanggan --}}
        <div class="grid grid-cols-1 gap-6 xl:grid-cols-2">
            <div class="report-card p-5 md:p-6">
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Pelanggan Lunas</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Pelanggan dengan transaksi lunas pada periode ini.</p>
                    </div>
                    <span class="soft-badge">{{ $paidCustomersCount }} pelanggan</span>
                </div>

                <div class="mb-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Top Customer</div>
                        <div class="mt-2 text-lg font-bold text-gray-900 dark:text-white">{{ $topPaidCustomerName }}</div>
                        <div class="mt-1 text-sm font-semibold text-emerald-600 dark:text-emerald-400">
                            Rp {{ number_format($topPaidCustomerAmount, 0, ',', '.') }}
                        </div>
                    </div>
                </div>

                <div class="space-y-3">
                    @forelse($paidCustomers->take(6) as $customer)
                        @php
                            $customerName = is_array($customer) ? ($customer['customer_name'] ?? '-') : ($customer->customer_name ?? '-');
                            $customerOrders = (int) (is_array($customer) ? ($customer['total_orders'] ?? 0) : ($customer->total_orders ?? 0));
                            $customerTotal = (float) (is_array($customer) ? ($customer['total_amount'] ?? 0) : ($customer->total_amount ?? 0));
                        @endphp
                        <div class="mini-card p-4">
                            <div class="flex items-center justify-between gap-4">
                                <div>
                                    <div class="text-sm font-bold text-gray-900 dark:text-white">{{ $customerName }}</div>
                                    <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{ $customerOrders }} order</div>
                                </div>
                                <div class="text-right text-sm font-bold text-emerald-600 dark:text-emerald-400">
                                    Rp {{ number_format($customerTotal, 0, ',', '.') }}
                                </div>
                            </div>
                        </div>
                    @empty
                        <div class="rounded-2xl border border-dashed border-gray-300 px-4 py-10 text-center text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400">
                            Belum ada data pelanggan lunas.
                        </div>
                    @endforelse
                </div>
            </div>

            <div class="report-card p-5 md:p-6">
                <div class="mb-4 flex items-center justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Pelanggan Piutang</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Pelanggan dengan sisa piutang pada periode ini.</p>
                    </div>
                    <span class="soft-badge">{{ $receivableCustomersCount }} pelanggan</span>
                </div>

                <div class="mb-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div class="mini-card p-4">
                        <div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">Top Customer</div>
                        <div class="mt-2 text-lg font-bold text-gray-900 dark:text-white">{{ $topReceivableCustomerName }}</div>
                        <div class="mt-1 text-sm font-semibold text-amber-600 dark:text-amber-400">
                            Rp {{ number_format($topReceivableCustomerAmount, 0, ',', '.') }}
                        </div>
                    </div>
                </div>

                <div class="space-y-3">
                    @forelse($receivableCustomers->take(6) as $customer)
                        @php
                            $customerName = is_array($customer) ? ($customer['customer_name'] ?? '-') : ($customer->customer_name ?? '-');
                            $customerOrders = (int) (is_array($customer) ? ($customer['total_orders'] ?? 0) : ($customer->total_orders ?? 0));
                            $customerTotal = (float) (is_array($customer) ? ($customer['total_amount'] ?? 0) : ($customer->total_amount ?? 0));
                        @endphp
                        <div class="mini-card p-4">
                            <div class="flex items-center justify-between gap-4">
                                <div>
                                    <div class="text-sm font-bold text-gray-900 dark:text-white">{{ $customerName }}</div>
                                    <div class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{ $customerOrders }} order</div>
                                </div>
                                <div class="text-right text-sm font-bold text-amber-600 dark:text-amber-400">
                                    Rp {{ number_format($customerTotal, 0, ',', '.') }}
                                </div>
                            </div>
                        </div>
                    @empty
                        <div class="rounded-2xl border border-dashed border-gray-300 px-4 py-10 text-center text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400">
                            Belum ada data pelanggan piutang.
                        </div>
                    @endforelse
                </div>
            </div>
        </div>

        {{-- Detail order --}}
        <div class="report-card overflow-hidden">
            <div class="flex flex-col gap-3 border-b border-gray-200 px-5 py-4 dark:border-gray-800 sm:flex-row sm:items-center sm:justify-between">
                <div>
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Detail Order Penjualan</h3>
                    <p class="text-sm text-gray-500 dark:text-gray-400">
                        Tabel detail untuk melihat kontribusi per order pada periode yang dipilih.
                    </p>
                </div>

                <a
                    href="{{ route('print.laporan', array_merge(['start_date' => $startDate, 'end_date' => $endDate], request()->only(['machine_id', 'category_id']))) }}"
                    target="_blank"
                    class="inline-flex items-center justify-center gap-2 rounded-xl bg-brand-500 px-4 py-2.5 text-sm font-bold text-white hover:bg-brand-600"
                >
                    Cetak
                </a>
            </div>

            <div class="overflow-x-auto">
                <table class="table-clean w-full min-w-[860px]">
                    <thead>
                        <tr class="border-b border-gray-200 bg-gray-50/70 dark:border-gray-800 dark:bg-gray-900/50">
                            <th class="px-5 py-3 text-left">Tanggal</th>
                            <th class="px-5 py-3 text-left">Invoice</th>
                            <th class="px-5 py-3 text-left">Pelanggan</th>
                            <th class="px-5 py-3 text-left">Status</th>
                            <th class="px-5 py-3 text-right">Nilai Invoice</th>
                            <th class="px-5 py-3 text-right">Nominal Omset</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                        @forelse($orders as $order)
                            @php
                                $displayOrder = $syncOrderDisplay($order);
                                $remainingBalance = (float) $displayOrder['remaining'];
                                $orderTotal = (float) $displayOrder['invoice_total'];
                                $nominalOmset = (float) $displayOrder['net_total'];
                                $isReceivable = $remainingBalance > 0;

                                $statusLabel = $isReceivable ? 'Piutang' : 'Lunas';
                                $statusClass = $isReceivable ? 'status-rec' : 'status-paid';
                                $tanggalTampil = $order->paid_at ?? $order->created_at ?? null;
                            @endphp

                            <tr>
                                <td class="px-5 py-4 text-sm text-gray-500 dark:text-gray-400">
                                    {{ $tanggalTampil ? $tanggalTampil->format('d/m/Y') : '-' }}
                                </td>
                                <td class="px-5 py-4">
                                    <a href="{{ route('orders.show', $order) }}" class="text-sm font-bold text-brand-600 hover:text-brand-700">
                                        {{ $order->invoice_number }}
                                    </a>
                                </td>
                                <td class="px-5 py-4 text-sm font-medium text-gray-800 dark:text-white/90">
                                    {{ $order->customer_name }}
                                </td>
                                <td class="px-5 py-4">
                                    <span class="inline-flex items-center rounded-full px-2.5 py-1 text-xs font-bold {{ $statusClass }}">
                                        {{ $statusLabel }}
                                    </span>
                                </td>
                                <td class="px-5 py-4 text-right text-sm font-bold text-gray-700 dark:text-gray-200">
                                    Rp {{ number_format($orderTotal, 0, ',', '.') }}
                                </td>
                                <td class="px-5 py-4 text-right text-sm font-bold {{ $isReceivable ? 'text-amber-600 dark:text-amber-400' : 'text-emerald-600 dark:text-emerald-400' }}">
                                    Rp {{ number_format($nominalOmset, 0, ',', '.') }}
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="px-5 py-12 text-center text-sm text-gray-500 dark:text-gray-400">
                                    Tidak ada data pada filter ini.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>

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