<?php
declare(strict_types=1);

namespace App\Services;

class PDFService
{
    public static function simpleText(string $title, array $lines): string
    {
        $objects = [];
        $offsets = [];
        $buffer = "%PDF-1.4\n";
        $addObj = function (string $content) use (&$objects) {
            $objects[] = $content;
            return count($objects);
        };
        $pagesKids = [];
        $fontObj = $addObj("<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>");
        $content = "BT /F1 12 Tf 50 750 Td (" . self::escape($title) . ") Tj ET\n";
        $y = 730;
        foreach ($lines as $line) {
            $content .= "BT /F1 10 Tf 50 $y Td (" . self::escape($line) . ") Tj ET\n";
            $y -= 16;
        }
        $stream = "<< /Length " . strlen($content) . " >>\nstream\n" . $content . "endstream";
        $contentObj = $addObj($stream);
        $pageObj = $addObj("<< /Type /Page /Parent 0 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 " . $fontObj . " 0 R >> >> /Contents " . $contentObj . " 0 R >>");
        $pagesKids[] = $pageObj;
        $pagesObj = $addObj("<< /Type /Pages /Kids [" . implode(' 0 R ', $pagesKids) . " 0 R] /Count " . count($pagesKids) . " >>");
        $catalogObj = $addObj("<< /Type /Catalog /Pages " . $pagesObj . " 0 R >>");
        $xrefPos = strlen($buffer);
        foreach ($objects as $i => $obj) {
            $offsets[$i + 1] = strlen($buffer);
            $buffer .= ($i + 1) . " 0 obj\n" . $obj . "\nendobj\n";
        }
        $buffer .= "xref\n0 " . (count($objects) + 1) . "\n0000000000 65535 f \n";
        foreach ($offsets as $off) {
            $buffer .= str_pad((string)$off, 10, '0', STR_PAD_LEFT) . " 00000 n \n";
        }
        $buffer .= "trailer\n<< /Size " . (count($objects) + 1) . " /Root " . $catalogObj . " 0 R >>\nstartxref\n" . strlen($buffer) . "\n%%EOF";
        return $buffer;
    }

    private static function escape(string $text): string
    {
        return str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $text);
    }
}
