<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Omset Penjualan</title>
    <style>
        @media print {
            @page {
                size: A4 portrait;
                margin: 12mm;
            }
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 11px;
            line-height: 1.45;
            color: #1f2937;
            background: #ffffff;
            padding: 18px;
        }

        .page {
            width: 100%;
        }

        .header {
            display: flex;
            align-items: center;
            gap: 14px;
            border-bottom: 2px solid #1f2937;
            padding-bottom: 14px;
            margin-bottom: 18px;
        }

        .header-logo img {
            max-height: 58px;
            max-width: 90px;
            object-fit: contain;
        }

        .header-content {
            flex: 1;
        }

        .shop-name {
            font-size: 20px;
            font-weight: 700;
            color: #111827;
            margin-bottom: 2px;
        }

        .shop-address {
            font-size: 11px;
            color: #6b7280;
            margin-bottom: 6px;
        }

        .report-title {
            font-size: 16px;
            font-weight: 700;
            color: #111827;
        }

        .report-period {
            font-size: 11px;
            color: #4b5563;
            margin-top: 4px;
        }

        .summary-grid {
            display: table;
            width: 100%;
            table-layout: fixed;
            border-spacing: 8px;
            margin: 0 -8px 18px -8px;
        }

        .summary-row {
            display: table-row;
        }

        .summary-box {
            display: table-cell;
            background: #f8fafc;
            border: 1px solid #dbeafe;
            border-radius: 8px;
            padding: 12px;
            vertical-align: top;
        }

        .summary-label {
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: .04em;
            color: #6b7280;
            font-weight: 700;
            margin-bottom: 6px;
        }

        .summary-value {
            font-size: 18px;
            font-weight: 700;
            color: #111827;
        }

        .summary-sub {
            margin-top: 4px;
            font-size: 10px;
            color: #6b7280;
        }

        .paid-box {
            background: #ecfdf5;
            border-color: #a7f3d0;
        }

        .receivable-box {
            background: #fffbeb;
            border-color: #fde68a;
        }

        .total-box {
            background: #eff6ff;
            border-color: #bfdbfe;
        }

        .section-title {
            font-size: 13px;
            font-weight: 700;
            color: #111827;
            margin: 18px 0 10px;
            padding-bottom: 6px;
            border-bottom: 1px solid #d1d5db;
        }

        .subsection-title {
            font-size: 12px;
            font-weight: 700;
            color: #111827;
            margin: 14px 0 8px;
        }

        .grid-2 {
            display: table;
            width: 100%;
            table-layout: fixed;
            border-spacing: 10px;
            margin: 0 -10px 12px -10px;
        }

        .grid-2-col {
            display: table-cell;
            vertical-align: top;
            width: 50%;
            padding: 0 10px;
        }

        .mini-card {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 10px;
            background: #fff;
            margin-bottom: 8px;
        }

        .mini-card-name {
            font-size: 11px;
            font-weight: 700;
            color: #111827;
        }

        .mini-card-meta {
            font-size: 10px;
            color: #6b7280;
            margin-top: 2px;
        }

        .mini-card-value {
            font-size: 12px;
            font-weight: 700;
            margin-top: 4px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            border: 1px solid #d1d5db;
            padding: 7px 8px;
            vertical-align: top;
        }

        th {
            background: #f3f4f6;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: .03em;
            color: #374151;
            font-weight: 700;
        }

        td {
            font-size: 10px;
            color: #1f2937;
        }

        .text-right {
            text-align: right;
        }

        .text-center {
            text-align: center;
        }

        .font-bold {
            font-weight: 700;
        }

        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 999px;
            font-size: 9px;
            font-weight: 700;
            line-height: 1.2;
        }

        .badge-paid {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #6ee7b7;
        }

        .badge-receivable {
            background: #fef3c7;
            color: #92400e;
            border: 1px solid #fcd34d;
        }

        .tfoot-total {
            background: #f9fafb;
            font-weight: 700;
        }

        .tfoot-grand {
            background: #111827;
            color: #ffffff;
            font-weight: 700;
        }

        .tfoot-grand td {
            color: #ffffff;
        }

        .note-box {
            margin-top: 14px;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            background: #f9fafb;
            border-radius: 8px;
            font-size: 10px;
            color: #4b5563;
        }

        .footer {
            margin-top: 22px;
            padding-top: 10px;
            border-top: 1px solid #d1d5db;
            display: flex;
            justify-content: space-between;
            gap: 12px;
            font-size: 10px;
            color: #6b7280;
        }

        .mb-16 {
            margin-bottom: 16px;
        }

        @media screen {
            body {
                max-width: 210mm;
                margin: 20px auto;
                border: 1px solid #d1d5db;
                box-shadow: 0 4px 18px rgba(0, 0, 0, 0.08);
            }
        }
    </style>
