<?php

namespace Ignite\Core\Http\Controllers\Admin;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Ignite\Core\Http\Controllers\Controller;
use Ignite\Core\Http\Forms\ProfileForm;
use Ignite\Core\Models\Grid\ParticipantTable;
use Ignite\Core\Contracts\Repositories\ParticipantRepository;
use Kris\LaravelFormBuilder\FormBuilderTrait;

class ParticipantController extends Controller
{
    use FormBuilderTrait;

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

    /**
     * Create a new controller instance.
     *
     * @param ParticipantRepository $participantRepository
     */
    public function __construct(ParticipantRepository $participantRepository)
    {
        $this->participantRepository = $participantRepository;
    }

    /**
     * Show the admin index page which will list participants by status.
     *
     * @param ParticipantTable $table
     * @param Request          $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Contracts\View\View
     */
    public function index(ParticipantTable $table, Request $request)
    {
        $status = $request->query('status', 'active');
        $statuses = $this->participantRepository->getStatuses();
        $statusLookup = array_flip($statuses);

        if (! array_key_exists($status, $statusLookup)) {
            $status = 'active';
        }

        $current = $status;
        session()->put('participantListType', $current);

        $table->with('status', $statusLookup[$status]);

        if ($request->wantsJson()) {
            return $table->ajax();
        }

        return $table->render('Core::admin.participants.index', compact('statuses', 'current'));
    }

    /**
     * Create a participant.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $form = $this->form(ProfileForm::class, [
            'method' => 'POST',
            'route' => 'admin.participant.store',
            'participant_type' => request()->type,
        ]);

        return view('Core::admin.participants.create', compact('form'));
    }

    /**
     * Save the New User Add page.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store()
    {
        $form = $this->form(ProfileForm::class);

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

        try {
            /** @var \Ignite\Core\Entities\Participant $participant */
            $participant = $this->participantRepository->create($form->getFieldValues());
            // TODO: Move to a language file
            $this->flash('success', 'Participant created successfully.');
            return redirect()->route('admin.participant.show', $participant->getKey());
        } catch (\Exception $e) {
            $this->logException($e);
            // TODO: Move to a language file
            $this->flash('error', 'We were unable to create the participant. Please contact IT.');

            return redirect()->back();
        }
    }

    /**
     * Show the Participant Edit page.
     *
     * @param  int $userId
     * @return \Illuminate\Http\Response
     * @throws \Ignite\Packages\Presenter\Exceptions\PresenterException
     */
    public function edit($userId)
    {
        $participant = $this->participantRepository->find($userId);

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

        $participant = $participant->present();

        return view('Core::admin.participants.edit', compact('form', 'participant'));
    }

    /**
     * Save the Participant Edit page.
     *
     * @param  int $userId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update($userId)
    {
        $form = $this->form(ProfileForm::class, [
            'model' => $this->participantRepository->find($userId)
        ]);

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

        try {
            /** @var \Ignite\Core\Entities\Participant $participant */
            $participant = $this->participantRepository->update($userId, $form->getFieldValues(true));
            // TODO: Move to a language file
            flash()->success('Participant updated successfully.')->important();

            return redirect()->route('admin.participant.show', $participant->getKey());
        } catch (\Exception $e) {
            $this->logException($e);
            // TODO: Move to a language file
            flash()->error(
                'We were unable to update the participant. Please contact IT.'
            );

            return redirect()->back();
        }
    }

    /**
     * Show the participant view page.
     *
     * @param  int $userId
     * @return \Illuminate\Http\Response
     */
    public function show($userId)
    {
        $participant = $this->participantRepository->find($userId);

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

        $participant = $participant->present();

        return view('Core::admin.participants.show', compact('participant', 'form'));
    }

    /**
     * Show the delete confirmation view.
     *
     * @param  int $userId
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function delete($userId)
    {
        $participant = $this->participantRepository->find($userId)->present();

        return view('Core::admin.participants.delete', compact('participant'));
    }

    /**
     * Trash the record.
     *
     * @param  int $userId
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function destroy($userId)
    {
        DB::beginTransaction();
        try {
            $participant = $this->participantRepository->find($userId, true);
            $this->participantRepository->trash($userId);
            $message = sprintf('%s was successfully trashed.', $participant->fullName());
            flash()->success($message)->important();
            DB::commit();
            return redirect()->route('admin.participant.index');
        } catch (\Exception $e) {
            DB::rollback();
            flash()->error($e->getMessage())->important();
            return redirect()->route('admin.participant.index');
        }
    }
}
