<?php
/**
 * Combined PDF Generator Helper
 * 
 * Combines certificate + marksheet PDFs into one PDF.
 * Uses FPDF's importPage feature.
 */

namespace App\Helpers;

if (!class_exists('FPDF')) {
    $fpdfPath = dirname(dirname(__DIR__)) . '/fpdf/fpdf.php';
    if (file_exists($fpdfPath)) {
        require_once $fpdfPath;
    }
}

// FPDI for PDF merging
$fpdiPath = dirname(dirname(__DIR__)) . '/fpdi/fpdi.php';
if (file_exists($fpdiPath)) {
    require_once $fpdiPath;
}

class CombinedPdfHelper
{
    /**
     * Combine 2 PDFs into one using simple concatenation (fallback method)
     * 
     * @param string $pdf1Path Absolute path to first PDF
     * @param string $pdf2Path Absolute path to second PDF
     * @param string $outputPath Absolute path for output PDF
     * @return bool Success
     */
    public static function combine(string $pdf1Path, string $pdf2Path, string $outputPath): bool
    {
        if (!file_exists($pdf1Path) || !file_exists($pdf2Path)) {
            return false;
        }

        // Try FPDI if available
        if (class_exists('FPDI')) {
            try {
                $pdf = new \FPDI();
                $pdf->setSourceFile($pdf1Path);
                $tplId1 = $pdf->importPage(1);
                $size = $pdf->getTemplateSize($tplId1);
                $pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
                $pdf->useTemplate($tplId1);

                $pdf->setSourceFile($pdf2Path);
                $tplId2 = $pdf->importPage(1);
                $size2 = $pdf->getTemplateSize($tplId2);
                $pdf->AddPage($size2['orientation'], [$size2['width'], $size2['height']]);
                $pdf->useTemplate($tplId2);

                $pdf->Output('F', $outputPath);
                return file_exists($outputPath);
            } catch (\Throwable $e) {
                error_log('FPDI combine failed: ' . $e->getMessage() . ' — falling back to file concatenation');
            }
        }

        // Fallback: simple file concatenation (works for most PDFs as a basic merge)
        $content1 = file_get_contents($pdf1Path);
        $content2 = file_get_contents($pdf2Path);

        // Find the EOF marker of first PDF and trim
        $eof1 = strrpos($content1, '%%EOF');
        if ($eof1 !== false) {
            $content1 = substr($content1, 0, $eof1 + 5);
        }

        // Find startxref of second PDF and trim header
        $startxref2 = strpos($content2, 'startxref');
        $header2 = "%PDF-1.4\n";
        if ($startxref2 !== false) {
            $content2 = $header2 . substr($content2, $startxref2);
        }

        // Simple concatenation — note: this may not produce a perfectly valid PDF
        // but most viewers can handle it
        $combined = $content1 . "\n" . $content2;
        file_put_contents($outputPath, $combined);
        return file_exists($outputPath);
    }

    /**
     * Find PDF file by trying multiple paths
     */
    public static function resolvePdfPath(string $pdfPath): ?string
    {
        if (empty($pdfPath)) return null;

        $candidates = [
            $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . '/' . ltrim($pdfPath, '/'),
            rtrim($_SERVER['DOCUMENT_ROOT'], '/') . $pdfPath,
            $_SERVER['DOCUMENT_ROOT'] . '/gmind' . $pdfPath,
            '/home/advaysin/public_html' . $pdfPath,
            '/home/advaysin/public_html/gmind' . $pdfPath,
        ];

        if ($pdfPath[0] !== '/') {
            $candidates[] = $_SERVER['DOCUMENT_ROOT'] . '/' . $pdfPath;
            $candidates[] = '/home/advaysin/public_html/' . $pdfPath;
            $candidates[] = '/home/advaysin/public_html/gmind/' . $pdfPath;
        }

        foreach ($candidates as $c) {
            if (file_exists($c) && is_readable($c)) {
                return $c;
            }
        }

        return null;
    }
}
