<?php

namespace App\Controllers;

use App\Models\EventModel;
use App\Models\EventRegistrationModel;

/**
 * Public, anonymous — this IS the kiosk. show() renders a big "enter your
 * code" entry screen meant to run full-screen on a shared tablet at the
 * venue entrance (reached by scanning the QR staff display there, or any
 * direct link); submit() validates the code and marks attendance. Both
 * views auto-reset back to the entry screen after a few seconds so the
 * next attendee can walk up without staff intervention.
 */
class EventCheckinController extends BaseController
{
    public function show(string $token)
    {
        $event = (new EventModel())->findByPublicToken($token);

        if ($event === null) {
            return view('public/not_found', ['pageTitle' => 'Not Found']);
        }

        return view('event_checkin/entry', [
            'pageTitle' => 'Check In — ' . $event->event_name,
            'event'     => $event,
            'token'     => $token,
        ]);
    }

    public function submit(string $token)
    {
        $event = (new EventModel())->findByPublicToken($token);

        if ($event === null) {
            return view('public/not_found', ['pageTitle' => 'Not Found']);
        }

        $code = trim((string) $this->request->getPost('code'));
        $registrations = new EventRegistrationModel();
        $registration  = $registrations->findByEventAndCode($event->id, $code);

        if ($registration === null) {
            return view('event_checkin/entry', [
                'pageTitle' => 'Check In — ' . $event->event_name,
                'event'     => $event,
                'token'     => $token,
                'error'     => 'That code wasn\'t recognized — please check and try again.',
            ]);
        }

        if ($registration->status === 'checked_in') {
            return view('event_checkin/entry', [
                'pageTitle' => 'Check In — ' . $event->event_name,
                'event'     => $event,
                'token'     => $token,
                'error'     => 'That code was already checked in.',
            ]);
        }

        if ($registration->status === 'cancelled') {
            return view('event_checkin/entry', [
                'pageTitle' => 'Check In — ' . $event->event_name,
                'event'     => $event,
                'token'     => $token,
                'error'     => 'This registration was cancelled.',
            ]);
        }

        $registrations->checkIn($registration->id);
        $this->logActivity('events', 'Checked in "' . $registration->full_name . '" at "' . $event->event_name . '".');

        return view('event_checkin/welcome', [
            'pageTitle' => 'Welcome — ' . $event->event_name,
            'event'     => $event,
            'token'     => $token,
            'fullName'  => $registration->full_name,
        ]);
    }
}
