<?php

namespace App\Http\Controllers;

use App\Models\Pet;
use App\Models\Setting;
use BaconQrCode\Renderer\Color\Rgb;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\Fill;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PetPrintController extends Controller
{
    /**
     * Render a print-friendly one-page bio for a pet.
     */
    public function __invoke(Request $request, Pet $pet): View
    {
        abort_unless($request->user()?->is_admin, 403);

        $isPubliclyVisible = $pet->isPubliclyVisible();
        $showQrCode = Setting::get('show_print_bio_qr_code', false);

        return view('pets.print', [
            'pet' => $pet->load(['species', 'breed']),
            'siteUrl' => $isPubliclyVisible ? config('app.url') : null,
            'qrCodeSvg' => $showQrCode && $isPubliclyVisible ? $this->qrCodeSvg(route('pets.show', $pet->slug)) : null,
            'showQrCode' => $showQrCode,
        ]);
    }

    /**
     * Render a QR code as an inline SVG string for the given URL.
     */
    private function qrCodeSvg(string $url): string
    {
        $svg = (new Writer(
            new ImageRenderer(
                new RendererStyle(120, 0, null, null, Fill::uniformColor(new Rgb(255, 255, 255), new Rgb(15, 23, 42))),
                new SvgImageBackEnd
            )
        ))->writeString($url);

        return trim(preg_replace('/^<\?xml.*?\?>/s', '', $svg));
    }
}
