<?php

namespace Ignite\Core\Http\Controllers\Admin;

use Ignite\Core\Contracts\Repositories\TransactionRepository;
use Ignite\Core\Http\Forms\Admin\TransactionForm;
use Ignite\Core\Models\Grid\TransactionTable;
use Illuminate\Http\Request;
use Ignite\Core\Http\Controllers\Controller;

class TransactionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param TransactionTable $table
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function index(TransactionTable $table, Request $request)
    {
        if ($request->wantsJson()) {
            return $table->ajax();
        }

        return $table->render('Core::admin.transactions.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $form = $this->form(TransactionForm::class, [
            'method' => 'POST',
            'route' => 'admin.transactions.store'
        ]);

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

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

        $form->redirectIfNotValid();

        $values = $form->getFieldValues(true);

        try {
            $transactionRepository->create(array_merge($values, [
                'related_id' => 0,
                'related_type' => null,
            ]));

            $this->flashSuccess('Transaction created successfully.');
        } catch (\Exception $e) {
            $this->flashError('Manual transaction could not be created.');
            $this->flashError($e->getMessage());
            return redirect()
                ->back()
                ->withErrors($form->getErrors(), $form->getErrorBag())
                ->withInput();
        }

        return redirect()->route('admin.transactions.index');
    }
}
