<?php

namespace App\Http\Resources\Tenant;

use App\Models\Event;
use App\Support\JoinTokenLayoutRegistry;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Route;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class EventJoinTokenResource extends JsonResource
{
    /**
     * @param  Request  $request
     */
    public function toArray($request): array
    {
        /** @var Event|null $eventFromRoute */
        $eventFromRoute = $request->route('event');
        $eventContext = $eventFromRoute instanceof Event ? $eventFromRoute : ($this->resource->event ?? null);

        $layouts = [];
        if ($eventContext && Route::has('api.v1.tenant.events.join-tokens.layouts.download')) {
            $layouts = JoinTokenLayoutRegistry::toResponse(function (string $layoutId, string $format) use ($eventContext) {
                return route('api.v1.tenant.events.join-tokens.layouts.download', [
                    'event' => $eventContext,
                    'joinToken' => $eventContext instanceof Event ? $this->resource->id : $this->resource,
                    'layout' => $layoutId,
                    'format' => $format,
                ]);
            });
        }

        $layoutsUrl = null;
        if ($eventContext && Route::has('api.v1.tenant.events.join-tokens.layouts.index')) {
            $layoutsUrl = route('api.v1.tenant.events.join-tokens.layouts.index', [
                'event' => $eventContext,
                'joinToken' => $eventContext instanceof Event ? $this->resource->id : $this->resource,
            ]);
        }

        $plainToken = $this->resource->plain_token ?? $this->token;
        $qrCodeUrl = $plainToken ? url('/e/'.$plainToken) : null;
        $qrCodeDataUrl = null;

        if ($qrCodeUrl) {
            try {
                $png = QrCode::format('png')
                    ->size(360)
                    ->margin(1)
                    ->errorCorrection('M')
                    ->generate($qrCodeUrl);

                $pngBinary = (string) $png;

                if ($pngBinary !== '') {
                    $qrCodeDataUrl = 'data:image/png;base64,'.base64_encode($pngBinary);
                }
            } catch (\Throwable $exception) {
                report($exception);
            }
        }

        return [
            'id' => $this->id,
            'label' => $this->label,
            'token' => $plainToken,
            'token_preview' => $this->token_preview,
            'url' => $qrCodeUrl,
            'qr_code_data_url' => $qrCodeDataUrl,
            'usage_limit' => $this->usage_limit,
            'usage_count' => $this->usage_count,
            'expires_at' => optional($this->expires_at)->toIso8601String(),
            'revoked_at' => optional($this->revoked_at)->toIso8601String(),
            'is_active' => $this->isActive(),
            'created_at' => optional($this->created_at)->toIso8601String(),
            'metadata' => $this->metadata ?? new \stdClass,
            'layouts_url' => $layoutsUrl,
            'layouts' => $layouts,
        ];
    }
}
