<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Invoice {{ $order->invoice_number ?? $order->id }}</title>

    @php
        $paperSize = $paperSize ?? request('paper', 'a4');

        if (!in_array($paperSize, ['a4', 'a5', '215x165'], true)) {
            $paperSize = 'a4';
        }

        $isA4 = $paperSize === 'a4';
        $isA5 = $paperSize === 'a5';
        $isCustom = $paperSize === '215x165';

        /*
         * A5 dibuat LANDSCAPE supaya tidak gampang jadi 2 halaman.
         * Ukuran 21,5 x 16,5 juga landscape sesuai kebutuhan nota/faktur custom.
         */
        $pageCss = match ($paperSize) {
            'a5' => 'size: A5 landscape; margin: 8mm;',
            '215x165' => 'size: 215mm 165mm; margin: 7mm;',
            default => 'size: A4 portrait; margin: 13mm 15mm;',
        };

        $fontSize = match ($paperSize) {
            'a5' => '10px',
            '215x165' => '10px',
            default => '12px',
        };

        $titleSize = match ($paperSize) {
            'a5' => '23px',
            '215x165' => '23px',
            default => '30px',
        };

        $logoWidth = match ($paperSize) {
            'a5' => '110px',
            '215x165' => '112px',
            default => '165px',
        };

        $logoHeight = match ($paperSize) {
            'a5' => '38px',
            '215x165' => '40px',
            default => '62px',
        };

        $qrSize = match ($paperSize) {
            'a5' => 66,
            '215x165' => 70,
            default => 88,
        };

        $minRows = match ($paperSize) {
            'a5' => 2,
            '215x165' => 3,
            default => 7,
        };

        $safeShopName = $shopName ?? config('app.name');
        $safeShopAddress = $shopAddress ?? '';
        $safeShopPhone = $shopPhone ?? '';
        $safeShopFooter = $shopFooter ?? '';
    @endphp

    <style>
        @page { {{ $pageCss }} }

        * {
            box-sizing: border-box;
        }

        html,
        body {
            margin: 0;
            padding: 0;
            background: #ffffff;
            color: #111827;
            font-family: Arial, Helvetica, sans-serif;
            font-size: {{ $fontSize }};
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .no-print {
            margin-bottom: 10px;
            text-align: right;
        }

        .print-btn {
            background: #2563eb;
            color: #ffffff;
            border: 1px solid #1d4ed8;
            border-radius: 7px;
            padding: 7px 12px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 700;
        }


        .print-toolbar {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            flex-wrap: wrap;
            gap: 6px;
            margin-bottom: 10px;
        }

        .print-size-btn {
            display: inline-block;
            background: #ffffff;
            color: #1d4ed8;
            border: 1px solid #bfdbfe;
            border-radius: 7px;
            padding: 7px 10px;
            cursor: pointer;
            font-size: 11px;
            font-weight: 800;
            text-decoration: none;
            line-height: 1;
        }

        .print-size-btn:hover {
            background: #eff6ff;
            border-color: #2563eb;
        }

        .print-size-btn.active {
            background: #2563eb;
            color: #ffffff;
            border-color: #1d4ed8;
        }

        .print-size-btn.pos {
            background: #0f172a;
            color: #ffffff;
            border-color: #0f172a;
        }


        .invoice-page {
            width: 100%;
            padding: {{ $isA4 ? '2mm 1mm' : '1.5mm 2mm 1mm' }};
            page-break-after: avoid;
            page-break-inside: avoid;
            overflow: hidden;
        }

        .header-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: {{ $isA4 ? '16px' : '10px' }};
        }

        .header-table td {
            vertical-align: top;
        }

        .header-left {
            width: 58%;
            padding-top: 4px;
        }

        .header-right {
            width: 42%;
            text-align: right;
        }

        .logo {
            max-width: {{ $logoWidth }};
            max-height: {{ $logoHeight }};
            object-fit: contain;
            display: block;
            margin-bottom: {{ $isA4 ? '8px' : '5px' }};
        }

        .shop-name {
            font-size: {{ $isA4 ? '21px' : '16px' }};
            font-weight: 900;
            line-height: 1.15;
            color: #0f172a;
            margin-bottom: 4px;
        }

        .shop-meta {
            font-size: {{ $isA4 ? '11.5px' : '9.5px' }};
            line-height: 1.35;
            color: #475569;
        }

        .invoice-title {
            font-size: {{ $titleSize }};
            line-height: 1;
            font-weight: 900;
            letter-spacing: .14em;
            color: #1d4ed8;
        }

        .invoice-number {
            margin-top: 5px;
            font-size: {{ $isA4 ? '12.5px' : '10.5px' }};
            font-weight: 900;
            color: #111827;
        }

        .qr-wrap {
            display: inline-block;
            margin-top: {{ $isA4 ? '10px' : '6px' }};
            text-align: center;
        }

        .qr-wrap img,
        .qr-wrap svg {
            width: {{ $qrSize }}px;
            height: {{ $qrSize }}px;
            display: block;
        }

        .qr-wrap svg {
            shape-rendering: crispEdges;
        }

        .qr-text {
            margin-top: 3px;
            max-width: {{ $qrSize + 24 }}px;
            color: #64748b;
            font-size: {{ $isA4 ? '9.5px' : '8px' }};
            line-height: 1.2;
            text-align: center;
        }
};
            height: {{ $isA4 ? '13px' : '11px' }};
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1.5px solid #111827;
            font-size: {{ $isA4 ? '10px' : '8px' }};
            font-weight: 900;
            line-height: 1;
        }

        .info-table {
            width: 100%;
            border: 1px solid #cbd5e1;
            border-collapse: separate;
            border-spacing: 0;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: {{ $isA4 ? '16px' : '11px' }};
        }

        .info-table > tbody > tr > td {
            width: 50%;
            vertical-align: top;
            padding: {{ $isA4 ? '11px 13px' : '8px 11px' }};
        }

        .info-table > tbody > tr > td + td {
            border-left: 1px solid #cbd5e1;
        }

        .section-title {
            margin-bottom: {{ $isA4 ? '8px' : '6px' }};
            color: #1d4ed8;
            font-size: {{ $isA4 ? '12.5px' : '10.5px' }};
            font-weight: 900;
            line-height: 1.15;
        }

        .data-row {
            width: 100%;
            border-collapse: collapse;
        }

        .data-row td {
            width: auto;
            border: 0 !important;
            padding: 2px 0 !important;
            line-height: 1.35;
            vertical-align: top;
        }

        .data-row .label {
            width: {{ $isA4 ? '76px' : '58px' }};
            color: #64748b;
            white-space: nowrap;
        }

        .data-row .sep {
            width: 10px;
            color: #64748b;
            text-align: center;
        }

        .items {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
        }

        .items th,
        .items td {
            border: 1px solid #94a3b8;
            padding: {{ $isA4 ? '7px 9px' : '5px 7px' }};
            vertical-align: top;
            line-height: {{ $isA4 ? '1.35' : '1.25' }};
        }

        .items th {
            background: #eff6ff;
            color: #1e3a8a;
            font-weight: 900;
            text-align: left;
            font-size: {{ $isA4 ? '11.5px' : '9.5px' }};
        }

        .items td {
            height: {{ $isA4 ? '30px' : '24px' }};
            font-size: {{ $fontSize }};
        }

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

        .col-no { width: {{ $isA4 ? '40px' : '34px' }}; }
        .col-qty { width: {{ $isA4 ? '62px' : '52px' }}; }
        .col-price { width: {{ $isA4 ? '112px' : '94px' }}; }
        .col-total { width: {{ $isA4 ? '122px' : '102px' }}; }

        .summary-wrap {
            width: 100%;
            margin-top: {{ $isA4 ? '16px' : '11px' }};
            page-break-inside: avoid;
        }

        .summary {
            width: {{ $isA4 ? '44%' : '42%' }};
            margin-left: auto;
            border-collapse: collapse;
        }

        .summary td {
            border: 1px solid #cbd5e1;
            padding: {{ $isA4 ? '7px 9px' : '5px 8px' }};
            line-height: 1.25;
        }

        .summary .label {
            color: #334155;
            font-weight: 900;
        }

        .summary .value {
            text-align: right;
            font-weight: 900;
        }

        .summary .grand td {
            background: #1d4ed8;
            color: #ffffff;
            font-size: {{ $isA4 ? '16px' : '13.5px' }};
            font-weight: 900;
        }

        .footer-sign {
            width: 100%;
            border-collapse: collapse;
            margin-top: {{ $isA4 ? '22px' : '13px' }};
            page-break-inside: avoid;
        }

        .footer-sign td {
            width: 50%;
            vertical-align: top;
            padding: 0;
        }

        .footer-left {
            color: #64748b;
            font-size: {{ $isA4 ? '10.5px' : '8.8px' }};
            line-height: 1.45;
            padding-right: 12px !important;
        }

        .footer-right {
            text-align: center;
            font-size: {{ $isA4 ? '11.5px' : '10px' }};
            color: #111827;
        }

        .sign-space {
            height: {{ $isA4 ? '64px' : '30px' }};
        }

        .small-note {
            margin-top: {{ $isA4 ? '11px' : '6px' }};
            color: #64748b;
            font-size: {{ $isA4 ? '10.5px' : '8.5px' }};
            line-height: 1.4;
        }

        .custom-hide {
            display: {{ $isA4 ? 'block' : 'none' }};
        }

        @media print {
            .no-print {
                display: none !important;
            }

            .invoice-page {
                page-break-after: avoid !important;
                page-break-inside: avoid !important;
                overflow: hidden !important;
            }
        }
    </style>
