<?php

namespace App\Livewire\Portal;

use App\Domain\Attendance\Services\CheckInTokenService;
use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Shared\Support\QrCode;
use App\Livewire\Portal\Concerns\PortalScreen;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

/**
 * The member's rotating check-in pass.
 *
 * Rendered server-side as an inline SVG — no CDN, no third party, and it keeps
 * working when the venue's wifi does not. The one QR that exists in this
 * codebase today is an <img> pointing at api.qrserver.com on an admin event
 * page, which would send every member's identity token to someone else's server.
 *
 * The code is fetched over the Livewire round-trip and never appears in a URL,
 * so it stays out of browser history, referrer headers and proxy logs.
 *
 * It is per active profile: a guardian with three children needs three passes,
 * which is why this is an affordance in the header rather than a bottom tab.
 */
#[Layout('layouts.portal')]
#[Title('بطاقة الدخول')]
class PortalPass extends Component
{
    use PortalScreen;

    public ?string $error = null;

    public function mount(): void
    {
        $this->authorizePortal();
    }

    public function render()
    {
        $participant = $this->portal()->activeParticipant();
        $svg = null;
        $secondsLeft = null;

        if ($participant) {
            try {
                $tokens = app(CheckInTokenService::class);
                $token = $tokens->issue($participant);
                $svg = QrCode::svg($token, 260, 4, __('رمز دخول العضو'));

                // How long this code stays valid, so the screen can count down
                // rather than silently going stale in someone's hand.
                $secondsLeft = CheckInTokenService::PERIOD_SECONDS
                    - (time() % CheckInTokenService::PERIOD_SECONDS);
            } catch (DomainException $e) {
                $this->error = $e->getMessage();
            }
        }

        return view('livewire.portal.portal-pass', [
            'participant' => $participant,
            'svg' => $svg,
            'secondsLeft' => $secondsLeft,
        ]);
    }
}
