<?php

namespace App\Http\Controllers;

use App\Models\Certificate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CertificateController extends Controller
{
    /**
     * Download the specified certificate PDF.
     */
    public function download(Certificate $certificate)
    {
        // Ensure user is authorized to download this certificate
        if ($certificate->user_id !== auth()->id()) {
            abort(403, 'Unauthorized action.');
        }

        $path = 'certificates/' . $certificate->certificate_code . '.pdf';

        // Check if file exists, if not generate it as a fallback
        if (!Storage::disk('local')->exists($path)) {
            $path = \App\Services\CertificateService::generate($certificate);
        }

        return response()->download(Storage::disk('local')->path($path), 'Certificate_' . $certificate->certificate_code . '.pdf');
    }
}