</head>

<body onload="window.print()">
@php
    $items = collect($order->items ?? []);
    $blankRows = max($minRows - $items->count(), 0);

    $isUsePpn = (bool) ($usePpn ?? ($order->use_ppn ?? false));

    $baseTotal = (float) ($order->subtotal_before_ppn ?? 0);

    if ($baseTotal <= 0) {
        $baseTotal = (float) ($order->total_price ?? $order->total ?? $order->grand_total ?? 0);

        if ($isUsePpn && (($order->ppn_amount ?? 0) > 0)) {
            $baseTotal = max($baseTotal - (float) $order->ppn_amount, 0);
        }
    }

    $ppnAmountFromOrder = (float) ($order->ppn_amount ?? 0);
    $ppnRateValue = (float) ($ppnRate ?? ($order->ppn_rate ?? 0));
    $ppnAmount = $isUsePpn ? ($ppnAmountFromOrder > 0 ? $ppnAmountFromOrder : round($baseTotal * ($ppnRateValue / 100))) : 0;
    $grandTotal = $baseTotal + $ppnAmount;

    $paidAmount = 0;

    if (isset($order->total_paid)) {
        $paidAmount = (float) $order->total_paid;
    } elseif (isset($order->paid_amount)) {
        $paidAmount = (float) $order->paid_amount;
    } elseif (isset($order->amount_paid)) {
        $paidAmount = (float) $order->amount_paid;
    }

    $remainingAmount = max($grandTotal - $paidAmount, 0);

    if ($remainingAmount <= 1) {
        $remainingAmount = 0;
    }

    $invoiceNumber = $order->invoice_number ?? ('INV-' . $order->id);
    $traceUrl = url('/trace-order?search=' . urlencode($invoiceNumber));

    /*
     * QR dibuat SVG supaya aman di hosting yang tidak punya GD/Imagick.
     * Penyebab barcode sebelumnya tidak muncul biasanya karena format PNG gagal dibuat,
     * lalu tertangkap catch dan $qr menjadi null.
     */
    $qrSvg = null;

    try {
        if (class_exists(\SimpleSoftwareIO\QrCode\Facades\QrCode::class)) {
            $qrSvg = \SimpleSoftwareIO\QrCode\Facades\QrCode::format('svg')
                ->size(260)
                ->margin(1)
                ->errorCorrection('H')
                ->generate($traceUrl);
        } elseif (class_exists('QrCode')) {
            $qrSvg = QrCode::format('svg')
                ->size(260)
                ->margin(1)
                ->errorCorrection('H')
                ->generate($traceUrl);
        }
    } catch (\Throwable $e) {
        $qrSvg = null;
    }

    $customerName = $order->customer_name ?? optional($order->customer ?? null)->name ?? '-';
    $customerPhone = $order->customer_phone ?? optional($order->customer ?? null)->phone ?? '-';

    $logoSrc = '';

    if (!empty($shopLogo)) {
        if (str_starts_with($shopLogo, 'http://') || str_starts_with($shopLogo, 'https://') || str_starts_with($shopLogo, '/') || str_starts_with($shopLogo, 'data:image')) {
            $logoSrc = $shopLogo;
        } else {
            $logoSrc = asset('storage/' . ltrim($shopLogo, '/'));
        }
    }

    $paperLabel = match ($paperSize) {
        'a5' => 'A5 Landscape',
        '215x165' => '21,5 × 16,5 cm',
        default => 'A4',
    };

    $isPaid = false;

    try {
        $isPaid = method_exists($order, 'isPaid') ? $order->isPaid() : (($order->payment_status ?? null) === 'paid');
    } catch (\Throwable $e) {
        $isPaid = false;
    }

    $statusLabel = $isPaid ? 'Lunas' : (($order->is_credit ?? false) ? 'Piutang' : 'Belum Lunas');
