<?php
class PageController
{
    public function home(): void
    {
        $settings = Settings::safeAll();
        View::render('home', ['settings' => $settings, 'trainingContents' => TrainingContent::all(true)]);
    }

    public function paymentReceipt(): void
    {
        $receipt = PaymentReceipt::findByCode((string)($_GET['code'] ?? ''));
        if (!$receipt) {
            http_response_code(404);
            exit('Comprovante não encontrado.');
        }
        $actor = Communication::actorByTypeAndId((string)$receipt['recipient_type'], (int)$receipt['recipient_id']);
        $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $shareUrl = $host !== '' ? $scheme . '://' . $host . url('receipt/view', ['code' => $receipt['receipt_code']]) : url('receipt/view', ['code' => $receipt['receipt_code']]);
        View::render('receipt', [
            'receipt' => $receipt,
            'recipient' => $actor ?: [],
            'shareUrl' => $shareUrl,
        ]);
    }

    public function paymentReceiptImage(): void
    {
        $receipt = PaymentReceipt::findByCode((string)($_GET['code'] ?? ''));
        if (!$receipt) {
            http_response_code(404);
            exit('Comprovante não encontrado.');
        }
        while (ob_get_level() > 0) ob_end_clean();
        $download = !empty($_GET['download']);
        $fileName = 'comprovante-' . preg_replace('/[^A-Z0-9]/', '', (string)$receipt['receipt_code']) . '.svg';
        header('Content-Type: image/svg+xml; charset=UTF-8');
        header('Content-Disposition: ' . ($download ? 'attachment' : 'inline') . '; filename="' . $fileName . '"');
        header('Cache-Control: public, max-age=300');
        header('X-Content-Type-Options: nosniff');
        echo PaymentReceipt::svg($receipt);
        exit;
    }
}
