<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Services\PdfService;
use RuntimeException;

final class PdfController extends Controller
{
    public function __construct(private ?PdfService $service = null)
    {
        $this->service ??= new PdfService();
    }

    public function invoice(int $id): Response
    {
        try {
            $invoice = $this->service->invoice($id);
            $pdf = $this->service->render('invoice', ['invoice' => $invoice]);
            return Response::binary($pdf, 'application/pdf', $invoice['invoice_number'] . '.pdf', 'inline');
        } catch (RuntimeException $e) {
            return Response::html('<h1>' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</h1>', $e->getCode() >= 400 ? $e->getCode() : 500);
        }
    }

    public function receipt(int $id): Response
    {
        try {
            $data = $this->service->receipt($id);
            $pdf = $this->service->render('receipt', $data);
            return Response::binary($pdf, 'application/pdf', $data['receipt_number'] . '.pdf', 'inline');
        } catch (RuntimeException $e) {
            return Response::html('<h1>' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</h1>', $e->getCode() >= 400 ? $e->getCode() : 500);
        }
    }


    public function assessment(int $id): Response
    {
        try { $data=$this->service->assessment($id); $pdf=$this->service->render('assessment',$data); return Response::binary($pdf,'application/pdf',$data['assessment']['assessment_reference'].'.pdf','inline'); }
        catch(RuntimeException $e){return Response::html('<h1>'.htmlspecialchars($e->getMessage(),ENT_QUOTES,'UTF-8').'</h1>',$e->getCode()>=400?$e->getCode():500);}
    }

    public function report(int $id): Response
    {
        try {
            $data = $this->service->report($id);
            $pdf = $this->service->render('report', $data);
            return Response::binary($pdf, 'application/pdf', $data['report']['report_reference'] . '-v' . $data['version']['version_number'] . '.pdf', 'inline');
        } catch (RuntimeException $e) {
            return Response::html('<h1>' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . '</h1>', $e->getCode() >= 400 ? $e->getCode() : 500);
        }
    }
}
