<?php
namespace App\Services;

use Illuminate\Support\Facades\Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Support\Str;

class QrCodeService
{
    /**
     * Create a QR code file and return the full storage path.
     *
     * @param  string  $text      Content encoded in the QR code
     * @param  string  $extension png|svg
     * @return string             Full absolute file path
     */
    public function make(string $text, string $extension = 'png'): string
    {
        // Validate type
        $extension = strtolower($extension);

        if (!in_array($extension, ['png', 'svg'])) {
            throw new \InvalidArgumentException("Invalid QR extension. Must be png or svg.");
        }

        // Generate random filename
        $filename = Str::random(32) . '.' . $extension;

        // Path inside storage/public/qrcodes
        $path = "qrcodes/{$filename}";

        // Generate QR
        if ($extension === 'png') {
            $qr = QrCode::format('png')
                ->size(400)
                ->errorCorrection('H')
                ->generate($text);  // binary PNG
        } else {
            $qr = QrCode::size(400)
                ->errorCorrection('H')
                ->generate($text);  // SVG
        }

        // Save file
        Storage::disk('public')->put($path, $qr);

        // Return full disk path
        return Storage::disk('public')->path($path);
    }

    /**
     * Get a public asset URL for a stored QR code.
     */
    public function url(string $fullPath): string
    {
        // Convert full storage path → storage/public relative path
        $relative = str_replace(Storage::disk('public')->path(''), '', $fullPath);

        return Storage::disk('public')->url($relative);
    }
}
