<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ $receipt->receipt_number }}</title>
    @if(isset($templateView) && view()->exists($templateView))
        @php
            $templateContent = view($templateView, ['payment' => $payment])->render();
            preg_match_all('/<style[^>]*>(.*?)<\/style>/is', $templateContent, $styleMatches);
            $styles = !empty($styleMatches[1]) ? '<style>' . implode('</style><style>', $styleMatches[1]) . '</style>' : '';
            $bodyContent = $templateContent;
            if (preg_match('/<body[^>]*>(.*?)<\/body>/is', $templateContent, $bodyMatches)) {
                $bodyContent = $bodyMatches[1];
            }
            $bodyContent = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $bodyContent);
        @endphp
        {!! $styles !!}
    @endif
    <style>
        @page {
            size: A4 portrait;
            margin: 12mm;
        }
        html, body {
            margin: 0;
            background: #fff !important;
            color-adjust: exact;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        @media print {
            html, body {
                width: 210mm;
                min-height: 297mm;
            }
            body { margin: 0; }
        }
    </style>
</head>
<body>
    @if(isset($bodyContent))
        {!! $bodyContent !!}
    @else
        <div style="padding: 24px; font-family: system-ui, -apple-system, Segoe UI, Roboto, sans-serif;">
            <h1 style="margin: 0 0 8px;">Receipt {{ $receipt->receipt_number }}</h1>
            <p style="margin: 0;">Template not found.</p>
        </div>
    @endif
    <script>
        window.addEventListener('load', function () {
            window.print();
        });
    </script>
</body>
</html>
