<?php

namespace Ignite\Core\Http\Controllers;

use Ignite\Core\Exceptions\InvalidPasswordException;
use Ignite\Core\Http\Forms\PasswordForm;
use Ignite\Core\Repositories\ParticipantRepository;
use Kris\LaravelFormBuilder\FormBuilderTrait;

class PasswordController extends Controller
{
    use FormBuilderTrait;

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

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

    /**
     * Edit a participant's password.
     *
     * @return \Illuminate\View\View
     */
    public function edit()
    {
        $participant = $this->participantRepository->findAuthenticated();

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

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

    /**
     * Update the profile information.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update()
    {
        try {
            $form = $this->form(PasswordForm::class);
            $values = $form->getFieldValues(true);
            $this->participantRepository->changePassword(
                auth()->user()->getKey(),
                $values['old_password'],
                $values['password']
            );
            $this->flash('success', 'Password changed successfully.');
            return redirect()->route('participant.profile.show');
        } catch (InvalidPasswordException $e) {
            $this->logException($e);
            $this->flash('danger', $e->getMessage());
            return redirect()->back();
        } catch (\Exception $e) {
            $this->logException($e);
            $this->flash('danger', 'We were unable to change your password. Please contact program headquarters.');
            return redirect()->back();
        }
    }
}
