<?php

namespace Ignite\Core\Http\Controllers;

use Exception;
use Illuminate\Auth\Events\Registered;
use Illuminate\Validation\ValidationException;
use Ignite\Core\Events\EnrollmentSubmitted;
use Ignite\Core\Http\Forms\EnrollForm;
use Ignite\Core\Contracts\Repositories\ParticipantRepository;
use Kris\LaravelFormBuilder\FormBuilderTrait;

class EnrollmentController extends Controller
{
    use FormBuilderTrait;

    /**
     * @var ParticipantRepository
     */
    protected $participantRepository;

    /**
     * EnrollController constructor.
     *
     * @param ParticipantRepository $participantRepository
     */
    public function __construct(ParticipantRepository $participantRepository)
    {
        $this->participantRepository = $participantRepository;
    }

    /**
     * Create a new enrollment.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        // Build the form
        $form = $this->form(EnrollForm::class, [
            'method' => 'POST'
        ]);

        // Get the page content
        $page = $this->getPageContent('enroll');

        // Display a view
        return view('participant.enrollment.create', compact('form', 'page'));
    }

    /**
     * Store the enrollment.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(\Illuminate\Http\Request $request)
    {
        $form = $this->form(EnrollForm::class);

        $recaptchaFieldName = config('services.recaptcha.field_name', 'g-recaptcha-response');
        $recaptchaFieldType = config('services.recaptcha.field_type', 'recaptcha_v2_robot');
        if (config('services.recaptcha.sitekey')) {
            $form->addBefore(
                array_key_first($form->getFields()),
                $recaptchaFieldName,
                $recaptchaFieldType,
                $form->getField($recaptchaFieldName)->getOptions()
            );
        }

        $form->redirectIfNotValid();

        try {
            if ($form->has($recaptchaFieldName)) {
                $form->remove($recaptchaFieldName);
            }

            $participant = $this->participantRepository->create(
                $form->getFieldValues()
            );

            event(new Registered($participant->user));
            event(new EnrollmentSubmitted($participant));

            return redirect()->route('participant.enroll.accepted');
        } catch (Exception $e) {
            $this->logException($e);
            // TODO: Move to a language file
            $this->flash(
                'danger',
                'Sorry, we were unable to enroll you at this time. ' .
                'Please contact support via email: ' . config('mail.from.address')
            );
            return redirect()->back();
        }
    }
}
