<?php

namespace App\Domains\QrCode\Services;

use chillerlan\QRCode\Output\QRGdImagePNG;
use chillerlan\QRCode\Output\QRMarkupSVG;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;

class QrRenderer
{
    /** @param array<string, mixed> $style */
    public function toSvg(string $data, array $style): string
    {
        $options = new QROptions([
            'outputInterface' => QRMarkupSVG::class,
            'outputBase64' => false,
        ]);

        return (new QRCode($options))->render($data);
    }

    /** @param array<string, mixed> $style */
    public function toPngBase64(string $data, array $style): string
    {
        $options = new QROptions([
            'outputInterface' => QRGdImagePNG::class,
            'outputBase64' => true,
            'scale' => 10,
        ]);

        return (new QRCode($options))->render($data);
    }

    /** @param array<string, string> $data */
    public function buildPayload(string $type, array $data): string
    {
        return match ($type) {
            'url' => $data['url'],
            'text' => $data['text'],
            'wifi' => sprintf(
                'WIFI:T:%s;S:%s;P:%s;;',
                $this->escapeWifiField($data['encryption'] ?? ''),
                $this->escapeWifiField($data['ssid'] ?? ''),
                $this->escapeWifiField($data['password'] ?? ''),
            ),
            'vcard' => $this->buildVcard($data),
            default => $data['url'] ?? '',
        };
    }

    private function escapeWifiField(string $value): string
    {
        return str_replace(['\\', ';', ',', '"'], ['\\\\', '\\;', '\\,', '\\"'], $value);
    }

    /** @param array<string, string> $d */
    private function buildVcard(array $d): string
    {
        $name = str_replace(["\r", "\n"], '', $d['name'] ?? '');
        $email = str_replace(["\r", "\n"], '', $d['email'] ?? '');
        $phone = str_replace(["\r", "\n"], '', $d['phone'] ?? '');

        return "BEGIN:VCARD\nVERSION:3.0\nFN:{$name}\nEMAIL:{$email}\nTEL:{$phone}\nEND:VCARD";
    }
}