</head>
<body onload="window.print()">
    @php
        $orders = collect($orders ?? []);
        $dailyData = collect($dailyData ?? []);
        $paidCustomersList = collect($paidCustomers ?? []);
        $receivableCustomersList = collect($receivableCustomers ?? []);

        $paidRevenue = (float) ($summary['paid_revenue'] ?? 0);
        $receivableRevenue = (float) ($summary['receivable_revenue'] ?? 0);
        $totalRevenue = (float) ($summary['total_revenue'] ?? ($paidRevenue + $receivableRevenue));

        $paidOrders = (int) ($summary['paid_orders'] ?? 0);
        $receivableOrders = (int) ($summary['receivable_orders'] ?? 0);

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

        $shopLogoUrl = null;
        if (!empty($shopLogo)) {
            $shopLogoUrl = \Illuminate\Support\Str::startsWith($shopLogo, ['http://', 'https://', '/'])
                ? $shopLogo
                : asset('storage/' . ltrim($shopLogo, '/'));
        }

        $formatQty = function ($value) {
            $value = (float) $value;
            if (floor($value) == $value) {
                return number_format($value, 0, ',', '.');
            }
            return number_format($value, 2, ',', '.');
        };
    @endphp

    <div class="page">
        <div class="header">
            @if($shopLogoUrl)
                <div class="header-logo">
                    <img src="{{ $shopLogoUrl }}" alt="{{ $shopName }}">
                </div>
            @endif

            <div class="header-content">
                <div class="shop-name">{{ $shopName }}</div>
                @if(!empty($shopAddress))
                    <div class="shop-address">{{ $shopAddress }}</div>
                @endif
                <div class="report-title">LAPORAN OMSET PENJUALAN</div>
                <div class="report-period">
                    Periode: {{ \Carbon\Carbon::parse($startDate)->format('d M Y') }} - {{ \Carbon\Carbon::parse($endDate)->format('d M Y') }}
                </div>
            </div>
        </div>

        <div class="summary-grid">
            <div class="summary-row">
                <div class="summary-box total-box">
                    <div class="summary-label">Total Omset</div>
                    <div class="summary-value">Rp {{ number_format($totalRevenue, 0, ',', '.') }}</div>
                    <div class="summary-sub">Gabungan order lunas + piutang</div>
                </div>

                <div class="summary-box">
                    <div class="summary-label">Total Order</div>
                    <div class="summary-value">{{ number_format($summary['total_orders'] ?? 0, 0, ',', '.') }}</div>
                    <div class="summary-sub">Semua transaksi pada periode ini</div>
                </div>

                <div class="summary-box">
                    <div class="summary-label">Total Qty</div>
                    <div class="summary-value">{{ $formatQty($summary['total_qty'] ?? 0) }}</div>
                    <div class="summary-sub">Total qty seluruh item</div>
                </div>
            </div>
        </div>

        <div class="summary-grid">
            <div class="summary-row">
                <div class="summary-box paid-box">
                    <div class="summary-label">Omset Lunas</div>
                    <div class="summary-value">Rp {{ number_format($paidRevenue, 0, ',', '.') }}</div>
                    <div class="summary-sub">{{ $paidOrders }} order • {{ $paidCustomersCount }} pelanggan</div>
                </div>

                <div class="summary-box receivable-box">
                    <div class="summary-label">Omset Piutang</div>
                    <div class="summary-value">Rp {{ number_format($receivableRevenue, 0, ',', '.') }}</div>
                    <div class="summary-sub">{{ $receivableOrders }} order • {{ $receivableCustomersCount }} pelanggan</div>
                </div>
            </div>
        </div>

        @if($dailyData->count() > 0)
            <div class="section-title">Ringkasan Harian</div>
            <table class="mb-16">
                <thead>
                    <tr>
                        <th>Tanggal</th>
                        <th class="text-center">Jumlah Order</th>
                        <th class="text-right">Omset</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($dailyData as $daily)
                        <tr>
                            <td>{{ \Carbon\Carbon::parse($daily->date)->format('d M Y') }}</td>
                            <td class="text-center">{{ $daily->total_orders }}</td>
                            <td class="text-right">Rp {{ number_format((float) $daily->total_revenue, 0, ',', '.') }}</td>
                        </tr>
                    @endforeach
                </tbody>
                <tfoot>
                    <tr class="tfoot-total">
                        <td colspan="2" class="text-right">Total Harian</td>
                        <td class="text-right">Rp {{ number_format((float) $dailyData->sum('total_revenue'), 0, ',', '.') }}</td>
                    </tr>
                </tfoot>
            </table>
        @endif

        @if($paidCustomersList->count() > 0 || $receivableCustomersList->count() > 0)
            <div class="section-title">Ringkasan Pelanggan</div>

            <div class="grid-2">
                <div class="grid-2-col">
                    <div class="subsection-title">Pelanggan Lunas</div>
                    @forelse($paidCustomersList->take(8) as $customer)
                        @php
                            $customerName = is_array($customer) ? ($customer['customer_name'] ?? '-') : ($customer->customer_name ?? '-');
                            $customerOrders = is_array($customer) ? ($customer['total_orders'] ?? 0) : ($customer->total_orders ?? 0);
                            $customerAmount = is_array($customer) ? ($customer['total_amount'] ?? 0) : ($customer->total_amount ?? 0);
                        @endphp
                        <div class="mini-card">
                            <div class="mini-card-name">{{ $customerName }}</div>
                            <div class="mini-card-meta">{{ number_format((float) $customerOrders, 0, ',', '.') }} order</div>
                            <div class="mini-card-value" style="color:#065f46;">Rp {{ number_format((float) $customerAmount, 0, ',', '.') }}</div>
                        </div>
                    @empty
                        <div class="mini-card">Tidak ada data pelanggan lunas.</div>
                    @endforelse
                </div>

                <div class="grid-2-col">
                    <div class="subsection-title">Pelanggan Piutang</div>
                    @forelse($receivableCustomersList->take(8) as $customer)
                        @php
                            $customerName = is_array($customer) ? ($customer['customer_name'] ?? '-') : ($customer->customer_name ?? '-');
                            $customerOrders = is_array($customer) ? ($customer['total_orders'] ?? 0) : ($customer->total_orders ?? 0);
                            $customerAmount = is_array($customer) ? ($customer['total_amount'] ?? 0) : ($customer->total_amount ?? 0);
                        @endphp
                        <div class="mini-card">
                            <div class="mini-card-name">{{ $customerName }}</div>
                            <div class="mini-card-meta">{{ number_format((float) $customerOrders, 0, ',', '.') }} order</div>
                            <div class="mini-card-value" style="color:#92400e;">Rp {{ number_format((float) $customerAmount, 0, ',', '.') }}</div>
                        </div>
                    @empty
                        <div class="mini-card">Tidak ada data pelanggan piutang.</div>
                    @endforelse
                </div>
            </div>
        @endif

        <div class="section-title">Detail Order</div>
        <table>
            <thead>
                <tr>
                    <th style="width: 10%;">Tanggal</th>
                    <th style="width: 13%;">Invoice</th>
                    <th style="width: 18%;">Pelanggan</th>
                    <th>Ringkasan Item</th>
                    <th style="width: 10%;" class="text-center">Status</th>
                    <th style="width: 14%;" class="text-right">Total</th>
                </tr>
            </thead>
            <tbody>
                @forelse($orders as $order)
                    @php
                        $printItems = collect($order->items ?? [])->filter(function ($item) {
                            return !(bool) ($item->is_cancelled ?? false);
                        })->values();

                        $firstItem = $printItems->first();
                        $extraItemsCount = max($printItems->count() - 1, 0);

                        $summaryFileName = $firstItem->file_name ?? '-';
                        $summaryQty = (float) ($firstItem->qty ?? 0);
                        $summarySizeUnit = strtolower(trim((string) ($firstItem->size_unit ?? '')));
                        if ($summarySizeUnit === 'm²') {
                            $summarySizeUnit = 'm2';
                        }
                        if ($summarySizeUnit === 'pcs') {
                            $summarySizeUnit = 'lembar';
                        }

                        $summarySizeDescription = $firstItem->size_description ?? '-';
                        $summarySizeValue = (float) ($firstItem->size_value ?? 0);
                        $displayTotal = (float) ($order->report_total_price ?? $order->total_price ?? 0);

                        $isReceivable = false;
                        if (
                            (isset($order->report_remaining_balance) && (float) $order->report_remaining_balance > 0) ||
                            (isset($order->remaining_balance) && (float) $order->remaining_balance > 0) ||
                            (isset($order->payment_status) && in_array($order->payment_status, ['partial', 'unpaid', 'receivable']))
                        ) {
                            $isReceivable = true;
                        }

                        $statusLabel = $isReceivable ? 'Piutang' : 'Lunas';
                        $statusClass = $isReceivable ? 'badge-receivable' : 'badge-paid';

                        $tanggalTampil = $order->paid_at ?? $order->created_at ?? null;

                        $qtyLine = '-';
                        if ($summaryQty > 0) {
                            $qtyLine = $formatQty($summaryQty);
                            if (!empty($summarySizeUnit)) {
                                $qtyLine .= ' ' . $summarySizeUnit;
                            }
                        }

                        $sizeLine = $summarySizeDescription ?: '-';
                        if ($summarySizeUnit === 'm2' && $summarySizeValue > 0) {
                            $sizeLine .= ' • nilai ' . $formatQty($summarySizeValue) . ' m2';
                        }
                    @endphp

                    <tr>
                        <td>
                            {{ $tanggalTampil ? \Carbon\Carbon::parse($tanggalTampil)->format('d/m/Y') : '-' }}
                        </td>
                        <td class="font-bold">
                            {{ $order->invoice_number }}
                        </td>
                        <td>
                            <div class="font-bold">{{ $order->customer_name }}</div>
                            @if(!empty($order->customer_phone))
                                <div style="color:#6b7280;">{{ $order->customer_phone }}</div>
                            @endif
                        </td>
                        <td>
                            <div class="font-bold">{{ $summaryFileName }}</div>
                            <div style="color:#6b7280;">{{ $sizeLine }}</div>
                            <div style="color:#6b7280;">Qty: {{ $qtyLine }}</div>
                            @if($extraItemsCount > 0)
                                <div style="margin-top:3px;color:#374151;">+{{ $extraItemsCount }} item lagi</div>
                            @endif
                        </td>
                        <td class="text-center">
                            <span class="badge {{ $statusClass }}">{{ $statusLabel }}</span>
                        </td>
                        <td class="text-right font-bold">
                            Rp {{ number_format($displayTotal, 0, ',', '.') }}
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="6" class="text-center">Tidak ada data order pada periode ini.</td>
                    </tr>
                @endforelse
            </tbody>
            <tfoot>
                <tr class="tfoot-total">
                    <td colspan="5" class="text-right">Total Lunas</td>
                    <td class="text-right">Rp {{ number_format($paidRevenue, 0, ',', '.') }}</td>
                </tr>
                <tr class="tfoot-total">
                    <td colspan="5" class="text-right">Total Piutang</td>
                    <td class="text-right">Rp {{ number_format($receivableRevenue, 0, ',', '.') }}</td>
                </tr>
                <tr class="tfoot-grand">
                    <td colspan="5" class="text-right">Grand Total Omset</td>
                    <td class="text-right">Rp {{ number_format($totalRevenue, 0, ',', '.') }}</td>
                </tr>
            </tfoot>
        </table>

        <div class="note-box">
            <div><strong>Keterangan:</strong></div>
            <div>- Omset dihitung dari gabungan transaksi lunas dan piutang.</div>
            <div>- Nilai item m2 mengikuti perhitungan ulang dari ukuran aktual item order.</div>
            <div>- Jika filter mesin tidak tersedia di sistem bahan, laporan tetap aman dicetak tanpa memaksa relasi mesin.</div>
        </div>

        <div class="footer">
            <div>Dicetak pada {{ now()->format('d M Y H:i') }}</div>
            <div>{{ $shopName }}</div>
        </div>
    </div>
</body>
</html>