<?php

namespace Modules\VetClinic\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\VetClinic\Entities\VcPet;

/**
 * Public verification of a vaccination certificate via the QR/token printed
 * on the certificate. Shows the issuing clinic, the pet's bio summary, and
 * the most recent vaccinations — enough to confirm authenticity, no more.
 */
class VcVaccinationVerifyController extends Controller
{
    public function show(Request $request, $token)
    {
        if (!is_string($token) || !preg_match('/^[a-f0-9]{16,64}$/i', $token)) {
            return $this->render(['ok' => false, 'reason' => 'bad_format']);
        }

        $pet = VcPet::with([
                'owner:id,name',
                'vaccinations' => fn($q) => $q->orderByDesc('administered_date')->limit(5),
                'vaccinations.vaccineType:id,name',
            ])
            ->where('cert_verify_token', strtolower($token))
            ->first();

        if (!$pet) {
            return $this->render(['ok' => false, 'reason' => 'not_found']);
        }

        $business = \App\Business::find($pet->business_id);

        return $this->render([
            'ok'       => true,
            'pet'      => $pet,
            'business' => $business,
        ]);
    }

    private function render(array $data)
    {
        return response()->view('vetClinic::pets.verify-vaccinations', $data);
    }
}
