<?php

namespace Zoomyboy\Event\Components;

use Cms\Classes\ComponentBase;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Lang;
use Input;
use Winter\Storm\Support\Facades\Validator;
use Zoomyboy\Event\Jobs\ProcessSubmitJob;
use Zoomyboy\Event\Models\Event;
use Zoomyboy\Event\Models\Participant;

class EventForm extends ComponentBase
{
    public Event $event;

    public function componentDetails()
    {
        return [
            'name' => 'EventForm Component',
            'description' => 'No description provided yet...',
        ];
    }

    public function defineProperties()
    {
        return [
            'event_id' => [
                'label' => 'ID',
            ],
        ];
    }

    private function customInit(int $eventId)
    {
        $this->event = Event::findOrFail($eventId);
    }

    public function onRender()
    {
        $this->customInit($this->property('event_id'));

        return $this->renderPartial('@'.$this->event->slug.'.htm');
    }

    public function onSubmit(): JsonResponse
    {
        $this->customInit(Input::get('event_id'));

        $rules = $this->event->loadConfig('validator');

        if ('Orga' === Input::get('activity')) {
            $rules['vorteam'] = 'in:Ja,Nein';
        }

        $validator = Validator::make(Input::all(), $rules, [
            'vorteam.in' => 'Bitte gebe an, ob du am Vorteam teilnehmen willst.',
            'parent.accepted' => 'Bitte gebe an, dass du volljährig bzw. ein Elternteil bist.',
        ], Lang::get('zoomyboy.event::validation.attributes'));

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        $participant = Participant::create([
            'firstname' => Input::get('firstname'),
            'lastname' => Input::get('lastname'),
            'email' => Input::get('email'),
            'event_id' => $this->event->id,
            'payload' => $this->event->transformInputs(Input::all()),
        ]);

        ProcessSubmitJob::dispatch($participant->id);

        return response()->json([], 201);
    }
}