<?php

namespace Ignite\Core\Http\Controllers;

use Ignite\Core\Http\Forms\ProfileForm;
use Ignite\Core\Repositories\ParticipantRepository;
use Kris\LaravelFormBuilder\FormBuilderTrait;

class ProfileController extends Controller
{
    use FormBuilderTrait;

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

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

    /**
     * Show the profile information.
     *
     * @return \Illuminate\View\View
     */
    public function show()
    {
        $participant = $this->participantRepository->findAuthenticated();

        $form = $this->form(ProfileForm::class, [
            'model' => $participant
        ], ['readonly' => true]);

        return view('participant.profile.show', [
            'participant' => $participant,
            'form' => $form,
        ]);
    }

    /**
     * Edit the profile information.
     *
     * @return \Illuminate\View\View
     */
    public function edit()
    {
        $participant = $this->participantRepository->findAuthenticated();

        $form = $this->form(ProfileForm::class, [
            'method' => 'POST',
            'route' => 'participant.profile.update',
            'model' => $participant
        ]);

        return view('participant.profile.edit', [
            'participant' => $participant,
            'form' => $form,
        ]);
    }

    /**
     * Update the profile information.
     *
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function update()
    {
        $participant = $this->participantRepository->findAuthenticated();

        $form = $this->form(ProfileForm::class, ['model' => $participant]);

        $form->redirectIfNotValid();

        $values = $form->getFieldValues(true);

        $this->participantRepository->update($participant->getKey(), $values);

        $this->flashSuccess('Your profile has been updated.');

        return redirect()->route('participant.profile.show');
    }
}
