<?php

namespace App\Services\Reports;

use Illuminate\Support\Facades\URL;

class ReportQrCodeService
{
    public function verificationUrl(string $type, string $id): string
    {
        return URL::to('/reports/verify') . '?' . http_build_query([
            'type' => $type,
            'id' => $id,
            'signature' => $this->signature($type, $id),
        ]);
    }

    public function signature(string $type, string $id): string
    {
        return hash_hmac('sha256', $type . '|' . $id, config('app.key'));
    }

    public function isValidSignature(string $type, string $id, string $signature): bool
    {
        return hash_equals($this->signature($type, $id), $signature);
    }

    public function svg(string $value, int $size = 220): string
    {
        /*
         * Recommended production dependency:
         * composer require simplesoftwareio/simple-qrcode
         */
        if (class_exists(\SimpleSoftwareIO\QrCode\Facades\QrCode::class)) {
            try {
                return (string) \SimpleSoftwareIO\QrCode\Facades\QrCode::format('svg')
                    ->size($size)
                    ->margin(1)
                    ->errorCorrection('H')
                    ->generate($value);
            } catch (\Throwable $e) {
                report($e);
            }
        }

        $safeValue = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
        $size = max(120, min(400, $size));
        $innerSize = $size - 8;

        return <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" width="{$size}" height="{$size}" viewBox="0 0 {$size} {$size}">
  <rect width="100%" height="100%" fill="#ffffff"/>
  <rect x="4" y="4" width="{$innerSize}" height="{$innerSize}" fill="none" stroke="#0b1f3a" stroke-width="4"/>
  <text x="50%" y="42%" text-anchor="middle" font-family="Arial, sans-serif" font-size="18" font-weight="700" fill="#0b1f3a">QR</text>
  <text x="50%" y="56%" text-anchor="middle" font-family="Arial, sans-serif" font-size="9" fill="#0b1f3a">Install QR package</text>
  <title>{$safeValue}</title>
</svg>
SVG;
    }

    public function dataUri(string $value, int $size = 220): string
    {
        return 'data:image/svg+xml;base64,' . base64_encode($this->svg($value, $size));
    }
}
