generateUniquePdfFilename($pdfFileName); $pdfPath = str_replace(storage_path('documents/'), '', dirname($pdfFileName)) . '/'; Log::debug('PDF exists and override is false, using unique name', [ 'path' => $pdfFileName ]); } Log::debug('Converting Excel to PDF', [ 'excel' => $fullExcelPath, 'pdf_dir' => $fullPdfPath ]); try { // Use existing helper function $result = xlsx_to_pdf_legacy($fullExcelPath, $fullPdfPath); if (!$result) { throw new Exception("PDF conversion failed"); } // Fix file permissions if PDF was created if (file_exists($pdfFileName)) { try { // Change owner to www-data for web access chown($pdfFileName, 'www-data'); chgrp($pdfFileName, 'www-data'); chmod($pdfFileName, 0644); } catch (\Throwable $th) { Log::warning('Could not change PDF file permissions', [ 'file' => $pdfFileName, 'error' => $th->getMessage() ]); } } Log::debug('PDF conversion successful', [ 'pdf_file' => $pdfFileName, 'exists' => file_exists($pdfFileName) ]); return $pdfPath; } catch (\Throwable $th) { Log::error('PDF conversion error', [ 'error' => $th->getMessage(), 'excel' => $fullExcelPath, 'pdf_dir' => $fullPdfPath ]); throw $th; } } /** * Generate unique PDF filename if file exists */ private function generateUniquePdfFilename(string $filePath): string { $counter = 1; $pathInfo = pathinfo($filePath); do { $newFileName = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '_' . $counter . '.' . $pathInfo['extension']; $counter++; } while (file_exists($newFileName)); return $newFileName; } }