initialize($weldLogData, $document, $sheet, $currentRow, $settings); $project = $weldLogData['project'] ?? ''; if (empty($project)) return $currentRow; $workPermitDocs = db("work_permit_documents")->where("zone", "like", "%" . $project . "%")->get()->toArray(); $placeholderReplacer = new \App\Services\RegisterCreator\PlaceholderReplacer(); // Sort by issue_date (oldest first) - reverse insertion order usort($workPermitDocs, function($a, $b) use ($placeholderReplacer, $weldLogData) { $a = (object) $a; $b = (object) $b; $dateA = $a->issue_date ?? $a->created_at ?? $placeholderReplacer->getLatestDate($weldLogData, $this->registerColumnBased); $dateB = $b->issue_date ?? $b->created_at ?? $placeholderReplacer->getLatestDate($weldLogData, $this->registerColumnBased); $timestampA = !empty($dateA) ? strtotime($dateA) : 0; $timestampB = !empty($dateB) ? strtotime($dateB) : 0; return $timestampA <=> $timestampB; }); foreach ($workPermitDocs as $doc) { $doc = (object) $doc; $normalized = $this->normalizeSearchTerm($doc->document_number); $search = $this->searchFiles("storage/documents/{$document['path']}/*{$normalized}*.pdf"); $document['title2'] = $doc->document_number; $document['title3'] = $doc->title ?? $doc->document_number; $this->document = $document; $documentDate = $doc->issue_date ?? $doc->created_at ?? $placeholderReplacer->getLatestDate($weldLogData, $this->registerColumnBased); $newRow = $this->addRowToExcel($search, $doc->document_number, $documentDate); if ($newRow > $currentRow) { $currentRow = $newRow; } } return $currentRow; } }