<?php
require_once __DIR__ . '/functions.php';

function export_to_excel(string $filename, array $columns, array $rows): void
{
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $output = fopen('php://output', 'w');
    fputcsv($output, $columns);
    foreach ($rows as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
    exit;
}

function export_to_pdf(string $filename, string $title, array $columns, array $rows): void
{
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $contentLines = [];
    $contentLines[] = $title;
    $contentLines[] = str_repeat('=', strlen($title));
    $headerLine = implode(' | ', $columns);
    $contentLines[] = $headerLine;
    $contentLines[] = str_repeat('-', strlen($headerLine));

    foreach ($rows as $row) {
        $contentLines[] = implode(' | ', array_map('strval', $row));
    }

    $content = build_pdf_content($contentLines);
    echo $content;
    exit;
}

function build_pdf_content(array $lines): string
{
    $objects = [];
    $pdfHeader = "%PDF-1.3\n";

    $contentStream = "BT\n";
    $contentStream .= "/F1 14 Tf\n";

    $yPosition = 780;
    foreach ($lines as $index => $line) {
        $fontSize = $index <= 1 ? 16 : 11;
        if ($index === 0) {
            $fontSize = 18;
        }
        $contentStream .= sprintf("/F1 %d Tf\n", $fontSize);
        $contentStream .= sprintf("1 0 0 1 50 %.2f Tm\n", $yPosition);
        $contentStream .= '(' . pdf_escape_text($line) . ') Tj\n';
        $yPosition -= ($fontSize + 8);
        if ($yPosition < 60) {
            $contentStream .= sprintf("1 0 0 1 300 40 Tm\n(Footer) Tj\n");
            break;
        }
    }
    $contentStream .= "ET\n";

    $contentLength = strlen($contentStream);

    $objects[] = "<< /Type /Catalog /Pages 2 0 R >>";
    $objects[] = "<< /Type /Pages /Kids [3 0 R] /Count 1 >>";
    $objects[] = "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>";
    $objects[] = "<< /Length $contentLength >>\nstream\n$contentStream\nendstream";
    $objects[] = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>";

    $pdfBody = '';
    $offsets = [0];
    $currentOffset = strlen($pdfHeader);

    foreach ($objects as $index => $object) {
        $offsets[] = $currentOffset;
        $bodyPart = ($index + 1) . " 0 obj\n" . $object . "\nendobj\n";
        $pdfBody .= $bodyPart;
        $currentOffset += strlen($bodyPart);
    }

    $xrefOffset = strlen($pdfHeader . $pdfBody);
    $xref = 'xref\n0 ' . (count($objects) + 1) . "\n";
    $xref .= "0000000000 65535 f \n";
    for ($i = 1; $i <= count($objects); $i++) {
        $xref .= sprintf('%010d 00000 n \n', $offsets[$i]);
    }

    $trailer = 'trailer\n<< /Size ' . (count($objects) + 1) . ' /Root 1 0 R >>\n';
    $trailer .= 'startxref\n' . $xrefOffset . "\n%%EOF";

    return $pdfHeader . $pdfBody . $xref . $trailer;
}

function pdf_escape_text(string $text): string
{
    $text = preg_replace('/[\x00-\x1F\x7F]/', '', $text) ?? '';
    $text = str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], $text);
    return $text;
}
?>