<?php

namespace Ignite\Core\Http\Controllers\Admin;

use Ignite\Core\Facades\Format;
use Ignite\Core\Http\Controllers\Controller;
use Ignite\Core\Http\Forms\Admin\TransactionForm;
use Ignite\Core\Http\Requests\CreateTransactionRequest;
use Ignite\Core\Models\Grid\ParticipantTransactionTable;
use Ignite\Core\Repositories\ParticipantRepository;
use Ignite\Core\Repositories\TransactionRepository;
use Ignite\Flash\Facades\Flash;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;

class ParticipantTransactionsController extends Controller
{
    /**
     * @var TransactionRepository
     */
    protected $transactionRepository;

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

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

    /**
     * Show the Transactions that belong to the provided participant.
     *
     * @param  bool|int $userId
     * @param  ParticipantTransactionTable $table
     * @param  Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     * @throws \Ignite\Packages\Presenter\Exceptions\PresenterException
     */
    public function index($userId, ParticipantTransactionTable $table, Request $request)
    {
        $table->with('user_id', $userId);
        $participant = $this->participantRepository->find($userId)->present();
        $balance = $this->transactionRepository->getBalance($userId);

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

        $form = $this->form(TransactionForm::class, [
            'method' => 'POST',
            'userId' => $userId,
            'url' => route('admin.participant.transactions.store', ['participant' => $userId])
        ]);

        return $table->render('Core::admin.transactions.participant.index', compact(
            'participant',
            'balance',
            'form'
        ));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store($userId)
    {
        $form = $this->form(TransactionForm::class, [
            'userId' => $userId,
        ]);

        if (! $form->isValid()) {
            Flash::error('Manual transaction could not be created. Please try again and see errors.');
            $form->redirectIfNotValid();
        }

        $values = $form->getFieldValues(true);
        $values['user_id'] = $userId;

        try {
            $this->transactionRepository->create(array_merge($values, [
                'related_id' => 0,
                'related_type' => null,
            ]));
            $this->flashSuccess('Transaction created successfully.');
        } catch (\Exception $e) {
            Flash::error('Manual transaction could not be created.');
            Flash::error($e->getMessage());
            return redirect()
                ->route('admin.participant.transactions', $userId)
                ->withErrors($form->getErrors(), $form->getErrorBag())
                ->withInput();
        }

        return redirect()->route('admin.participant.transactions', $userId);
    }
}
