<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=80mm, initial-scale=1.0">
    <title>Nota {{ $order->invoice_number }}</title>

    <style>
        @media print {
            @page {
                size: 80mm auto;
                margin: 0;
            }
        }

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

        body {
            font-family: 'Courier New', monospace;
            font-size: 12px;
            width: 80mm;
            padding: 5mm;
            background: #fff;
            color: #000;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .receipt-shell {
            position: relative;
            min-height: 130mm;
        }

        .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(-32deg);
            font-size: 28px;
            line-height: 1;
            font-weight: 900;
            letter-spacing: 3px;
            text-transform: uppercase;
            white-space: nowrap;
            color: rgba(220, 38, 38, 0.10);
        }

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

        .header {
            text-align: center;
            margin-bottom: 10px;
            font-weight: bold;
        }

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

        .header .address {
            font-size: 12px;
            color: #000;
            font-weight: bold;
            margin-top: 2px;
        }

        .divider {
            border-bottom: 1px dashed #000;
            margin: 6px 0;
        }

        .divider-double {
            border-bottom: 2px dashed #000;
            margin: 8px 0;
        }

        .invoice-info {
            text-align: center;
            background: transparent;
        }

        .qrcode-wrapper {
            display: flex;
            justify-content: center;
            margin: 12px 0 6px 0;
        }

        .qrcode-box {
            background: #fff;
            padding: 6px;
        }

        .qrcode-box img,
        .qrcode-box svg {
            width: 140px;
            height: 140px;
            display: block;
        }

        .qrcode-box svg {
            shape-rendering: crispEdges;
        }

        .invoice-code {
            font-size: 14px;
            font-weight: bold;
            letter-spacing: 1px;
            margin-top: 4px;
        }

        .tax-status {
            text-align: center;
            font-size: 11px;
            font-weight: 900;
            margin-top: 5px;
        }

        .demo-warning-box {
            margin: 10px 0 8px 0;
            padding: 8px 7px;
            border: 2px solid #dc2626;
            background: rgba(220, 38, 38, 0.06);
            text-align: center;
        }

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

        .demo-warning-subtitle {
            font-size: 10px;
            font-weight: 900;
            color: #b91c1c;
            margin-top: 4px;
            line-height: 1.35;
            text-transform: uppercase;
        }

        .demo-warning-subtitle strong {
            color: #991b1b;
        }

        .row {
            display: flex;
            justify-content: space-between;
            font-weight: bold;
            font-size: 11px;
            gap: 8px;
        }

        .row span:first-child {
            flex-shrink: 0;
        }

        .row span:last-child {
            text-align: right;
            flex: 1;
        }

        .item {
            margin-bottom: 6px;
            padding-bottom: 4px;
            font-weight: bold;
            border-bottom: 1px dotted #ccc;
            background: transparent;
        }

        .item-name {
            font-weight: bold;
            font-size: 12px;
            word-break: break-word;
        }

        .item-detail {
            font-size: 10px;
            font-weight: bold;
            color: #000;
            word-break: break-word;
        }

        .item-price {
            display: flex;
            justify-content: space-between;
            font-weight: bold;
            font-size: 10px;
            gap: 8px;
        }

        .item-price span:first-child {
            flex: 1;
        }

        .item-price span:last-child {
            text-align: right;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .totals {
            margin-top: 9px;
            font-weight: bold;
            background: transparent;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            font-weight: bold;
            font-size: 11px;
            gap: 8px;
        }

        .grand-total {
            font-size: 15px;
            font-weight: bold;
            border-top: 1px solid #000;
            border-bottom: 1px solid #000;
            padding: 4px 0;
            margin-top: 4px;
        }

        .payment-row {
            display: flex;
            font-weight: bold;
            justify-content: space-between;
            font-size: 11px;
            gap: 8px;
        }

        .change {
            font-size: 14px;
            font-weight: bold;
        }

        .status-paid {
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin: 10px 0;
            padding: 6px;
            border: 2px solid #000;
            background: transparent;
        }

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

        .footer {
            text-align: center;
            margin-top: 12px;
            font-weight: bold;
            border-top: 1px dashed #000;
            padding-top: 6px;
            background: transparent;
        }

        .footer-text {
            font-size: 11px;
            font-weight: bold;
            word-break: break-word;
        }

        .footer-time {
            font-size: 10px;
            font-weight: bold;
            color: #000;
        }

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

<body onload="window.print()">

@php
    $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(300)
                ->margin(2)
                ->errorCorrection('H')
                ->generate($traceUrl);
        } elseif (class_exists('QrCode')) {
            $qrSvg = QrCode::format('svg')
                ->size(300)
                ->margin(2)
                ->errorCorrection('H')
                ->generate($traceUrl);
        }
    } catch (\Throwable $e) {
        $qrSvg = null;
    }

    $usePpn = (bool) ($order->use_ppn ?? false);
    $ppnRate = (float) ($order->ppn_rate ?? 0);
    $ppnAmount = (float) ($order->ppn_amount ?? 0);

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

    if ($subtotalBeforePpn <= 0) {
        $subtotalBeforePpn = (float) ($order->total_price ?? 0);

        if ($usePpn && $ppnAmount > 0) {
            $subtotalBeforePpn = max($subtotalBeforePpn - $ppnAmount, 0);
        }
    }

    if ($usePpn && $ppnAmount <= 0 && $ppnRate > 0) {
        $ppnAmount = round($subtotalBeforePpn * ($ppnRate / 100));
    }

    $grandTotal = $usePpn ? ($subtotalBeforePpn + $ppnAmount) : (float) ($order->total_price ?? $subtotalBeforePpn);

    $paidAmount = (float) ($order->paid_amount ?? $grandTotal);
    $changeAmount = max($paidAmount - $grandTotal, 0);

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

    $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, '/'));
        }
    }
