<?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
     */
    public function update()
    {
        $participant = $this->participantRepository->findAuthenticated();

        $form = $this->form(ProfileForm::class);

        $this->participantRepository->update(
            $participant->getKey(), $form->getFieldValues(true)
        );

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