<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\MenuModelPermission;
use Spatie\Permission\Models\Permission;

class PermissionsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:permission-list', ['only' => ['index']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $module)
    {
        $menu_module = MenuModelPermission::find($module);

        if (!$menu_module) {
            return redirect()->route('modules')->with('error', $validator->getMessageBag()->first());
        }
        $data = Permission::where("module_id", $module)->paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = Permission::where("module_id", $module)
                    ->when(!empty($search_query), function ($query) use ($search_query) {
                        return $query->where('name', 'like', '%'.$search_query.'%')
                            ->orWhere('per_name', 'like', '%'.$search_query.'%');
                    })
                    ->paginate($sort_by);

            return view('permissions.table', compact('data'));
        }
        else
        {
            return view('permissions.index',compact('data', 'menu_module'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('permissions.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:permissions',
        ]);
        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        $module    = MenuModelPermission::where('id', $request->module_id)->select('menu_name')->first();
        $menu_name = \Str::slug(strtolower($module->menu_name), '-');
        $data      = $request->except([
            '_token',
            '_method'
        ]);
        $data['guard_name'] = 'web';
        $data['name']       = $menu_name . '-' . strtolower($request->name);

        Permission::create($data);

        return redirect()->back()
            ->with('success','Permission created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $permission = Permission::find($id);

        return view('permissions.edit',compact('permission'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:permissions,name,'.$id
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $permission = Permission::find($id);

        if (!$permission) {
            return redirect()->back()
                ->with('error','Permission not found!');
        }

        $permission->update($data);

        return redirect()->back()
            ->with('success','Permission updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        Permission::find($request->id)->delete();

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'reload' => true,
                'redirect' => false,
            ]
        ]);
    }
}
