<?php
namespace App\Services;

use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\View;

class VisitReportService
{
    /**
     * Generate a PDF report for the visit and store it under public storage.
     * Returns the relative storage path (e.g., visits/reports/visit_12_...pdf)
     */
    public function generateAndStore(\App\Models\Visit $visit): ?string
    {
        try {
            $data = [
                'visit' => $visit->load(['client','technician','photos','logs','spareparts']),
            ];

            $html = View::make('admin.visits.report', $data)->render();
            $pdf = Pdf::loadHTML($html)->setPaper('a4', 'portrait');

            $dir = storage_path('app/public/visits/reports');
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $filename = 'visit_'.$visit->id.'_report_'.time().'.pdf';
            $full = $dir.DIRECTORY_SEPARATOR.$filename;
            $pdf->save($full);

            return 'visits/reports/'.$filename;
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('VisitReportService error: '.$e->getMessage());
            return null;
        }
    }
}
