<?php

namespace Modules\ClinicCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\ClinicCore\Entities\ClcConsent;
use Modules\ClinicCore\Entities\ClcConsentSignature;

/**
 * Public verification of a digitally-signed consent. Anyone with the QR / URL
 * printed on a paper copy can confirm the signature exists, when it was
 * captured, and a non-PII summary of who/what was signed. The full consent
 * body is intentionally NOT shown — this is just an authenticity check.
 */
class ClcConsentVerifyController extends Controller
{
    public function show(Request $request, $hash)
    {
        // Accept anywhere from 12 (short prefix on the printout) up to 64 (full hash).
        if (!preg_match('/^[a-f0-9]{12,64}$/i', $hash)) {
            return $this->render(['ok' => false, 'reason' => 'bad_format']);
        }

        $hash = strtolower($hash);

        $sig = ClcConsentSignature::query()
            ->where('png_hash_sha256', 'like', $hash . '%')
            ->orderBy('signed_at')
            ->first();

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

        $consent = ClcConsent::with(['pet:id,patient_name,species,breed', 'owner:id,name'])
            ->find($sig->consent_id);

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

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

        return $this->render([
            'ok'           => true,
            'sig'          => $sig,
            'consent'      => $consent,
            'business'     => $business,
            'is_active'    => empty($sig->superseded_at),
            'is_archived'  => !empty($consent->archived_at),
        ]);
    }

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