<?php

namespace Ignite\Core\Http\Controllers;

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('register');

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

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

        if (! $form->isValid()) {
            throw ValidationException::withMessages($form->getErrors());
        }

        try {
            /** @var \Ignite\Core\Entities\Participant $participant */
            $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('error',
                'Sorry, we were unable to enroll you at this time. ' .
                'The program administrator has been notified ' .
                'and will contact you with further instructions.'
            );
            return redirect()->back();
        }
    }
}
