<x-admin-layout title="Dashboard" subtitle="Pusat pantau operasional harian, penjualan, request pelanggan, dan stok.">
    @php
        $money = fn ($value) => 'Rp '.number_format((float) $value, 0, ',', '.');
        $statusLabel = fn ($value) => str_replace('_', ' ', (string) $value);
        $statusTone = fn ($status) => match ($status) {
            'baru' => 'border-sky-200 bg-sky-50 text-sky-700',
            'proses' => 'border-amber-200 bg-amber-50 text-amber-700',
            'selesai', 'lunas', 'dikonversi' => 'border-emerald-200 bg-emerald-50 text-emerald-700',
            'diambil' => 'border-slate-200 bg-slate-50 text-slate-700',
            'pending', 'dp', 'direview' => 'border-orange-200 bg-orange-50 text-orange-700',
            'dibatalkan', 'rejected' => 'border-red-200 bg-red-50 text-red-700',
            default => 'border-slate-200 bg-slate-50 text-slate-700',
        };
        $totalStatus = max(1, (int) $statusCounts->sum());
        $totalPayments = max(1, (int) $paymentCounts->sum());
        $totalRequests = max(1, (int) $requestCounts->sum());
    @endphp

    <div class="mb-5 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div class="text-sm text-slate-500">Hari ini: {{ now()->format('d/m/Y H:i') }}</div>
        @if ($branches->isNotEmpty())
            <form class="flex items-center gap-2" method="get">
                <select name="branch_id" class="rounded-md border px-3 py-2 text-sm">
                    <option value="">Semua cabang</option>
                    @foreach ($branches as $branch)
                        <option value="{{ $branch->id }}" @selected((int) $branchId === (int) $branch->id)>{{ $branch->name }}</option>
                    @endforeach
                </select>
                <button class="rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white">Terapkan</button>
            </form>
        @endif
    </div>

    <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <a href="{{ route('reports.index') }}" class="rounded-lg bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
            <div class="flex items-center justify-between">
                <div class="text-sm text-slate-500">Penjualan Hari Ini</div>
                <span class="rounded-full bg-emerald-50 px-2 py-1 text-xs text-emerald-700">sales</span>
            </div>
            <div class="mt-2 text-2xl font-semibold">{{ $money($salesToday) }}</div>
            <div class="mt-2 text-xs text-slate-500">{{ $ordersToday }} order masuk hari ini</div>
        </a>
        <a href="{{ route('orders.index') }}" class="rounded-lg bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
            <div class="flex items-center justify-between">
                <div class="text-sm text-slate-500">Order Aktif</div>
                <span class="rounded-full bg-sky-50 px-2 py-1 text-xs text-sky-700">laundry</span>
            </div>
            <div class="mt-2 text-2xl font-semibold">{{ number_format($activeOrders, 0, ',', '.') }}</div>
            <div class="mt-2 text-xs text-slate-500">Belum berstatus diambil</div>
        </a>
        <a href="{{ route('customer-requests.index') }}" class="rounded-lg bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
            <div class="flex items-center justify-between">
                <div class="text-sm text-slate-500">Request Baru</div>
                <span class="rounded-full bg-amber-50 px-2 py-1 text-xs text-amber-700">customer</span>
            </div>
            <div class="mt-2 text-2xl font-semibold">{{ number_format($newRequests, 0, ',', '.') }}</div>
            <div class="mt-2 text-xs text-slate-500">Perlu direview admin</div>
        </a>
        <a href="{{ route('inventory.index') }}" class="rounded-lg bg-white p-5 shadow-sm transition hover:-translate-y-0.5 hover:shadow-md">
            <div class="flex items-center justify-between">
                <div class="text-sm text-slate-500">Stok Minimum</div>
                <span class="rounded-full bg-red-50 px-2 py-1 text-xs text-red-700">inventory</span>
            </div>
            <div class="mt-2 text-2xl font-semibold">{{ number_format($lowStockTotal, 0, ',', '.') }}</div>
            <div class="mt-2 text-xs text-slate-500">Item perlu dicek/pembelian</div>
        </a>
    </div>

    <div class="mt-4 grid gap-4 md:grid-cols-3">
        <div class="rounded-lg bg-white p-5 shadow-sm">
            <div class="text-sm text-slate-500">Omzet 7 Hari</div>
            <div class="mt-2 text-xl font-semibold">{{ $money($salesThisWeek) }}</div>
        </div>
        <div class="rounded-lg bg-white p-5 shadow-sm">
            <div class="text-sm text-slate-500">Lunas Hari Ini</div>
            <div class="mt-2 text-xl font-semibold">{{ $money($paidToday) }}</div>
        </div>
        <div class="rounded-lg bg-white p-5 shadow-sm">
            <div class="text-sm text-slate-500">Piutang / Sisa Tagihan</div>
            <div class="mt-2 text-xl font-semibold">{{ $money($outstandingBalance) }}</div>
        </div>
    </div>

    @if (auth()->user()->canPermission('bonuses'))
        <section class="mt-4 rounded-lg bg-white p-5 shadow-sm">
            <div class="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
                <div>
                    <h2 class="font-semibold">Bonus Saya Bulan Ini</h2>
                    <p class="mt-1 text-sm text-slate-500">{{ \Carbon\Carbon::parse($myBonusSummary['period_start'])->format('d/m/Y') }} - {{ \Carbon\Carbon::parse($myBonusSummary['period_end'])->format('d/m/Y') }}</p>
                </div>
                <a href="{{ route('bonuses.index') }}" class="rounded-md border px-4 py-2 text-sm font-medium">Detail Bonus</a>
            </div>
            <div class="mt-4 grid gap-3 md:grid-cols-3">
                <div class="rounded-md bg-slate-50 p-3"><div class="text-sm text-slate-500">Belum Dicairkan</div><strong class="mt-1 block text-xl">{{ $money($myBonusSummary['bonus_total']) }}</strong></div>
                <div class="rounded-md bg-slate-50 p-3"><div class="text-sm text-slate-500">Item Bonus</div><strong class="mt-1 block text-xl">{{ $myBonusSummary['items'] }}</strong></div>
                <div class="rounded-md bg-slate-50 p-3"><div class="text-sm text-slate-500">Nota</div><strong class="mt-1 block text-xl">{{ $myBonusSummary['orders'] }}</strong></div>
            </div>
        </section>
    @endif

    <div class="mt-6 grid gap-6 xl:grid-cols-3">
        <section class="rounded-lg bg-white p-5 shadow-sm xl:col-span-2">
            <div class="flex items-center justify-between gap-3">
                <div>
                    <h2 class="font-semibold">Grafik Penjualan 7 Hari</h2>
                    <p class="mt-1 text-sm text-slate-500">Batang tinggi menunjukkan omzet, angka kecil menunjukkan jumlah order.</p>
                </div>
                <a href="{{ route('reports.index') }}" class="rounded-md border px-3 py-2 text-sm">Laporan</a>
            </div>
            <div class="mt-6 flex h-72 items-end gap-3 border-b border-slate-200 pb-2">
                @foreach ($salesTrend as $point)
                    @php $height = max(8, ((float) $point['sales'] / $maxSalesTrend) * 100); @endphp
                    <div class="flex min-w-0 flex-1 flex-col items-center justify-end gap-2">
                        <div class="text-center text-[11px] text-slate-500">{{ $point['orders'] }} order</div>
                        <div class="w-full rounded-t-md bg-slate-900" style="height: {{ $height }}%"></div>
                        <div class="text-xs text-slate-500">{{ $point['label'] }}</div>
                    </div>
                @endforeach
            </div>
            <div class="mt-3 grid grid-cols-7 gap-2 text-center text-[11px] text-slate-500">
                @foreach ($salesTrend as $point)
                    <div class="truncate">{{ $money($point['sales']) }}</div>
                @endforeach
            </div>
        </section>

        <section class="rounded-lg bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Status Order</h2>
            <div class="mt-4 space-y-4">
                @foreach (\App\Models\Order::CORE_STATUSES as $status)
                    @php
                        $count = (int) ($statusCounts[$status] ?? 0);
                        $width = ($count / $totalStatus) * 100;
                    @endphp
                    <div>
                        <div class="mb-1 flex justify-between text-sm"><span class="capitalize">{{ $statusLabel($status) }}</span><strong>{{ $count }}</strong></div>
                        <div class="h-2 overflow-hidden rounded-full bg-slate-100"><div class="h-full rounded-full bg-slate-900" style="width: {{ $width }}%"></div></div>
                    </div>
                @endforeach
            </div>
        </section>
    </div>

    <div class="mt-6 grid gap-6 xl:grid-cols-3">
        <section class="rounded-lg bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Pembayaran</h2>
            <div class="mt-4 space-y-3">
                @foreach (['lunas', 'dp', 'pending'] as $payment)
                    @php
                        $count = (int) ($paymentCounts[$payment] ?? 0);
                        $width = ($count / $totalPayments) * 100;
                    @endphp
                    <div>
                        <div class="flex justify-between text-sm"><span class="uppercase">{{ $payment }}</span><span>{{ $count }}</span></div>
                        <div class="mt-1 h-2 overflow-hidden rounded-full bg-slate-100"><div class="h-full rounded-full bg-emerald-600" style="width: {{ $width }}%"></div></div>
                    </div>
                @endforeach
            </div>
        </section>

        <section class="rounded-lg bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Request Pelanggan</h2>
            <div class="mt-4 space-y-3 text-sm">
                @foreach (['baru', 'direview', 'dikonversi', 'dibatalkan'] as $status)
                    @php $count = (int) ($requestCounts[$status] ?? 0); @endphp
                    <div class="flex items-center justify-between gap-3">
                        <span class="capitalize">{{ $statusLabel($status) }}</span>
                        <span class="rounded-full border px-2 py-0.5 text-xs {{ $statusTone($status) }}">{{ $count }}</span>
                    </div>
                    <div class="h-1.5 overflow-hidden rounded-full bg-slate-100"><div class="h-full rounded-full bg-amber-500" style="width: {{ ($count / $totalRequests) * 100 }}%"></div></div>
                @endforeach
            </div>
        </section>

        <section class="rounded-lg bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Top Produk / Layanan 7 Hari</h2>
            <div class="mt-4 space-y-4 text-sm">
                @forelse ($topProducts as $product)
                    <div>
                        <div class="flex justify-between gap-3"><span class="truncate font-medium">{{ $product->product_name }}</span><span>{{ $money($product->sales) }}</span></div>
                        <div class="mt-1 flex items-center gap-2">
                            <div class="h-2 flex-1 overflow-hidden rounded-full bg-slate-100"><div class="h-full rounded-full bg-slate-900" style="width: {{ ((float) $product->sales / $maxProductSales) * 100 }}%"></div></div>
                            <span class="w-12 text-right text-xs text-slate-500">{{ number_format((float) $product->qty, 1, ',', '.') }}</span>
                        </div>
                    </div>
                @empty
                    <div class="py-4 text-slate-500">Belum ada penjualan produk.</div>
                @endforelse
            </div>
        </section>
    </div>

    <div class="mt-6 grid gap-6 xl:grid-cols-3">
        <section class="rounded-lg bg-white p-5 shadow-sm xl:col-span-2">
            <div class="flex items-center justify-between">
                <h2 class="font-semibold">Order Terbaru</h2>
                <a href="{{ route('orders.index') }}" class="text-sm text-slate-600 underline">Lihat semua</a>
            </div>
            <div class="mt-3 overflow-x-auto">
                <table class="w-full text-left text-sm">
                    <thead class="border-b text-xs uppercase text-slate-500">
                        <tr><th class="py-3">Nota</th><th>Pelanggan</th><th>Status</th><th>Pembayaran</th><th class="text-right">Total</th></tr>
                    </thead>
                    <tbody class="divide-y">
                        @forelse ($latestOrders as $order)
                            <tr>
                                <td class="py-3 font-medium"><a class="underline" href="{{ route('orders.show', $order) }}">{{ $order->invoice_no }}</a></td>
                                <td>{{ $order->customer?->name ?? 'Walk-in' }}</td>
                                <td><span class="rounded-full border px-2 py-0.5 text-xs {{ $statusTone($order->status) }}">{{ $order->status }}</span></td>
                                <td><span class="rounded-full border px-2 py-0.5 text-xs {{ $statusTone($order->payment_status) }}">{{ $order->payment_status }}</span></td>
                                <td class="text-right">{{ $money($order->grand_total) }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="5" class="py-5 text-center text-slate-500">Belum ada order.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </section>

        <section class="rounded-lg bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Lewat Estimasi</h2>
            <div class="mt-3 divide-y text-sm">
                @forelse ($overdueOrders as $order)
                    <a href="{{ route('orders.show', $order) }}" class="block py-3">
                        <div class="flex justify-between gap-3"><span class="font-medium">{{ $order->invoice_no }}</span><span class="text-red-600">{{ $order->estimated_done_at?->format('d/m H:i') }}</span></div>
                        <div class="mt-1 text-slate-500">{{ $order->customer?->name ?? 'Walk-in' }} - {{ $order->status }}</div>
                    </a>
                @empty
                    <div class="py-4 text-slate-500">Tidak ada order lewat estimasi.</div>
                @endforelse
            </div>
        </section>
    </div>

    <section class="mt-6 rounded-lg bg-white p-5 shadow-sm">
        <div class="flex items-center justify-between">
            <h2 class="font-semibold">Warning Stok</h2>
            <a href="{{ route('inventory.index') }}" class="text-sm text-slate-600 underline">Buka inventory</a>
        </div>
        <div class="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-5">
            @forelse ($lowStocks as $stock)
                <div class="rounded-md border border-red-100 bg-red-50 p-3 text-sm">
                    <div class="font-medium text-red-900">{{ $stock->product->name }}</div>
                    <div class="mt-2 flex justify-between text-red-700"><span>Stok</span><strong>{{ number_format((float) $stock->quantity, 2, ',', '.') }}</strong></div>
                    <div class="text-xs text-red-600">Minimum {{ number_format((float) $stock->product->minimum_stock, 2, ',', '.') }}</div>
                </div>
            @empty
                <div class="py-4 text-slate-500">Tidak ada stok minimum.</div>
            @endforelse
        </div>
    </section>
</x-admin-layout>
