<?php

namespace App\Services;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use ReflectionClass;
use Webklex\PDFMerger\Facades\PDFMergerFacade as PDFMerger;

class PdfMergerService
{
    /**
     * Merge multiple PDF files into a single PDF
     *
     * @param  array  $pdfFiles Array of PDF files with 'name' and 'media' keys
     * @param  string  $filename Output filename
     * @return string The path to the merged PDF file
     *
     * @throws \Exception
     */
    public static function mergePdfs(array $pdfFiles, string $filename): string
    {
        try {
            $oMerger = PDFMerger::init();

            // Get the reflection class and property
            $reflection = new ReflectionClass($oMerger);
            $property = $reflection->getProperty('aFiles');
            $property->setAccessible(true);

            // Get current files array (or initialize as empty collection)
            $currentFiles = $property->getValue($oMerger) ?? collect();

            // Ensure it's a collection
            if (! ($currentFiles instanceof \Illuminate\Support\Collection)) {
                $currentFiles = collect($currentFiles);
            }

            // Add each PDF file to the collection
            foreach ($pdfFiles as $pdfFile) {
                $media = $pdfFile['media'];
                $mediaTempUrl = $media->getTemporaryUrl(Carbon::now()->addMinutes(5));

                $currentFiles->push([
                    'name' => $mediaTempUrl,
                    'pages' => 'all',
                    'orientation' => null,
                ]);
            }

            // Remove duplicates and set the property back
            $uniqueFiles = $currentFiles->unique('name')->values();
            $property->setValue($oMerger, $uniqueFiles);

            $oMerger->merge();
            $oMerger->save($filename);

            return $filename;
        } catch (\Exception $e) {
            Log::error('PDF merge failed', [
                'error' => $e->getMessage(),
                'filename' => $filename,
                'file_count' => count($pdfFiles),
            ]);

            throw $e;
        }
    }
}
