<?php

namespace App\Filament\Resources\ExchangeRequestResource\Pages;

use App\Filament\Resources\ExchangeRequestResource;
use App\Filament\Resources\ExchangeRequestResource\Components\ExchangeRequestApprovalFlow;
use App\Filament\Resources\ServiceProviderResource;
use App\Models\ExchangeRequest;
use Carbon\Carbon;
use Filament\Actions;
use Filament\Infolists\Components\Grid;
use Filament\Infolists\Components\Section;
use Filament\Infolists\Components\Split;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Infolists\Infolist;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Support\Enums\FontWeight;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\HtmlString;
use RalphJSmit\Filament\Activitylog\Actions\TimelineAction;
use RalphJSmit\Filament\Activitylog\Infolists\Components\Timeline;
use ReflectionClass;
use Spatie\Activitylog\Models\Activity;
use Webklex\PDFMerger\Facades\PDFMergerFacade as PDFMerger;

class ViewExchangeRequest extends ViewRecord
{
    protected static string $resource = ExchangeRequestResource::class;

    protected function getHeaderActions(): array
    {
        $actions = [];
        $record = $this->getRecord();

        if ($record->status !== ExchangeRequest::STATUS_REJECTED && $record->status !== ExchangeRequest::STATUS_APPROVED) {
            $actions[] = Actions\EditAction::make();
        }

        // Add approval actions if user has permission
        if ($record->canApproveToNextStage()) {
            array_push($actions, ...ExchangeRequestApprovalFlow::getApprovalFlowActions($record));
        }

        // Add PDF export action
        $actions[] = Actions\Action::make('export_pdfs')
            ->label(__('exchange_request.export_pdfs'))
            ->icon('heroicon-o-document-arrow-down')
            ->color('info')
            ->action(function () {
                return $this->exportPdfs();
            });

        $actions[] = TimelineAction::make()
            ->label(__('order.timeline'))
            ->modifyTimelineUsing(function (Timeline $timeline) {
                return $timeline
                    ->modifyActivitiesQueryUsing(function (Builder $query) {
                        return $query->whereIn('event', ['approved', 'rejected', 'send_back']);
                    })
                    ->itemIcon('approved', 'heroicon-o-check-circle')
                    ->itemIconColor('approved', 'success')
                    ->itemIcon('rejected', 'heroicon-o-x-circle')
                    ->itemIconColor('rejected', 'danger')
                    ->itemIcon('send_back', 'heroicon-o-arrow-uturn-left')
                    ->itemIconColor('send_back', 'warning')
                    ->eventDescriptions([
                        'approved' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $newStatus = $activity->getExtraProperty('new_status');
                            $oldStatusName = ExchangeRequest::getStatuses()[$oldStatus] ?? $oldStatus;
                            $newStatusName = ExchangeRequest::getStatuses()[$newStatus] ?? $newStatus;

                            $description = __('order.order_approved_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus && $newStatus) {
                                $description .= '<br/>'.__('order.status_changed', ['old_status' => $oldStatusName, 'new_status' => $newStatusName]);
                            }

                            return new HtmlString($description);
                        },
                        'rejected' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $oldStatusName = ExchangeRequest::getStatuses()[$oldStatus] ?? $oldStatus;
                            $description = __('order.order_rejected_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus) {
                                $description .= ' '.__('order.status_was', ['status' => $oldStatusName]);
                            }

                            return new HtmlString($description);
                        },
                        'send_back' => function (Activity $activity) {
                            $oldStatus = $activity->getExtraProperty('old_status');
                            $newStatus = $activity->getExtraProperty('new_status');
                            $oldStatusName = ExchangeRequest::getStatuses()[$oldStatus] ?? $oldStatus;
                            $newStatusName = ExchangeRequest::getStatuses()[$newStatus] ?? $newStatus;

                            $description = __('order.order_sent_back_by', ['name' => $activity->causer?->name]);
                            if ($oldStatus && $newStatus) {
                                $description .= '<br/>'.__('order.status_changed', ['old_status' => $oldStatusName, 'new_status' => $newStatusName]);
                            }

                            return new HtmlString($description);
                        },
                    ])
                    ->itemBadge(
                        'approved',
                        fn (Activity $activity) => $activity->getExtraProperty('notes')
                            ? __('order.notes', ['notes' => $activity->getExtraProperty('notes')])
                            : __('order.notes_na'),
                        [ExchangeRequest::class]
                    )
                    ->itemBadgeColor('approved', 'success')
                    ->itemBadge(
                        'rejected',
                        fn (Activity $activity) => $activity->getExtraProperty('notes')
                            ? __('order.notes', ['notes' => $activity->getExtraProperty('notes')])
                            : __('order.notes_na'),
                        [ExchangeRequest::class]
                    )
                    ->itemBadgeColor('rejected', 'danger')
                    ->itemBadge(
                        'send_back',
                        fn (Activity $activity) => $activity->getExtraProperty('notes')
                            ? __('order.notes', ['notes' => $activity->getExtraProperty('notes')])
                            : __('order.notes_na'),
                        [ExchangeRequest::class]
                    )
                    ->itemBadgeColor('send_back', 'warning')
                    ->emptyStateHeading(__('order.no_timeline_activities'))
                    ->emptyStateDescription(__('order.no_timeline_activities_description'));
            });

        return $actions;
    }

    public function infolist(Infolist $infolist): Infolist
    {
        return $infolist
            ->schema([
                Grid::make(1)
                    ->schema([
                        // Exchange Request Status Bar
                        $this->getExchangeRequestStatusesBar(),
                        // Exchange Request Info Split
                        $this->getExchangeRequestInfoSplit(),
                    ]),
            ]);
    }

    public function getExchangeRequestStatusesBar(): ViewEntry
    {
        return ViewEntry::make('exchange_request_status_bar')
            ->view('filament.components.exchange-request-status-bar')
            ->columnSpanFull();
    }

    public function getExchangeRequestInfoSplit(): Split
    {
        return Split::make([
            // First Column
            Grid::make(1)
                ->schema([
                    // Exchange Request Details Card
                    Section::make(__('exchange_request.exchange_request_details'))
                        ->icon('heroicon-o-currency-dollar')
                        ->schema([

                            // Exchange Request ID
                            TextEntry::make('id')
                                ->label(__('exchange_request.number'))
                                ->weight(weight: FontWeight::SemiBold)
                                ->prefix('#'),

                            TextEntry::make('status')
                                ->label('')
                                ->formatStateUsing(
                                    fn (string $state): string => __(ExchangeRequest::getStatuses()[$state] ?? $state)
                                )
                                ->badge()
                                ->color(fn (string $state): string => match ($state) {
                                    ExchangeRequest::STATUS_CREATED => 'gray',
                                    ExchangeRequest::STATUS_FINANCIAL_APPROVED => 'warning',
                                    ExchangeRequest::STATUS_SHARED_SERVICES_APPROVED => 'info',
                                    ExchangeRequest::STATUS_CEO_APPROVED => 'primary',
                                    ExchangeRequest::STATUS_TRANSACTION_APPROVED => 'violet',
                                    ExchangeRequest::STATUS_APPROVED => 'success',
                                    ExchangeRequest::STATUS_REJECTED => 'danger',
                                    default => 'gray',
                                }),

                            TextEntry::make('completionReport.description')
                                ->label(__('completion_report.description'))
                                ->weight(FontWeight::SemiBold),

                            TextEntry::make('completionReport.value')
                                ->label(__('completion_report.value'))
                                ->formatStateUsing(function ($state) {
                                    return number_format((float) $state, 2);
                                })
                                ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                ->weight(FontWeight::SemiBold)
                                ->color('success'),

                            TextEntry::make('completionReport.delivery_date')
                                ->label(__('completion_report.delivery_date'))
                                ->date(),

                            TextEntry::make('transaction_date')
                                ->label(__('exchange_request.transaction_date'))
                                ->date()
                                ->placeholder(__('common.not_set'))
                                ->visible(fn (ExchangeRequest $record): bool => $record->transaction_date !== null),

                            TextEntry::make('completionReport.status')
                                ->label(__('exchange_request.completion_report_status'))
                                ->formatStateUsing(
                                    fn (string $state): string => match ($state) {
                                        'approved' => __('completion_report.status_approved'),
                                        'pending' => __('completion_report.status_pending'),
                                        'rejected' => __('completion_report.status_rejected'),
                                        default => ucfirst($state)
                                    }
                                )
                                ->badge()
                                ->color(fn (string $state): string => match ($state) {
                                    'approved' => 'success',
                                    'pending' => 'warning',
                                    'rejected' => 'danger',
                                    default => 'gray',
                                }),

                            TextEntry::make('created_at')
                                ->label(__('common.created_at'))
                                ->date(),

                            TextEntry::make('updated_at')
                                ->label(__('common.updated_at'))
                                ->date(),

                            TextEntry::make('createdBy.name')
                                ->label(__('common.created_by'))
                                ->formatStateUsing(function ($record) {
                                    $user = $record->createdBy;
                                    if (! $user) {
                                        return __('common.unknown');
                                    }

                                    if ($user->job_title) {
                                        return new HtmlString($user->name.'<br><span class="text-sm text-gray-500">'.$user->job_title.'</span>');
                                    }

                                    return $user->name;
                                })
                                ->html()
                                ->placeholder(__('common.unknown')),
                        ])
                        ->columns(2),

                    // Transaction File Section
                    Section::make(__('exchange_request.transaction_file'))
                        ->icon('heroicon-o-document')
                        ->schema([
                            TextEntry::make('transaction_file_url')
                                ->label('')
                                ->formatStateUsing(function ($state) {
                                    if ($state) {
                                        return '<a href="'.$state.'" target="_blank" class="text-blue-600 hover:text-blue-800 underline">'.__('common.download').'</a>';
                                    }

                                    return __('exchange_request.no_transaction_file');
                                })
                                ->html()
                                ->placeholder(__('exchange_request.no_transaction_file')),
                        ])
                        ->collapsible(),

                    // Additional Files Section
                    Section::make(__('exchange_request.additional_files'))
                        ->icon('heroicon-o-document-duplicate')
                        ->schema([
                            TextEntry::make('completionReport.er_files')
                                ->label('')
                                ->state(function ($record) {
                                    $files = $record->completionReport->getErFiles();

                                    if ($files->isEmpty()) {
                                        return __('exchange_request.no_additional_files');
                                    }

                                    $links = [];
                                    foreach ($files as $index => $file) {
                                        $url = $file->getTemporaryUrl(Carbon::now()->addMinutes(5));
                                        $fileName = $file->name ?: __('exchange_request.file').' '.($index + 1);
                                        $links[] = '<a href="'.$url.'" target="_blank" class="text-blue-600 hover:text-blue-800 underline block mb-1">'.$fileName.'</a>';
                                    }

                                    return implode('', $links);
                                })
                                ->html()
                                ->placeholder(__('exchange_request.no_additional_files')),
                        ])
                        ->collapsible()
                        ->visible(fn ($record) => $record->completionReport?->hasErFiles()),

                    // Order and Association Information (if project charter has order)
                    Section::make(__('exchange_request.related_order_association'))
                        ->icon('heroicon-o-building-office-2')
                        ->schema([
                            // Order Information
                            TextEntry::make('order.id')
                                ->label(__('order.order_number'))
                                ->formatStateUsing(function ($state, $record) {
                                    if (! $state) {
                                        return null;
                                    }

                                    return '#'.$state;
                                })
                                ->url(function ($record) {
                                    $order = $record->completionReport?->projectCharterDeliverable?->projectCharter?->order;

                                    return $order ? \App\Filament\Resources\OrderResource::getUrl('view', ['record' => $order]) : null;
                                })
                                ->color('primary')
                                ->weight(FontWeight::SemiBold),

                            // Association Information
                            TextEntry::make('association.name')
                                ->label(__('association.association'))
                                ->url(function ($record) {
                                    $association = $record->completionReport?->projectCharterDeliverable?->projectCharter?->order?->association;

                                    return $association ? \App\Filament\Resources\AssociationResource::getUrl('view', ['record' => $association]) : null;
                                })
                                ->color('primary')
                                ->weight(FontWeight::SemiBold),

                            // Association Documents
                            TextEntry::make('association_authorization_letter')
                                ->label(__('association.authorization_letter'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->association?->getFirstMedia('authorization_letter')?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" target="_blank">'.
                                    __('common.download').'</a>')),

                            TextEntry::make('association_iban_certificate')
                                ->label(__('association.iban_certificate'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->association?->getFirstMedia('iban_certificate')?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" target="_blank">'.
                                    __('common.download').'</a>')),

                            TextEntry::make('association_license_certificate')
                                ->label(__('association.license_certificate'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->association?->getFirstMedia('license_certificate')?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" target="_blank">'.
                                    __('common.download').'</a>')),

                            // Order Agreement File
                            TextEntry::make('order_agreement.agreement_file')
                                ->label(__('order_agreement.agreement_file'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->order?->getAgreementFile()?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" target="_blank">'.
                                    __('common.download').'</a>')),

                            TextEntry::make('order.donorFinancialPortfolios')
                                ->label(__('order.portfolio_allocations'))
                                ->listWithLineBreaks()
                                ->bulleted()
                                ->formatStateUsing(function ($state): string {
                                    Log::info($state);

                                    return $state->name.' - '.number_format($state->pivot->allocated_amount, 2).new HtmlString('<span class="icon-saudi_riyal"></span>');
                                })
                                ->html()
                                ->columnSpanFull(),

                        ])
                        ->columns(2)
                        ->visible(function ($record) {
                            return $record->completionReport?->projectCharterDeliverable?->projectCharter?->order !== null;
                        })
                        ->collapsible(),

                    // service provider information (if project charter has one)
                    Section::make(__('service_provider.service_provider'))
                        ->icon('heroicon-o-user')
                        ->schema([
                            TextEntry::make('projectCharter.serviceProvider.name')
                                ->label(__('service_provider.service_provider'))
                                ->icon('heroicon-o-user')
                                ->color('primary')
                                ->placeholder('-'),
                            // ->url(fn($record) => $record->projectCharter?->serviceProvider ? ServiceProviderResource::getUrl('view', ['record' => $record->projectCharter->serviceProvider]) : null),

                            // contract file
                            TextEntry::make('projectCharter.serviceProvider.contract')
                                ->label(__('service_provider.contract'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->projectCharter?->serviceProvider?->getContractTemporaryUrl().'" target="_blank">'.
                                    __('common.download').'</a>')),

                            // commercial_registration file
                            TextEntry::make('projectCharter.serviceProvider.commercial_registration')
                                ->label(__('service_provider.commercial_registration'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->projectCharter?->serviceProvider?->getCommercialRegistrationTemporaryUrl().'" target="_blank">'.
                                    __('common.download').'</a>')),

                            // iban_certificate file
                            TextEntry::make('projectCharter.serviceProvider.iban_certificate')
                                ->label(__('service_provider.iban_certificate'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->projectCharter?->serviceProvider?->getIbanCertificateTemporaryUrl().'" target="_blank">'.
                                    __('common.download').'</a>')),

                        ])
                        ->columns(2)
                        ->visible(function ($record) {
                            return $record->projectCharter?->serviceProvider !== null;
                        })
                        ->collapsible(),
                ])
                ->grow(),

            // Second Column
            Grid::make(1)
                ->schema([
                    // Project Charter Information
                    Section::make(__('exchange_request.project_charter_details'))
                        ->icon('heroicon-o-document-chart-bar')
                        ->schema([
                            TextEntry::make('projectCharter.id')
                                ->label(__('project_charter.charter_number'))
                                ->formatStateUsing(function ($state, $record) {
                                    if (! $state) {
                                        return null;
                                    }

                                    $projectManner = $record->projectCharter?->project_manner;
                                    if ($projectManner) {
                                        return strtoupper(mb_substr((string) $projectManner, 0, 1)).'-'.$state;
                                    }

                                    return '#'.$state;
                                })
                                ->url(function ($record) {
                                    $charter = $record->completionReport?->projectCharterDeliverable?->projectCharter;

                                    return $charter ? \App\Filament\Resources\ProjectCharterResource::getUrl('view', ['record' => $charter]) : null;
                                })
                                ->color('primary')
                                ->weight(FontWeight::SemiBold),

                            TextEntry::make('projectCharter.name')
                                ->label(__('project_charter.name'))
                                ->weight(FontWeight::SemiBold)
                                ->limit(50),

                            TextEntry::make('projectCharter.estimated_cost')
                                ->label(__('project_charter.estimated_cost'))
                                ->formatStateUsing(function ($state) {
                                    return $state ? number_format((float) $state, 2) : __('common.not_set');
                                })
                                ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                ->weight(FontWeight::SemiBold)
                                ->color('info'),

                            TextEntry::make('projectCharter.remaining_cost')
                                ->label(__('exchange_request.project_charter_remaining_cost'))
                                ->formatStateUsing(function ($state) {
                                    return $state !== null ? number_format((float) $state, 2) : __('common.not_set');
                                })
                                ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                                ->weight(FontWeight::SemiBold)
                                ->color(function ($state) {
                                    if ($state === null) {
                                        return 'gray';
                                    }

                                    return $state >= 0 ? 'success' : 'danger';
                                }),
                        ])
                        ->columns(2)
                        ->collapsible(),

                    // Project Charter Deliverable Info and Files
                    Section::make(__('exchange_request.related_deliverable'))
                        ->icon('heroicon-o-document-text')
                        ->schema([
                            TextEntry::make('projectCharterDeliverable.name')
                                ->label(__('project_charter_deliverable.name'))
                                ->weight(FontWeight::SemiBold),

                            TextEntry::make('projectCharterDeliverable.description')
                                ->label(__('project_charter_deliverable.description'))
                                ->html()
                                ->limit(200),

                            TextEntry::make('projectCharterDeliverable.expected_delivery_date')
                                ->label(__('project_charter_deliverable.expected_delivery_date'))
                                ->date(),

                            // Deliverable File
                            TextEntry::make('deliverable_file')
                                ->label(__('project_charter_deliverable.file'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->projectCharterDeliverable?->getFirstMedia('deliverable_files')?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" target="_blank">'.
                                    __('common.download').'</a>')),
                        ])
                        ->columns(2)
                        ->collapsible(),

                    // Completion Report File
                    Section::make(__('exchange_request.completion_report_file'))
                        ->icon('heroicon-o-document-check')
                        ->schema([
                            TextEntry::make('completion_report_file')
                                ->label(__('completion_report.pdf_file'))
                                ->icon('heroicon-o-paper-clip')
                                ->color('primary')
                                ->state(fn (ExchangeRequest $record): HtmlString => new HtmlString('<a class="text-blue-500 hover:underline" href="'.$record->completionReport?->getFirstMedia('pdf_file')?->getTemporaryUrl(Carbon::now()->addMinutes(5)).'" target="_blank">'.
                                    __('common.download').'</a>'))
                                ->columnSpanFull(),

                            TextEntry::make('completionReport.creator.name')
                                ->label(__('common.created_by'))
                                ->formatStateUsing(function ($record) {
                                    $user = $record->completionReport?->creator;
                                    if (! $user) {
                                        return __('common.unknown');
                                    }

                                    if ($user->job_title) {
                                        return new HtmlString($user->name.'<br><span class="text-sm text-gray-500">'.$user->job_title.'</span>');
                                    }

                                    return $user->name;
                                })
                                ->html()
                                ->placeholder(__('common.unknown')),

                            TextEntry::make('completionReport.created_at')
                                ->label(__('completion_report.created_at'))
                                ->date(),

                            TextEntry::make('completionReport.approved_by.name')
                                ->label(__('completion_report.approved_by'))
                                ->formatStateUsing(function ($record) {
                                    $user = $record->completionReport?->approved_by;
                                    if (! $user) {
                                        return __('completion_report.not_approved');
                                    }

                                    if ($user->job_title) {
                                        return new HtmlString($user->name.'<br><span class="text-sm text-gray-500">'.$user->job_title.'</span>');
                                    }

                                    return $user->name;
                                })
                                ->html()
                                ->placeholder(__('completion_report.not_approved'))
                                ->visible(fn (ExchangeRequest $record): bool => $record->completionReport?->status === 'approved'),

                            TextEntry::make('completionReport.approved_at')
                                ->label(__('completion_report.approved_at'))
                                ->date()
                                ->visible(fn (ExchangeRequest $record): bool => $record->completionReport?->status === 'approved'),

                            TextEntry::make('completionReport.cr_files')
                                ->label(__('exchange_request.additional_files'))
                                ->state(function ($record) {
                                    $files = $record->completionReport->getCrFiles();

                                    if ($files->isEmpty()) {
                                        return __('exchange_request.no_additional_files');
                                    }

                                    $links = [];
                                    foreach ($files as $index => $file) {
                                        $url = $file->getTemporaryUrl(Carbon::now()->addMinutes(5));
                                        $fileName = $file->name ?: __('exchange_request.file').' '.($index + 1);
                                        $links[] = '<a href="'.$url.'" target="_blank" class="text-blue-600 hover:text-blue-800 underline block mb-1">'.$fileName.'</a>';
                                    }

                                    return implode('', $links);
                                })
                                ->html()
                                ->placeholder(__('exchange_request.no_additional_files'))
                                ->columnSpanFull(),
                        ])
                        ->columns(2)
                        ->collapsible()
                        ->collapsed(function ($record) {
                            return $record->completionReport?->getFirstMedia('pdf_file') === null;
                        }),
                ]),
        ]);
    }

    /**
     * Export all PDF files on the page as a merged PDF
     */
    public function exportPdfs()
    {
        $record = $this->getRecord();
        $pdfFiles = $this->collectPdfFiles($record);

        if (empty($pdfFiles)) {
            Notification::make()
                ->title(__('exchange_request.no_pdfs_found'))
                ->body(__('exchange_request.no_pdfs_to_export'))
                ->warning()
                ->send();

            return;
        }

        try {
            $mergedPdfPath = $this->mergePdfs($pdfFiles, $record);

            return response()->download($mergedPdfPath, "exchange_request_{$record->id}_documents.pdf")->deleteFileAfterSend(true);
        } catch (\Exception $e) {
            Notification::make()
                ->title(__('exchange_request.export_failed'))
                ->body(__('exchange_request.export_error_message'))
                ->danger()
                ->send();

            Log::error('PDF export failed', ['error' => $e->getMessage(), 'record_id' => $record->id]);

            return;
        }
    }

    /**
     * Collect all PDF files from the exchange request record
     */
    private function collectPdfFiles(ExchangeRequest $record): array
    {
        $pdfFiles = [];

        // Transaction file (if it's a PDF)
        $transactionFile = $record->getTransactionFile();
        if ($transactionFile && $transactionFile->mime_type === 'application/pdf') {
            $pdfFiles[] = [
                'name' => 'Transaction File',
                'media' => $transactionFile,
            ];
        }

        // Additional files (if they are PDFs)
        $additionalFiles = $record->completionReport?->getErFiles() ?? [];
        foreach ($additionalFiles as $index => $file) {
            if ($file->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'Additional File '.($index + 1),
                    'media' => $file,
                ];
            }
        }

        // Deliverable files (always PDF)
        $deliverableFile = $record->projectCharterDeliverable?->getFirstMedia('deliverable_files');
        if ($deliverableFile) {
            $pdfFiles[] = [
                'name' => 'Deliverable File',
                'media' => $deliverableFile,
            ];
        }

        // Completion report PDF file (always PDF)
        $completionReportFile = $record->completionReport?->getFirstMedia('pdf_file');
        if ($completionReportFile) {
            $pdfFiles[] = [
                'name' => 'Completion Report',
                'media' => $completionReportFile,
            ];
        }

        // Association documents (check if PDF)
        $association = $record->association;
        if ($association) {
            $authLetter = $association->getFirstMedia('authorization_letter');
            if ($authLetter && $authLetter->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'Authorization Letter',
                    'media' => $authLetter,
                ];
            }

            $ibanCert = $association->getFirstMedia('iban_certificate');
            if ($ibanCert && $ibanCert->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'IBAN Certificate',
                    'media' => $ibanCert,
                ];
            }

            $licenseCert = $association->getFirstMedia('license_certificate');
            if ($licenseCert && $licenseCert->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'License Certificate',
                    'media' => $licenseCert,
                ];
            }
        }

        // Service provider files (check if PDF)
        $serviceProvider = $record->projectCharter?->serviceProvider;
        if ($serviceProvider) {
            $contract = $serviceProvider->getFirstMedia('contract');
            if ($contract && $contract->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'Service Provider Contract',
                    'media' => $contract,
                ];
            }

            $commercialReg = $serviceProvider->getFirstMedia('commercial_registration');
            if ($commercialReg && $commercialReg->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'Commercial Registration',
                    'media' => $commercialReg,
                ];
            }

            $spIbanCert = $serviceProvider->getFirstMedia('iban_certificate');
            if ($spIbanCert && $spIbanCert->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'Service Provider IBAN Certificate',
                    'media' => $spIbanCert,
                ];
            }
        }

        // Order agreement file (check if PDF)
        $order = $record->order;
        if ($order) {
            $agreementFile = $order->getAgreementFile();
            if ($agreementFile && $agreementFile->mime_type === 'application/pdf') {
                $pdfFiles[] = [
                    'name' => 'Order Agreement',
                    'media' => $agreementFile,
                ];
            }
        }

        return $pdfFiles;
    }

    /**
     * Merge multiple PDF files into a single PDF
     */
    private function mergePdfs(array $pdfFiles, ExchangeRequest $record)
    {
        $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("exchange_request_{$record->id}_documents.pdf");

        return "exchange_request_{$record->id}_documents.pdf";
    }
}
