<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\DTOs\RecruitmentReportFilters;
use Dompdf\Dompdf;
use Dompdf\Options;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class RecruitmentReportPdfExportService
{
    public function __construct(
        private readonly RecruitmentReportRegistry $registry,
    ) {}

    public function download(string $type, int $tenantId, RecruitmentReportFilters $filters): Response
    {
        $report = $this->registry->build($type, $tenantId, $filters);
        $html = View::make('pages.hr.recruitment.reports.pdf', [
            'type' => $type,
            'report' => $report,
            'filters' => $filters,
            'generatedAt' => now(),
        ])->render();

        $options = new Options;
        $options->set('isRemoteEnabled', false);
        $options->set('defaultFont', 'DejaVu Sans');
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'landscape');
        $dompdf->render();

        $filename = 'recruitment_'.$type.'_'.now()->format('Ymd_His').'.pdf';

        return response($dompdf->output(), 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => 'attachment; filename="'.$filename.'"',
        ]);
    }
}
