<?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()
    {
        $form = $this->form(PasswordForm::class);

        try {
            $this->participantRepository->changePassword(
                auth()->user()->getKey(),
                $form->getField('old_password')->getRawValue(),
                $form->getField('password')->getRawValue()
            );
            $this->flash('success', 'Password changed successfully.');
            return redirect()->route('participant.profile.show');
        } catch (InvalidPasswordException $e) {
            $this->logException($e);
            $this->flash('error', $e->getMessage());
            return redirect()->back();
        } catch (\Exception $e) {
            $this->logException($e);
            $this->flash('error', 'We were unable to change your password. Please contact program headquarters.');
            return redirect()->back();
        }
    }
}