@endphp

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

    <div class="receipt-content">
        <div class="header">
            @if($logoSrc)
                <img src="{{ $logoSrc }}" style="max-height:35px;">
            @endif

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

            @if($shopAddress)
                <div class="address">{{ $shopAddress }}</div>
            @endif

            @if($shopPhone)
                <div class="address">Telp: {{ $shopPhone }}</div>
            @endif
        </div>

        <div class="divider"></div>

        <div class="invoice-info">
            <div class="qrcode-wrapper">
                <div class="qrcode-box">
                    @if($qrSvg)
                        {!! $qrSvg !!}
                    @else
                        <div style="width:140px;height:140px;display:flex;align-items:center;justify-content:center;border:1px solid #000;font-size:10px;text-align:center;line-height:1.2;">
                            QR tidak tersedia<br>{{ $invoiceNumber }}
                        </div>
                    @endif
                </div>
            </div>

            <div class="invoice-code">
                {{ $invoiceNumber }}
            </div>

            <div class="tax-status">
                {{ $usePpn ? 'INVOICE + PPN ' . rtrim(rtrim(number_format($ppnRate, 2, ',', '.'), '0'), ',') . '%' : 'TANPA PPN' }}
            </div>
        </div>

        @if(env('APP_DEMO', false))
            <div class="demo-warning-box">
                <div class="demo-warning-title">Demo Mode</div>
                <div class="demo-warning-subtitle">
                    Nota ini adalah <strong>simulasi / percobaan</strong><br>
                    termasuk <strong>transaksi palsu</strong> dan <strong>bukan bukti pembayaran sah</strong>
                </div>
            </div>
        @endif

        <div class="divider"></div>

        <div class="invoice-info">
            <div class="row">
                <span>Tgl:</span>
                <span>{{ optional($order->paid_at)->format('d/m/Y H:i') ?: now()->format('d/m/Y H:i') }}</span>
            </div>

            <div class="row">
                <span>Pelanggan:</span>
                <span>{{ $order->customer_name }}</span>
            </div>

            <div class="row">
                <span>Kasir:</span>
                <span>{{ $order->cashier->name ?? '-' }}</span>
            </div>

            <div class="row">
                <span>Designer:</span>
                <span>{{ $order->designer->name ?? '-' }}</span>
            </div>
        </div>

        <div class="divider-double"></div>

        @foreach($order->items as $item)
            @php
                $qty = (float) ($item->qty ?? $item->quantity ?? 0);
                $price = (float) ($item->calculated_price ?? $item->unit_price ?? $item->price ?? 0);
                $subtotal = (float) ($item->subtotal ?? ($qty * $price));

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

            <div class="item">
                <div class="item-name">
                    {{ $item->product_name }} - {{ $item->file_name }}
                </div>

                <div class="item-detail">
                    {{ $item->size_description }} |
                    {{ ($item->sisi ?? 1) }} sisi |
                    {{ $item->material_name ?? '-' }}
                </div>

                <div class="item-price">
                    <span>
                        {{ rtrim(rtrim(number_format($qty, 2, ',', '.'), '0'), ',') }} x Rp {{ number_format($price,0,',','.') }}
                    </span>

                    <span>
                        Rp {{ number_format($subtotal,0,',','.') }}
                    </span>
                </div>
            </div>
        @endforeach

        <div class="divider"></div>

        <div class="totals">
            <div class="total-row">
                <span>Subtotal</span>
                <span>Rp {{ number_format($subtotalBeforePpn,0,',','.') }}</span>
            </div>

            @if($usePpn)
                <div class="total-row">
                    <span>PPN {{ rtrim(rtrim(number_format($ppnRate, 2, ',', '.'), '0'), ',') }}%</span>
                    <span>Rp {{ number_format($ppnAmount,0,',','.') }}</span>
                </div>
            @endif

            <div class="total-row grand-total">
                <span>TOTAL</span>
                <span>Rp {{ number_format($grandTotal,0,',','.') }}</span>
            </div>
        </div>

        <div class="payment-row">
            <span>Tunai</span>
            <span>Rp {{ number_format($paidAmount,0,',','.') }}</span>
        </div>

        <div class="payment-row change">
            <span>Kembalian</span>
            <span>Rp {{ number_format($changeAmount,0,',','.') }}</span>
        </div>

        <div class="status-paid">
            *** LUNAS ***
        </div>

        @if(env('APP_DEMO', false))
            <div class="demo-legal-note">
                Demo mode aktif · transaksi ini tidak valid untuk penagihan, audit,
                klaim pembayaran, pengambilan barang, atau bukti transaksi resmi
            </div>
        @endif

        <div class="footer">
            <div class="footer-text">
                {{ $shopFooter }}
            </div>

            <div class="footer-time">
                {{ now()->format('d/m/Y H:i:s') }}
            </div>
        </div>
    </div>
</div>

</body>
</html>
