<?php

declare(strict_types=1);

namespace App\Service\Pdf;

use App\Entity\Ecole;
use App\Service\PublicUrlGenerator;
use TCPDF;

final class PdfDocumentBranding
{
    public function __construct(
        private readonly string $projectDir,
        private readonly PublicUrlGenerator $publicUrlGenerator,
    ) {
    }

    public function publicImagePath(?string $relativePath): ?string
    {
        if (!$relativePath) {
            return null;
        }

        $path = $this->projectDir.'/public/'.ltrim($relativePath, '/');

        return is_file($path) ? $path : null;
    }

    public function buildQrPayload(
        string $documentType,
        ?Ecole $ecole,
        ?string $reference,
        ?string $matricule,
        ?string $status,
        \DateTimeInterface $generatedAt,
    ): string {
        if ($ecole !== null && $reference) {
            return $this->publicUrlGenerator->confirmationUrl($ecole, $reference);
        }

        $lines = [
            'Document : '.$documentType,
            'École : '.($ecole?->getNom() ?: '-'),
            'Dossier : '.($reference ?: '-'),
        ];

        if ($matricule) {
            $lines[] = 'Matricule : '.$matricule;
        }

        $lines[] = 'Statut : '.($status ?: '-');
        $lines[] = 'Date : '.$generatedAt->format('d/m/Y H:i');

        return implode("\n", $lines);
    }

    public function renderAdministrativeMarks(TCPDF $pdf, ?Ecole $ecole, float $x, float $y, float $w, float $h): void
    {
        $signaturePath = $this->publicImagePath($ecole?->getImageSignatureAdministration());
        $cachetPath = $this->publicImagePath($ecole?->getImageCachetAdministration());

        if (!$signaturePath && !$cachetPath) {
            $pdf->SetTextColor(30, 42, 56);
            $pdf->SetFont('dejavusans', 'B', 8.2);
            $pdf->SetXY($x, $y + ($h / 2) - 2);
            $pdf->Cell($w, 5, 'L’administration', 0, 0, 'C');

            return;
        }

        if ($signaturePath && $cachetPath) {
            $signatureWidth = min(34, $w * 0.74);
            $cachetWidth = min(18, $w * 0.42);
            $pdf->Image($signaturePath, $x + 1, $y + 1, $signatureWidth, min(12, $h - 1), '', '', '', true, 300, '', false, false, 0, true);
            $pdf->Image($cachetPath, $x + $w - $cachetWidth - 1, $y - 1, $cachetWidth, min(16, $h + 2), '', '', '', true, 300, '', false, false, 0, true);

            return;
        }

        $imagePath = $signaturePath ?: $cachetPath;
        $maxWidth = $signaturePath ? min(42, $w - 6) : min(30, $w - 6);
        $maxHeight = $signaturePath ? min(13, $h) : min(18, $h + 2);
        $imageX = $x + (($w - $maxWidth) / 2);

        $pdf->Image($imagePath, $imageX, $y - ($cachetPath ? 1 : 0), $maxWidth, $maxHeight, '', '', '', true, 300, '', false, false, 0, true);
    }
}
