<?php

namespace App\Services;

use App\Models\Certificate;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class CertificatePdfService
{
    /**
     * Generate and save PDF certificate to disk.
     *
     * @return string Relative storage path of generated PDF
     */
    public function generateAndSave(Certificate $certificate): string
    {
        $certificate->load(['student.college', 'template', 'course', 'issuer']);

        // 1. Generate QR Code as Base64 PNG/SVG data string
        $verificationUrl = route('public.verify', $certificate->certificate_uuid);
        $qrCodeSvg = QrCode::size(140)
            ->margin(1)
            ->color(16, 85, 47) // Deep Emerald green accent
            ->generate($verificationUrl);

        $qrCodeBase64 = 'data:image/svg+xml;base64,'.base64_encode($qrCodeSvg);

        // 2. Render View template to PDF (A4 Landscape)
        $viewName = $certificate->template->view_name ?? 'pdf.templates.internship';
        if (! view()->exists($viewName)) {
            $viewName = 'pdf.templates.internship';
        }

        $pdf = Pdf::loadView($viewName, [
            'certificate' => $certificate,
            'student' => $certificate->student,
            'college' => $certificate->student->college,
            'course' => $certificate->course,
            'qrCode' => $qrCodeBase64,
            'verificationUrl' => $verificationUrl,
        ])->setPaper('a4', 'landscape');

        // 3. Store PDF file in storage/app/public/certificates/{year}/{uuid}.pdf
        $year = date('Y', strtotime($certificate->issue_date ?? now()));
        $relativePath = "certificates/{$year}/{$certificate->certificate_uuid}.pdf";

        Storage::disk('public')->put($relativePath, $pdf->output());

        // 4. Update model
        $certificate->update(['pdf_path' => $relativePath]);

        return $relativePath;
    }

    /**
     * Output direct stream or download response.
     */
    public function downloadPdfResponse(Certificate $certificate)
    {
        if (! $certificate->pdf_path || ! Storage::disk('public')->exists($certificate->pdf_path)) {
            $this->generateAndSave($certificate);
        }

        return Storage::disk('public')->download(
            $certificate->pdf_path,
            "Certificate-{$certificate->student->full_name}-{$certificate->certificate_uuid}.pdf"
        );
    }
}