@endphp

<div class="invoice-page">
    <div class="no-print">
        @php
            $paperUrl = fn ($paper) => request()->fullUrlWithQuery(['paper' => $paper]);
            $pos80Url = \Illuminate\Support\Facades\Route::has('kasir.receipt')
                ? route('kasir.receipt', $order)
                : null;
        @endphp

        <div class="print-toolbar">
            <span style="color:#64748b;margin-right:8px;">Ukuran: {{ $paperLabel }}</span>

            <a href="{{ $paperUrl('a4') }}" class="print-size-btn {{ $paperSize === 'a4' ? 'active' : '' }}">
                Cetak A4
            </a>

            <a href="{{ $paperUrl('a5') }}" class="print-size-btn {{ $paperSize === 'a5' ? 'active' : '' }}">
                Cetak A5
            </a>

            <a href="{{ $paperUrl('215x165') }}" class="print-size-btn {{ $paperSize === '215x165' ? 'active' : '' }}">
                Cetak 21,5 × 16,5
            </a>

            @if($pos80Url)
                <a href="{{ $pos80Url }}" class="print-size-btn pos">
                    Cetak POS 80
                </a>
            @endif

            <button class="print-btn" onclick="window.print()">Print Sekarang</button>
        </div>
    </div>

    <table class="header-table">
        <tr>
            <td class="header-left">
                @if($logoSrc)
                    <img src="{{ $logoSrc }}" class="logo" alt="Logo">
                @endif

                <div class="shop-name">{{ $safeShopName }}</div>

                <div class="shop-meta">
                    @if($safeShopAddress)
                        {{ $safeShopAddress }}<br>
                    @endif

                    @if($safeShopPhone)
                        Telp: {{ $safeShopPhone }}
                    @endif
                </div>
            </td>

            <td class="header-right">
                <div class="invoice-title">INVOICE</div>
                <div class="invoice-number">{{ $invoiceNumber }}</div>

                <div class="qr-wrap">
                    @if($qrSvg)
                        {!! $qrSvg !!}
                    @else
                        <div style="width:{{ $qrSize }}px;height:{{ $qrSize }}px;display:flex;align-items:center;justify-content:center;border:1px solid #cbd5e1;font-size:8px;text-align:center;line-height:1.2;color:#64748b;">
                            QR tidak tersedia<br>{{ $invoiceNumber }}
                        </div>
                    @endif
                    <div class="qr-text">Scan untuk trace order</div>
                </div>
            </td>
        </tr>
    </table>

    <table class="info-table">
        <tr>
            <td>
                <div class="section-title">Kepada</div>
                <table class="data-row">
                    <tr>
                        <td class="label">Nama</td>
                        <td class="sep">:</td>
                        <td>{{ $customerName }}</td>
                    </tr>
                    <tr>
                        <td class="label">No HP</td>
                        <td class="sep">:</td>
                        <td>{{ $customerPhone ?: '-' }}</td>
                    </tr>
                    <tr>
                        <td class="label">Status</td>
                        <td class="sep">:</td>
                        <td>{{ $statusLabel }}</td>
                    </tr>
                </table>
            </td>

            <td>
                <div class="section-title">Detail Invoice</div>
                <table class="data-row">
                    <tr>
                        <td class="label">Tanggal</td>
                        <td class="sep">:</td>
                        <td>{{ optional($order->created_at)->format('d/m/Y H:i') }}</td>
                    </tr>
                    <tr>
                        <td class="label">No Invoice</td>
                        <td class="sep">:</td>
                        <td>{{ $invoiceNumber }}</td>
                    </tr>
                    @if($isUsePpn && (($taxSetting->npwp ?? null) || ($taxSetting->pkp_name ?? null)))
                        <tr>
                            <td class="label">NPWP/PKP</td>
                            <td class="sep">:</td>
                            <td>{{ $taxSetting->npwp ?: $taxSetting->pkp_name }}</td>
                        </tr>
                    @endif
                </table>
            </td>
        </tr>
    </table>

    <table class="items">
        <thead>
            <tr>
                <th class="col-no center">No</th>
                <th>Item</th>
                <th class="col-qty center">Qty</th>
                <th class="col-price right">Harga</th>
                <th class="col-total right">Subtotal</th>
            </tr>
        </thead>
        <tbody>
            @forelse($items as $index => $item)
                @php
                    $qty = (float) ($item->qty ?? $item->quantity ?? 0);
                    $price = (float) ($item->calculated_price ?? $item->unit_price ?? $item->price ?? $item->harga ?? 0);
                    $subtotal = (float) ($item->subtotal ?? $item->total ?? ($qty * $price));

                    if ($price <= 0 && $qty > 0 && $subtotal > 0) {
                        $price = $subtotal / $qty;
                    }

                    $itemDesc = collect([
                        $item->product_name ?? $item->name ?? optional($item->product ?? null)->name ?? null,
                        !empty($item->file_name) ? 'File: ' . $item->file_name : null,
                        !empty($item->size_description) ? 'Ukuran: ' . $item->size_description : null,
                        !empty($item->material_name) ? 'Bahan: ' . $item->material_name : null,
                        !empty($item->finishing_note) ? 'Finishing: ' . $item->finishing_note : null,
                    ])->filter()->implode(' | ');
                @endphp

                <tr>
                    <td class="center">{{ $index + 1 }}</td>
                    <td>{{ $itemDesc ?: '-' }}</td>
                    <td class="center">{{ rtrim(rtrim(number_format($qty, 2, ',', '.'), '0'), ',') }}</td>
                    <td class="right">Rp {{ number_format($price, 0, ',', '.') }}</td>
                    <td class="right">Rp {{ number_format($subtotal, 0, ',', '.') }}</td>
                </tr>
            @empty
                <tr>
                    <td class="center">1</td>
                    <td colspan="4">-</td>
                </tr>
            @endforelse

            @for($i = 0; $i < $blankRows; $i++)
                <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                </tr>
            @endfor
        </tbody>
    </table>

    <div class="summary-wrap">
        <table class="summary">
            <tr>
                <td class="label">Subtotal</td>
                <td class="value">Rp {{ number_format($baseTotal, 0, ',', '.') }}</td>
            </tr>

            @if($isUsePpn)
                <tr>
                    <td class="label">PPN {{ rtrim(rtrim(number_format($ppnRateValue, 2, ',', '.'), '0'), ',') }}%</td>
                    <td class="value">Rp {{ number_format($ppnAmount, 0, ',', '.') }}</td>
                </tr>
            @endif

            <tr class="grand">
                <td>TOTAL</td>
                <td class="value">Rp {{ number_format($grandTotal, 0, ',', '.') }}</td>
            </tr>

            @if($paidAmount > 0)
                <tr>
                    <td class="label">Terbayar</td>
                    <td class="value">Rp {{ number_format($paidAmount, 0, ',', '.') }}</td>
                </tr>

                <tr>
                    <td class="label">Sisa</td>
                    <td class="value">Rp {{ number_format($remainingAmount, 0, ',', '.') }}</td>
                </tr>
            @endif
        </table>
    </div>

    <table class="footer-sign">
        <tr>
            <td class="footer-left">
                @if($safeShopFooter)
                    {{ $safeShopFooter }}
                @else
                    Terima kasih atas kepercayaan Anda.
                @endif

                @if($isUsePpn && ($taxSetting->notes ?? null) && $isA4)
                    <div class="small-note">{{ $taxSetting->notes }}</div>
                @endif
            </td>

            <td class="footer-right">
                Hormat Kami,
                <div class="sign-space"></div>
                <strong>{{ $safeShopName }}</strong>
            </td>
        </tr>
    </table>
</div>
</body>
</html>
