<?php

namespace App\Services;

use App\Models\Program;
use App\Models\ProgramQrCode;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QrCodeService
{
    public function generateForProgram(Program $program): ProgramQrCode
    {
        $program->qrCodes()->where('is_active', true)->update(['is_active' => false]);

        $token = Str::random(48);
        $url   = route('public.checkin.show', $token);
        $path  = 'qrcodes/' . $token . '.png';

        Storage::disk('public')->makeDirectory('qrcodes');

        $png = QrCode::format('png')
                     ->size(400)
                     ->margin(2)
                     ->errorCorrection('H')
                     ->generate($url);

        Storage::disk('public')->put($path, $png);

        return $program->qrCodes()->create([
            'token'         => $token,
            'qr_image_path' => $path,
            'is_active'     => true,
        ]);
    }

    public function getPublicUrl(ProgramQrCode $qrCode): string
    {
        return Storage::disk('public')->url($qrCode->qr_image_path);
    }

    public function getRawPng(ProgramQrCode $qrCode): string
    {
        return Storage::disk('public')->get($qrCode->qr_image_path);
    }
}
