<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use App\Modules\HR\Recruitment\Repositories\RecruitmentOfferLetterRepository;
use Dompdf\Dompdf;
use Dompdf\Options;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;

class RecruitmentOfferLetterPdfService
{
    public function __construct(
        private readonly RecruitmentOfferLetterRepository $repository,
    ) {}

    public function generateAndStore(RecruitmentOfferLetter $offer): RecruitmentOfferLetter
    {
        $offer->loadMissing([
            'candidate', 'vacancy', 'department', 'position', 'employmentStatus', 'application',
        ]);
        $html = View::make('pages.hr.recruitment.offer-letters.pdf', ['offer' => $offer])->render();
        $pdf = $this->renderPdf($html);
        $path = 'tenants/'.$offer->tenant_id.'/recruitment/offers/'.$offer->id.'/v'.$offer->version.'.pdf';
        Storage::disk('local')->put($path, $pdf);

        return $this->repository->update($offer, [
            'pdf_path' => $path,
            'template_key' => $offer->template_key ?: 'default_offer',
            'template_version' => $offer->template_version ?: '1',
        ]);
    }

    public function binary(RecruitmentOfferLetter $offer): string
    {
        if ($offer->pdf_path && Storage::disk('local')->exists($offer->pdf_path)) {
            return (string) Storage::disk('local')->get($offer->pdf_path);
        }
        $fresh = $this->generateAndStore($offer);

        return (string) Storage::disk('local')->get((string) $fresh->pdf_path);
    }

    private function renderPdf(string $html): string
    {
        $options = new Options;
        $options->set('isRemoteEnabled', false);
        $options->set('defaultFont', 'DejaVu Sans');
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4');
        $dompdf->render();

        return (string) $dompdf->output();
    }
}
