<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ $title }} - {{ $customer }}</title>
    <style>
        @media print {
            @page { size: A4 portrait; margin: 15mm; }
            .no-print { display: none !important; }
        }

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

        body {
            font-family: Arial, sans-serif;
            font-size: 10px;
            line-height: 1.4;
            background: white;
            padding: 20px;
            color: #111827;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .document-shell {
            position: relative;
            min-height: 250mm;
        }

        .watermark-demo {
            position: absolute;
            inset: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            pointer-events: none;
            user-select: none;
            z-index: 0;
            overflow: hidden;
        }

        .watermark-demo span {
            display: block;
            transform: rotate(-28deg);
            font-size: 70px;
            line-height: 1;
            font-weight: 900;
            letter-spacing: 10px;
            text-transform: uppercase;
            white-space: nowrap;
            color: rgba(220, 38, 38, 0.08);
        }

        .document-content {
            position: relative;
            z-index: 1;
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #333;
        }

        .header h1 {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .header h2 {
            font-size: 14px;
            font-weight: normal;
            color: #666;
            margin-top: 6px;
        }

        .header .period {
            font-size: 12px;
            margin-top: 10px;
        }

        .sub-info {
            margin-top: 8px;
            font-size: 10px;
            color: #555;
        }

        .demo-badge {
            display: inline-block;
            margin-top: 10px;
            padding: 4px 10px;
            border: 1px solid #dc2626;
            background: rgba(220, 38, 38, 0.10);
            color: #b91c1c;
            font-size: 10px;
            font-weight: 800;
            letter-spacing: 1px;
            text-transform: uppercase;
            border-radius: 3px;
        }

        .demo-warning-box {
            margin: 0 0 18px 0;
            padding: 12px 14px;
            border: 2px solid #dc2626;
            background: rgba(220, 38, 38, 0.06);
            border-radius: 6px;
        }

        .demo-warning-title {
            font-size: 13px;
            font-weight: 900;
            color: #b91c1c;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 4px;
        }

        .demo-warning-text {
            font-size: 11px;
            font-weight: 700;
            color: #991b1b;
            line-height: 1.5;
        }

        .summary-section {
            display: flex;
            justify-content: space-around;
            gap: 10px;
            margin-bottom: 20px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 5px;
        }

        .summary-box {
            text-align: center;
            flex: 1;
        }

        .summary-box .label {
            font-size: 10px;
            color: #666;
            text-transform: uppercase;
        }

        .summary-box .value {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            margin-top: 4px;
        }

        .summary-box .value.success { color: #16a34a; }
        .summary-box .value.danger { color: #dc2626; }

        .detail-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 16px;
            background: transparent;
        }

        .detail-table th,
        .detail-table td {
            border: 1px solid #ddd;
            padding: 6px 8px;
            text-align: left;
            font-size: 9px;
            vertical-align: top;
        }

        .detail-table th {
            background: #f5f5f5;
            font-weight: bold;
            text-transform: uppercase;
        }

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

        .order-title {
            margin: 14px 0 6px 0;
            font-size: 11px;
            font-weight: bold;
            color: #111;
        }

        .badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 8px;
            font-weight: bold;
            vertical-align: middle;
        }

        .badge-unpaid { background: #fee2e2; color: #dc2626; }
        .badge-partial { background: #fef3c7; color: #d97706; }
        .badge-selected { background: #dbeafe; color: #1d4ed8; }
        .badge-demo { background: #fee2e2; color: #b91c1c; }

        .muted {
            color: #666;
            font-size: 9px;
            margin-top: 2px;
        }

        .selected-info {
            margin: 10px 0 18px 0;
            padding: 10px 12px;
            border: 1px solid #bfdbfe;
            background: #eff6ff;
            border-radius: 6px;
            font-size: 10px;
            color: #1e3a8a;
        }

        .invoice-list {
            margin-top: 6px;
            line-height: 1.6;
        }

        .invoice-chip {
            display: inline-block;
            margin: 2px 4px 2px 0;
            padding: 3px 8px;
            border-radius: 999px;
            background: #e5e7eb;
            font-size: 9px;
            color: #111827;
        }

        .demo-legal-note {
            margin-top: 20px;
            padding: 10px 12px;
            border: 1px dashed #dc2626;
            background: rgba(220, 38, 38, 0.04);
            color: #b91c1c;
            font-size: 10px;
            font-weight: 800;
            line-height: 1.5;
            text-transform: uppercase;
            text-align: center;
            border-radius: 6px;
        }

        .footer {
            margin-top: 30px;
            padding-top: 15px;
            border-top: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            font-size: 9px;
            color: #666;
        }

        .print-btn {
            background: #1a1a1a;
            color: white;
            padding: 10px 30px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-top: 20px;
        }

        .print-btn:hover { background: #333; }

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

        @media screen {
            body {
                max-width: 210mm;
                margin: 20px auto;
                border: 1px solid #ccc;
                box-shadow: 0 0 10px rgba(0,0,0,0.1);
            }
        }
    </style>
</head>

<body>
    @php
        $selectedOrderIds = collect((array) request('order_ids', []))
            ->map(fn ($id) => (int) $id)
            ->filter()
            ->values();

        $ordersCollection = $orders instanceof \Illuminate\Contracts\Pagination\Paginator
            ? collect($orders->items())
            : collect($orders);

        $filteredOrders = $selectedOrderIds->isNotEmpty()
            ? $ordersCollection->whereIn('id', $selectedOrderIds)->values()
            : $ordersCollection->values();

        $totalOrders = $filteredOrders->count();
        $totalTagihan = $filteredOrders->sum('total_price');
        $totalDibayar = $filteredOrders->sum(fn($o) => (float) $o->getTotalPaid());
        $totalPiutang = $filteredOrders->sum(fn($o) => (float) $o->getRemainingBalance());

        $printMode = $selectedOrderIds->isNotEmpty() ? 'Transaksi Terpilih' : 'Semua Transaksi Customer';
    @endphp

    <div class="document-shell">
        @if(env('APP_DEMO', false))
            <div class="watermark-demo">
                <span>DEMO MODE</span>
            </div>
        @endif

        <div class="document-content">
            <div class="header">
                @if($shopLogo ?? false)
                    <img src="{{ $shopLogo }}" alt="{{ $shopName }}" style="max-height: 50px; margin-bottom: 10px;">
                @endif

                <h1>{{ $shopName }}</h1>

                @if(!empty($shopAddress))
                    <p>{{ $shopAddress }}</p>
                @endif

                <h2>SURAT PENAGIHAN PIUTANG</h2>

                <div class="period">
                    Customer: <b>{{ $customer }}</b><br>
                    @if(!empty($month))
                        Periode: {{ \Carbon\Carbon::createFromFormat('Y-m', $month)->translatedFormat('F Y') }}
                    @else
                        Periode: Semua Piutang (s/d {{ now()->format('d M Y') }})
                    @endif
                </div>

                <div class="sub-info">
                    Mode Cetak: <b>{{ $printMode }}</b>
                </div>

                @if(env('APP_DEMO', false))
                    <div class="demo-badge">Mode Demo</div>
                @endif
            </div>

            @if(env('APP_DEMO', false))
                <div class="demo-warning-box">
                    <div class="demo-warning-title">Dokumen Simulasi / Percobaan</div>
                    <div class="demo-warning-text">
                        Surat penagihan ini dibuat dalam <strong>DEMO MODE</strong>. Seluruh data customer,
                        nominal, invoice, piutang, dan status pembayaran pada dokumen ini merupakan
                        <strong>simulasi / transaksi palsu / percobaan sistem</strong> dan
                        <strong>bukan surat penagihan sah</strong>, bukan dokumen penagihan resmi,
                        bukan dasar audit, dan tidak boleh digunakan untuk penagihan nyata kepada pelanggan.
                    </div>
                </div>
            @endif

            @if($selectedOrderIds->isNotEmpty())
                <div class="selected-info">
                    <div><b>Transaksi yang dicetak dipilih manual dari daftar customer.</b></div>
                    <div class="invoice-list">
                        @foreach($filteredOrders as $order)
                            <span class="invoice-chip">{{ $order->invoice_number }}</span>
                        @endforeach
                    </div>
                </div>
            @endif

            <div class="summary-section">
                <div class="summary-box">
                    <div class="label">Total Order</div>
                    <div class="value">{{ $totalOrders }}</div>
                </div>
                <div class="summary-box">
                    <div class="label">Total Tagihan</div>
                    <div class="value">Rp {{ number_format($totalTagihan, 0, ',', '.') }}</div>
                </div>
                <div class="summary-box">
                    <div class="label">Sudah Dibayar</div>
                    <div class="value success">Rp {{ number_format($totalDibayar, 0, ',', '.') }}</div>
                </div>
                <div class="summary-box">
                    <div class="label">Total Piutang</div>
                    <div class="value danger">Rp {{ number_format($totalPiutang, 0, ',', '.') }}</div>
                </div>
            </div>

            @forelse($filteredOrders as $idx => $order)
                @php
                    $paid = (float) $order->getTotalPaid();
                    $remaining = (float) $order->getRemainingBalance();
                    $badgeClass = $order->payment_status === 'partial' ? 'badge-partial' : 'badge-unpaid';
                    $badgeText = $order->payment_status === 'partial' ? 'Sebagian' : 'Belum Bayar';
                @endphp

                <div class="order-title">
                    {{ $idx + 1 }}. Invoice: {{ $order->invoice_number }}
                    <span class="badge {{ $badgeClass }}">{{ $badgeText }}</span>
                    @if($selectedOrderIds->isNotEmpty())
                        <span class="badge badge-selected">Dipilih</span>
                    @endif
                    @if(env('APP_DEMO', false))
                        <span class="badge badge-demo">Demo</span>
                    @endif
                    <span class="muted"> | Tanggal: {{ $order->created_at->format('d/m/Y') }}</span>
                </div>

                <table class="detail-table">
                    <thead>
                        <tr>
                            <th class="text-right" style="width: 20%;">Total</th>
                            <th class="text-right" style="width: 20%;">Dibayar</th>
                            <th class="text-right" style="width: 20%;">Sisa</th>
                            <th style="width: 40%;">Catatan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td class="text-right">Rp {{ number_format($order->total_price, 0, ',', '.') }}</td>
                            <td class="text-right" style="color:#16a34a;">
                                {{ $paid > 0 ? 'Rp ' . number_format($paid, 0, ',', '.') : '-' }}
                            </td>
                            <td class="text-right" style="color:#dc2626; font-weight:bold;">
                                Rp {{ number_format($remaining, 0, ',', '.') }}
                            </td>
                            <td>{{ $order->notes ?? '-' }}</td>
                        </tr>
                    </tbody>
                </table>

                <table class="detail-table">
                    <thead>
                        <tr>
                            <th style="width: 5%;" class="text-center">No</th>
                            <th style="width: 30%;">Item / Produk</th>
                            <th style="width: 25%;">File</th>
                            <th style="width: 20%;">Ukuran</th>
                            <th style="width: 10%;" class="text-right">Qty</th>
                            <th style="width: 10%;">Keterangan</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($order->items as $i => $item)
                            @php
                                $unitRaw = strtolower(trim(
                                    $item->size_unit
                                    ?? $item->unit
                                    ?? $item->qty_unit
                                    ?? $item->unit_label
                                    ?? ''
                                ));

                                $isMeter = $unitRaw !== '' && (
                                    str_contains($unitRaw, 'meter') ||
                                    $unitRaw === 'm' ||
                                    str_contains($unitRaw, 'm2') ||
                                    str_contains($unitRaw, 'm²')
                                );

                                $qtyUnit = trim($item->qty_unit ?? 'Lembar');
                            @endphp

                            <tr>
                                <td class="text-center">{{ $i + 1 }}</td>
                                <td>
                                    <b>{{ $item->product_name ?? '-' }}</b>
                                    @if(!empty($item->material_name))
                                        <div class="muted">Bahan: {{ $item->material_name }}</div>
                                    @endif
                                    @if(!empty($item->finishing_note))
                                        <div class="muted">Finishing: {{ $item->finishing_note }}</div>
                                    @endif
                                </td>
                                <td>{{ $item->file_name ?? '-' }}</td>
                                <td>
                                    @if($isMeter)
                                        {{ $item->size_description ?? '-' }}
                                    @else
                                        -
                                    @endif
                                </td>
                                <td class="text-right">
                                    {{ $item->qty ?? 0 }} {{ $qtyUnit }}
                                </td>
                                <td>{{ $item->notes ?? '-' }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            @empty
                <p class="text-center" style="color:#666;">Tidak ada piutang untuk customer ini.</p>
            @endforelse

            @if(env('APP_DEMO', false))
                <div class="demo-legal-note">
                    Demo mode aktif. Dokumen ini bukan surat penagihan resmi, bukan bukti utang yang sah,
                    tidak valid untuk penagihan lapangan, audit, penagihan hukum, penyerahan barang,
                    atau proses bisnis resmi lainnya.
                </div>
            @endif

            <div class="footer">
                <div>Dicetak pada: {{ now()->format('d M Y H:i:s') }}</div>
                <div>
                    @if(env('APP_DEMO', false))
                        Untuk Simulasi Demo
                    @else
                        Untuk Penagihan
                    @endif
                </div>
            </div>

            <div class="no-print">
                <button class="print-btn" onclick="window.print()">🖨️ Cetak</button>
            </div>
        </div>
    </div>
</body>
</html>