<?php

declare(strict_types=1);

namespace App\Services;

final class QrCodeService
{
    public function dataUri(string $url, int $size = 148): string
    {
        if (class_exists(\Endroid\QrCode\Builder\Builder::class)) {
            $result = \Endroid\QrCode\Builder\Builder::create()
                ->data($url)
                ->size($size)
                ->margin(8)
                ->build();

            return $result->getDataUri();
        }

        $hash = md5($url);
        $cells = '';
        for ($i = 0; $i < 49; $i++) {
            $hex = hexdec($hash[$i % strlen($hash)]);
            $x = ($i % 7) * 16;
            $y = intdiv($i, 7) * 16;
            if ($hex % 2 === 0 || in_array($i, [0, 1, 7, 8, 5, 6, 12, 13, 35, 36, 42, 43], true)) {
                $cells .= "<rect x=\"{$x}\" y=\"{$y}\" width=\"14\" height=\"14\" rx=\"2\"/>";
            }
        }

        $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 112 112" width="' . $size . '" height="' . $size . '"><rect width="112" height="112" fill="#fff"/><g fill="#111827">' . $cells . '</g></svg>';

        return 'data:image/svg+xml;base64,' . base64_encode($svg);
    }
}
