<?php
declare(strict_types=1);

/**
 * مولّد PDF بسيط (نصي) بدون مكتبات خارجية.
 * يدعم خطوط قياسية (Helvetica). مناسب للتقارير الإدارية البسيطة.
 */

function pdf_output_lines(array $lines, string $title = 'Report'): string
{
    $lines = array_values(array_filter(array_map('strval', $lines), fn($x)=>$x!==''));
    $yStart = 800;   // points
    $lineHeight = 14;

    $content = "BT\n/F1 11 Tf\n";
    $y = $yStart;
    foreach ($lines as $ln) {
        $ln = preg_replace("/[\\r\\n]+/", " ", $ln);
        $ln = str_replace(["\\", "(", ")"], ["\\\\", "\\(", "\\)"], $ln);
        $content .= sprintf("1 0 0 1 40 %d Tm (%s) Tj\n", $y, $ln);
        $y -= $lineHeight;
        if ($y < 60) {
            // no multi-page in this tiny generator; stop gracefully
            $content .= sprintf("1 0 0 1 40 %d Tm (%s) Tj\n", 60, '... (تم اختصار التقرير) ...');
            break;
        }
    }
    $content .= "ET\n";

    $objects = [];

    // 1 Catalog
    $objects[] = "<< /Type /Catalog /Pages 2 0 R >>";
    // 2 Pages
    $objects[] = "<< /Type /Pages /Kids [3 0 R] /Count 1 >>";
    // 3 Page
    $objects[] = "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>";
    // 4 Font
    $objects[] = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>";
    // 5 Contents
    $stream = $content;
    $objects[] = "<< /Length " . strlen($stream) . " >>\nstream\n" . $stream . "endstream";

    $pdf = "%PDF-1.4\n";
    $offsets = [0];
    for ($i=0; $i<count($objects); $i++) {
        $offsets[] = strlen($pdf);
        $n = $i+1;
        $pdf .= "{$n} 0 obj\n{$objects[$i]}\nendobj\n";
    }

    $xrefPos = strlen($pdf);
    $pdf .= "xref\n0 " . (count($objects)+1) . "\n";
    $pdf .= "0000000000 65535 f \n";
    for ($i=1; $i<=count($objects); $i++) {
        $pdf .= sprintf("%010d 00000 n \n", $offsets[$i]);
    }
    $pdf .= "trailer\n<< /Size " . (count($objects)+1) . " /Root 1 0 R >>\nstartxref\n{$xrefPos}\n%%EOF";
    return $pdf;
}
