<?php

namespace App\Http\Controllers\Admin\Core\Auth;

use App\Datatables\Admin\Core\Auth\PermissionsDataTable;
use App\Repositories\Core\App\ApplicationModules;
use App\Repositories\Core\App\Applications;
use App\Repositories\Core\Auth\Permissions;
use App\Repositories\Core\Auth\Users;
use Illuminate\Http\Request;

class PermissionController extends Controller
{
    public function __construct()
    {
        $this->middleware('ability:admin,permissions_crud');
    }

    public function index(PermissionsDataTable $dataTable)
    {
        $data = \App\Repositories\Config::init();

        return $dataTable->render('admin.Core.Auth.Permission.index', $data);
    }

    public function create()
    {
        $data = \App\Repositories\Config::init();
        $data['roles'] = Users::getRolesToEdit();
        $data['applications'] = Applications::getOptions();
        $data['application_modules'] = ApplicationModules::getOptions();

        return view('Admin.Core.Auth.Permission.create', $data);
    }

    public function edit(Request $request, $id = false)
    {
        $id = (int) $id ? $id : $request->input('id');
        $data = \App\Repositories\Config::init();
        $data['permission'] = Permissions::get($id);
        $data['roles'] = Users::getRolesToEdit();
        $data['applications'] = Applications::getOptions();
        $data['application_modules'] = ApplicationModules::getOptions();

        return view('Admin.Core.Auth.Permission.edit', $data);
    }

    public function store(Request $request)
    {
        $data = $request->all();
        unset($data['roles']);
        unset($data['_token']);

        /*
                $this->validate($request, [
                    'name'         => 'required|unique:permissions,name',
                    'display_name' => 'required',
                    'description'  => 'required',
                ]);
                $data['name'] = Str::slug($data['display_name']);
        */

        Permissions::store($data);

        return redirect()->route('Admin.Core.Auth.Permission.index')->with('growl', [__('permissions.successadd'), 'success']);
    }

    public function destroy($id)
    {
        Permissions::delete($id);

        return response()->json(['error' => 0]);
    }
}
