<?php

namespace Ignite\Core\Http\Controllers\Admin;

use Ignite\Core\Contracts\Repositories\PermissionRepository;
use Ignite\Core\Http\Controllers\Controller;
use Ignite\Core\Http\Forms\Admin\PermissionForm;
use Ignite\Core\Models\Grid\PermissionTable;
use Illuminate\Http\Request;

class PermissionsController extends Controller
{
    /**
     * @var PermissionRepository
     */
    private $permissionRepository;

    /**
     * PermissionsController constructor.
     *
     * @param PermissionRepository $permissionRepository
     */
    public function __construct(PermissionRepository $permissionRepository)
    {
        $this->permissionRepository = $permissionRepository;
    }

    /**
     * Display the list of permissions.
     *
     * @param  PermissionTable $table
     * @param  Request $request
     * @return mixed
     */
    public function index(PermissionTable $table, Request $request)
    {
        if ($request->wantsJson()) {
            return $table->ajax();
        }

        return $table->render('Core::admin.security.permissions.index', compact('table'));
    }

    /**
     * Display the form to create a new permission.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $form = $this->form(PermissionForm::class, [
            'method' => 'POST',
            'url' => route('admin.security.permissions.store')
        ]);

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

    /**
     * Store the new permission.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store()
    {
        $form = $this->form(PermissionForm::class);

        $values = $form->getFieldValues();

        if (! $form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput($values);
        }

        try {
            $permission = $this->permissionRepository->create($values);
            $this->flashSuccess('Permission created successfully.');
            return redirect()->route('admin.security.permissions.edit', $permission);
        } catch (\Exception $e) {
            $this->logException($e);
            $this->flashError('Permission could not be created. I.T. has been notified.');
            return redirect()->back();
        }
    }

    /**
     * Display the form to edit an existing permission.
     *
     * @param  int $permission
     * @return \Illuminate\View\View
     */
    public function edit($permission)
    {
        $permission = $this->permissionRepository->find($permission);

        $form = $this->form(PermissionForm::class, [
            'method' => 'PATCH',
            'url' => route('admin.security.permissions.update', $permission),
            'model' => $permission
        ]);

        return view('Core::admin.security.permissions.edit', compact('form', 'permission'));
    }

    /**
     * Update the existing permission.
     *
     * @param  int $permission
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update($permission)
    {
        $form = $this->form(PermissionForm::class, [], ['permission' => $permission]);
        $values = $form->getFieldValues();

        if (! $form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput($values);
        }

        try {
            $permission = $this->permissionRepository->update($permission, $values);
            $this->flashSuccess('Permission updated successfully.');
            return redirect()->route('admin.security.permissions.edit', $permission);
        } catch (\Exception $e) {
            $this->logException($e);
            $this->flashError('Permission could not be updated. I.T. has been notified.');
            return redirect()->back();
        }
    }

    /**
     * Delete the permission.
     *
     * @param  int $permission
     * @param  Request $request
     * @return \Illuminate\Http\Response
     */
    public function destroy($permission, Request $request)
    {
        try {
            $this->permissionRepository->delete($permission);
            $message = "Permission with ID: $permission was deleted successfully.";
            $status = 'success';
        } catch (\Exception $e) {
            $message = "Permission with ID: $permission could not be deleted. Error: " . $e->getMessage();
            $status = 'error';
        }

        if ($request->wantsJson()) {
            return response()->json(['status' => $status, 'message' => $message]);
        }

        $this->flash($status, $message);

        return redirect()->back();
    }

    /**
     * Delete the group.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function destroyMany(Request $request)
    {
        $ids = $request->get('ids', '');
        $permissions = explode(',', $ids);
        $count = count($permissions);
        $noun = str_plural('permission', count($permissions));
        $verb = $count === 1 ? 'was' : 'were';

        try {
            $this->permissionRepository->deleteMany($permissions);
            $this->flashSuccess("$count $noun $verb deleted successfully.");
        } catch (\Exception $e) {
            $this->logException($e);
            $this->flashError("Unable to delete the selected $count $noun: $ids.");
        }

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