<?php
$code = (string)$receipt['receipt_code'];
$imageUrl = url('receipt/image', ['code' => $code]);
$fallbackDownloadUrl = url('receipt/image', ['code' => $code, 'download' => 1]);
$phone = (string)($recipient['whatsapp'] ?? '');
$message = 'Olá ' . ($receipt['client_name'] ?? 'cliente') . '! Seu pagamento foi confirmado. Comprovante: ' . $shareUrl;
$whatsapp = $phone !== '' ? whatsapp_url($phone, $message) : 'https://wa.me/?text=' . rawurlencode($message);
?>
<main class="container py-4 py-md-5 receipt-page">
    <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-center gap-3 mb-4">
        <div>
            <span class="badge text-bg-success rounded-pill px-3 py-2 mb-2"><i class="bi bi-check-circle"></i> Pagamento confirmado</span>
            <h1 class="h3 fw-bold text-cfc-dark mb-1">Comprovante de pagamento</h1>
            <p class="text-muted mb-0">Documento digital salvo no perfil do cliente.</p>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <button type="button" class="btn btn-outline-primary rounded-pill" id="downloadReceipt" data-image="<?= e($imageUrl) ?>" data-fallback="<?= e($fallbackDownloadUrl) ?>" data-code="<?= e($code) ?>"><i class="bi bi-download"></i> Baixar PNG</button>
            <button type="button" class="btn btn-primary rounded-pill" id="shareReceipt" data-image="<?= e($imageUrl) ?>" data-url="<?= e($shareUrl) ?>" data-code="<?= e($code) ?>"><i class="bi bi-share"></i> Compartilhar imagem</button>
            <a class="btn btn-success rounded-pill" target="_blank" rel="noopener" href="<?= e($whatsapp) ?>"><i class="bi bi-whatsapp"></i> Enviar link</a>
        </div>
    </div>
    <div class="receipt-preview-shell mx-auto">
        <img class="receipt-preview-image" src="<?= e($imageUrl) ?>" alt="Comprovante de pagamento <?= e($code) ?>">
    </div>
</main>
<script>
(() => {
    async function receiptPngFile(imageUrl, code) {
        const response = await fetch(imageUrl, {credentials:'same-origin'});
        if (!response.ok) throw new Error('Não foi possível carregar o comprovante.');
        const svgBlob = await response.blob();
        const objectUrl = URL.createObjectURL(svgBlob);
        try {
            const image = await new Promise((resolve, reject) => {
                const img = new Image();
                img.onload = () => resolve(img);
                img.onerror = () => reject(new Error('Não foi possível converter o comprovante.'));
                img.src = objectUrl;
            });
            const canvas = document.createElement('canvas');
            canvas.width = 1080;
            canvas.height = 1350;
            const context = canvas.getContext('2d');
            context.fillStyle = '#eaf3ff';
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.drawImage(image, 0, 0, canvas.width, canvas.height);
            const pngBlob = await new Promise((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('Não foi possível gerar a imagem PNG.')), 'image/png', .96));
            return new File([pngBlob], `comprovante-${code}.png`, {type:'image/png', lastModified:Date.now()});
        } finally {
            URL.revokeObjectURL(objectUrl);
        }
    }

    const downloadButton = document.getElementById('downloadReceipt');
    downloadButton?.addEventListener('click', async () => {
        const old = downloadButton.innerHTML;
        downloadButton.disabled = true;
        downloadButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Gerando PNG...';
        try {
            const file = await receiptPngFile(downloadButton.dataset.image, downloadButton.dataset.code);
            const url = URL.createObjectURL(file);
            const anchor = document.createElement('a');
            anchor.href = url;
            anchor.download = file.name;
            document.body.appendChild(anchor);
            anchor.click();
            anchor.remove();
            setTimeout(() => URL.revokeObjectURL(url), 1500);
        } catch (_) {
            location.href = downloadButton.dataset.fallback;
        } finally {
            downloadButton.disabled = false;
            downloadButton.innerHTML = old;
        }
    });

    const shareButton = document.getElementById('shareReceipt');
    shareButton?.addEventListener('click', async () => {
        const url = shareButton.dataset.url || location.href;
        const old = shareButton.innerHTML;
        shareButton.disabled = true;
        shareButton.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Preparando...';
        try {
            const file = await receiptPngFile(shareButton.dataset.image, shareButton.dataset.code);
            if (navigator.canShare && navigator.canShare({files:[file]})) {
                await navigator.share({title:'Comprovante de pagamento', text:'Pagamento confirmado.', files:[file]});
            } else if (navigator.share) {
                await navigator.share({title:'Comprovante de pagamento', text:'Pagamento confirmado.', url});
            } else {
                await navigator.clipboard.writeText(url);
                alert('Link do comprovante copiado.');
            }
        } catch (error) {
            if (!error || error.name !== 'AbortError') window.open('https://wa.me/?text=' + encodeURIComponent('Comprovante de pagamento: ' + url), '_blank', 'noopener');
        } finally {
            shareButton.disabled = false;
            shareButton.innerHTML = old;
        }
    });
})();
</script>
