@extends('layouts.app')

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

    @php
        $__revenueRound1000 = function ($amount) {
            $amount = max((float) ($amount ?? 0), 0);
            return $amount > 0 ? (float) (ceil($amount / 1000) * 1000) : 0;
        };

        $__revenueDisplayNet = function ($row) use ($__revenueRound1000) {
            return $__revenueRound1000($row->net_amount ?? $row->amount ?? 0);
        };

        $__revenueDisplayChange = function ($row, $displayNet) {
            $paid = (float) ($row->paid_amount ?? 0);
            return max($paid - (float) $displayNet, 0);
        };

        $totalRevenue       = $__revenueRound1000($summary['total_revenue'] ?? 0);
        $totalTransactions  = (int)   ($summary['total_transactions'] ?? 0);
        $totalQty           = (float) ($summary['total_qty'] ?? 0);
        $totalProducts      = (int)   ($summary['total_products'] ?? 0);

        $avgTicket = $totalTransactions > 0 ? ($totalRevenue / $totalTransactions) : 0;

        $tab = ($currentTab ?? request('tab') ?? 'transaksi');

        $machineLabel = 'Semua Mesin';
        if (!empty(request('machine_id')) && isset($machines)) {
            $machineLabel = optional($machines->firstWhere('id', (int) request('machine_id')))->name ?? 'Mesin Terpilih';
        }

        $categoryLabel = 'Semua Kategori';
        if (!empty(request('category_id')) && isset($categories)) {
            $categoryLabel = optional($categories->firstWhere('id', (int) request('category_id')))->name ?? 'Kategori Terpilih';
        }

        $periodLabel = ($startDate ?? '-') . ' s/d ' . ($endDate ?? '-');

        $exportUrl = route('reports.revenue.export', array_merge(
            request()->only(['start_date', 'end_date', 'machine_id', 'category_id', 'tab']),
            ['start_date' => $startDate, 'end_date' => $endDate, 'tab' => $tab]
        ));

        $printUrl = route('print.laporan-pendapatan', array_merge(
            ['start_date' => $startDate, 'end_date' => $endDate],
            request()->only(['machine_id', 'category_id'])
        ));
    @endphp

    <div class="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4 md:gap-4">
        <x-posgraf.stat-card title="Total Pendapatan" value="Rp {{ number_format($totalRevenue, 0, ',', '.') }}" color="success">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>

        <x-posgraf.stat-card title="Pembayaran Masuk" value="{{ number_format($totalTransactions, 0) }}" color="brand">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>

        <x-posgraf.stat-card title="Total Qty" value="{{ number_format($totalQty, 0, ',', '.') }} pcs" color="warning">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>

        <x-posgraf.stat-card title="Jumlah Produk Unik" value="{{ number_format($totalProducts, 0) }}" color="blue">
            <x-slot name="icon">
                <svg class="size-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"/>
                </svg>
            </x-slot>
        </x-posgraf.stat-card>
    </div>

    <div class="mb-6 rounded-2xl border border-brand-200 bg-brand-50 p-5 dark:border-brand-900/40 dark:bg-brand-900/10">
        <div class="flex items-start gap-4">
            <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-500 text-white">
                <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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">Ringkasan Pendapatan</h4>
                    <span class="rounded-full bg-white/80 px-2 py-0.5 text-xs font-medium text-gray-700 dark:bg-white/10 dark:text-white/70">
                        Periode: {{ $periodLabel }}
                    </span>
                    <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">
                        Mesin: {{ $machineLabel }}
                    </span>
                    <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">
                        Kategori: {{ $categoryLabel }}
                    </span>
                    <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: {{ $tab === 'produk' ? 'Per Produk' : 'Per Pembayaran' }}
                    </span>
                </div>

                <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                    Laporan ini membaca <span class="font-semibold">pendapatan bersih</span> dari pembayaran,
                    yaitu <span class="font-semibold">dibayar dikurangi kembalian</span>.
                    Jadi bila customer bayar lebih besar lalu ada kembalian, yang masuk ke pendapatan hanya nilai bersihnya,
                    bukan nominal uang yang diserahkan.
                    Pada transaksi lunas tunai, nilai ini otomatis akan sama dengan <span class="font-semibold">grand total</span> yang benar-benar menjadi pendapatan.
                    Rata-rata pendapatan bersih per pembayaran saat ini sekitar
                    <span class="font-semibold">Rp {{ number_format($avgTicket, 0, ',', '.') }}</span>.
                </p>

                <div class="mt-3 grid grid-cols-1 gap-2 md:grid-cols-2">
                    <div class="rounded-xl bg-white/80 p-3 text-xs text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                        <div class="mb-1 font-semibold">Cara baca cepat</div>
                        <ul class="list-disc space-y-1 pl-4">
                            <li><b>Total Pendapatan</b> = total pendapatan bersih sesuai filter tanggal.</li>
                            <li><b>Pembayaran Masuk</b> = jumlah baris pembayaran yang tercatat.</li>
                            <li><b>Dibayar</b> = uang yang diterima kasir.</li>
                            <li><b>Kembalian</b> = uang yang dikembalikan ke customer.</li>
                            <li><b>Pendapatan Bersih</b> = Dibayar - Kembalian.</li>
                        </ul>
                    </div>

                    <div class="rounded-xl bg-white/80 p-3 text-xs text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                        <div class="mb-1 font-semibold">Catatan penting</div>
                        <ul class="list-disc space-y-1 pl-4">
                            <li>Untuk pembayaran dengan kembalian, pendapatan tetap mengikuti nilai bersih / grand total transaksi yang benar-benar masuk.</li>
                            <li>Jika satu invoice dibayar beberapa kali, setiap pembayaran tetap tampil sebagai baris terpisah.</li>
                            <li>Total pendapatan tidak akan melebihi sisa tagihan order, jadi transaksi lama tetap aman.</li>
                            <li>Status <b>Cicilan</b>, <b>Pelunasan</b>, atau <b>Lunas</b> hanya membantu pembacaan transaksi.</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="mb-6 rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
        <form method="GET" class="grid grid-cols-1 items-end gap-4 sm:grid-cols-2 lg:grid-cols-5">
            <input type="hidden" name="tab" value="{{ $tab }}">

            <div class="w-full">
                <x-form.date-picker name="start_date" label="Dari Tanggal" placeholder="Pilih tanggal" :defaultDate="$startDate" />
            </div>

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

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

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

            <div class="flex w-full gap-2">
                <button type="submit" class="h-11 flex-1 rounded-lg bg-brand-500 px-5 text-sm font-medium text-white hover:bg-brand-600">
                    Filter
                </button>
                <a href="{{ route('reports.revenue') }}" class="flex h-11 items-center justify-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">
                    Reset
                </a>
            </div>
        </form>
    </div>

    <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
        <div class="flex flex-col gap-3 border-b border-gray-200 px-5 py-4 dark:border-gray-800 lg:flex-row lg:items-center lg:justify-between">
            <div class="flex items-center gap-3">
                <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">Rincian Pendapatan</h3>

                <div class="flex overflow-hidden rounded-lg border border-gray-200 text-sm dark:border-gray-700">
                    <a href="{{ route('reports.revenue', array_merge(request()->only(['start_date', 'end_date', 'machine_id', 'category_id']), ['tab' => 'transaksi'])) }}"
                       class="px-3 py-1.5 {{ $tab === 'transaksi' ? 'bg-brand-500 text-white' : 'bg-white text-gray-600 hover:bg-gray-100 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700' }} transition-colors">
                        Per Pembayaran
                    </a>
                    <a href="{{ route('reports.revenue', array_merge(request()->only(['start_date', 'end_date', 'machine_id', 'category_id']), ['tab' => 'produk'])) }}"
                       class="border-l border-gray-200 px-3 py-1.5 {{ $tab === 'produk' ? 'bg-brand-500 text-white' : 'bg-white text-gray-600 hover:bg-gray-100 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700' }} transition-colors dark:border-gray-700">
                        Per Produk
                    </a>
                </div>
            </div>

            <div class="flex flex-wrap items-center gap-2">
                <a href="{{ $exportUrl }}"
                   class="inline-flex items-center gap-2 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300">
                    <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 3v12m0 0l3-3m-3 3l-3-3M4 17v3a1 1 0 001 1h14a1 1 0 001-1v-3"/>
                    </svg>
                    Export Excel
                </a>

                <a href="{{ $printUrl }}" target="_blank"
                   class="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-brand-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 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/>
                    </svg>
                    Cetak
                </a>
            </div>
        </div>

        <div class="overflow-x-auto">
            @if($tab === 'transaksi')
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-900/50">
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Tanggal Bayar</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Invoice</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Pelanggan</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Status</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Jenis</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Rekening</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Kasir</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Dibayar</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Kembalian</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Pendapatan Bersih</th>
                        </tr>
                    </thead>

                    <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                        @forelse($byTransaction as $row)
                            @php
                                $displayNetAmount = $__revenueDisplayNet($row);
                                $displayChangeAmount = $__revenueDisplayChange($row, $displayNetAmount);

                                $badgeClass = match($row->status_badge ?? 'success') {
                                    'warning' => 'bg-warning-100 text-warning-700 dark:bg-warning-500/20 dark:text-warning-400',
                                    'brand' => 'bg-brand-100 text-brand-700 dark:bg-brand-500/20 dark:text-brand-400',
                                    default => 'bg-success-100 text-success-700 dark:bg-success-500/20 dark:text-success-400',
                                };
                            @endphp

                            <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                                <td class="px-5 py-4 text-sm text-gray-500">
                                    {{ optional($row->payment_date)->format('d/m/Y H:i') ?? '-' }}
                                </td>

                                <td class="px-5 py-4">
                                    <a href="{{ url('/orders/' . $row->order_id) }}"
                                       class="text-sm font-medium text-brand-600 hover:text-brand-700 hover:underline">
                                        {{ $row->invoice_number }}
                                    </a>
                                </td>

                                <td class="px-5 py-4 text-sm text-gray-800 dark:text-white/90">
                                    <div>{{ $row->customer_name }}</div>
                                    @if(!empty($row->notes))
                                        <div class="mt-1 text-xs italic text-gray-500 dark:text-gray-400">
                                            {{ $row->notes }}
                                        </div>
                                    @endif
                                </td>

                                <td class="px-5 py-4 text-sm">
                                    <span class="inline-flex rounded-full px-2.5 py-1 text-xs font-medium {{ $badgeClass }}">
                                        {{ $row->status_label }}
                                    </span>
                                </td>

                                <td class="px-5 py-4 text-sm text-gray-600 dark:text-gray-400">
                                    {{ $row->payment_method_label ?? '-' }}
                                </td>

                                <td class="px-5 py-4 text-sm text-gray-600 dark:text-gray-400">
                                    {{ $row->payment_account_label ?? '-' }}
                                </td>

                                <td class="px-5 py-4 text-sm text-gray-600 dark:text-gray-400">
                                    {{ $row->cashier_name ?? '-' }}
                                </td>

                                <td class="px-5 py-4 text-right text-sm text-gray-700 dark:text-gray-300">
                                    Rp {{ number_format((float) ($row->paid_amount ?? 0), 0, ',', '.') }}
                                </td>

                                <td class="px-5 py-4 text-right text-sm text-danger-600 dark:text-danger-400">
                                    Rp {{ number_format($displayChangeAmount, 0, ',', '.') }}
                                </td>

                                <td class="px-5 py-4 text-right text-sm font-semibold text-success-600 dark:text-success-400">
                                    Rp {{ number_format($displayNetAmount, 0, ',', '.') }}
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="10" class="px-5 py-12 text-center text-sm text-gray-500">Tidak ada data</td>
                            </tr>
                        @endforelse
                    </tbody>

                    @if(isset($byTransaction) && method_exists($byTransaction, 'count') && $byTransaction->count() > 0)
                        <tfoot class="border-t-2 border-gray-300 bg-gray-50 dark:border-gray-700 dark:bg-gray-900/50">
                            <tr>
                                <td colspan="9" class="px-5 py-4 text-sm font-semibold text-gray-800 dark:text-white/90">
                                    Total {{ number_format($totalTransactions, 0) }} Pembayaran Masuk
                                </td>
                                <td class="px-5 py-4 text-right text-base font-bold text-brand-600 dark:text-brand-400">
                                    Rp {{ number_format($totalRevenue, 0, ',', '.') }}
                                </td>
                            </tr>
                        </tfoot>
                    @endif
                </table>
            @else
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-900/50">
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">#</th>
                            <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Produk</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Order</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Qty</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Pendapatan</th>
                            <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">%</th>
                        </tr>
                    </thead>

                    <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
                        @forelse($byProduct as $index => $product)
                            @php
                                $productRevenue = $__revenueRound1000($product->total_revenue ?? 0);
                                $percentage = $totalRevenue > 0 ? ($productRevenue / $totalRevenue) * 100 : 0;
                            @endphp

                            <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                                <td class="px-5 py-4 text-sm text-gray-500">{{ $index + 1 }}</td>
                                <td class="px-5 py-4 text-sm font-medium text-gray-800 dark:text-white/90">{{ $product->name }}</td>
                                <td class="px-5 py-4 text-right text-sm text-gray-600 dark:text-gray-400">{{ number_format($product->total_orders) }}</td>
                                <td class="px-5 py-4 text-right text-sm text-gray-600 dark:text-gray-400">{{ number_format($product->total_qty, 0, ',', '.') }}</td>
                                <td class="px-5 py-4 text-right text-sm font-semibold text-success-600 dark:text-success-400">
                                    Rp {{ number_format($productRevenue, 0, ',', '.') }}
                                </td>
                                <td class="px-5 py-4 text-right text-sm text-gray-500">{{ number_format($percentage, 1) }}%</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="px-5 py-12 text-center text-sm text-gray-500">Tidak ada data</td>
                            </tr>
                        @endforelse
                    </tbody>

                    @if(isset($byProduct) && method_exists($byProduct, 'count') && $byProduct->count() > 0)
                        <tfoot class="border-t-2 border-gray-300 bg-gray-50 dark:border-gray-700 dark:bg-gray-900/50">
                            <tr>
                                <td colspan="4" class="px-5 py-4 text-sm font-semibold text-gray-800 dark:text-white/90">Total</td>
                                <td class="px-5 py-4 text-right text-base font-bold text-brand-600 dark:text-brand-400">
                                    Rp {{ number_format($totalRevenue, 0, ',', '.') }}
                                </td>
                                <td class="px-5 py-4 text-right text-sm font-semibold text-gray-500">100%</td>
                            </tr>
                        </tfoot>
                    @endif
                </table>
            @endif
        </div>
    </div>

    <div class="mt-12 border-t border-gray-200 pt-6 text-center text-xs text-gray-500 dark:border-gray-800 dark:text-gray-400">
        <p>
            © {{ date('Y') }} <span class="font-semibold text-gray-700 dark:text-gray-300">Rio Ardiansyah - aplikasipercetakan.com</span>.
            All rights reserved.
        </p>
    </div>
@endsection
