<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\CustomExport;
use App\Helpers\Helper;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('Admin.setting.role.index', ['data' => array()]);
    }
    public function findData(Request $request)
    {
        $data = array();
        $input = $request->input();
        if(count($input) > 0){
            $data = $input;
            $data['show_table'] = 1;
            session()->flashInput($request->input());
        }
        return view('Admin.setting.role.index', ['data' => array()]);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('Admin.setting.role.create_edit');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request);
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255', 'unique:roles']
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        $input = $request->input();
        unset($input['_token']);

        Role::create($input);
        Helper::successMsg("insert", "Role");
        return redirect()->route('role.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // $data = Role::find(decrypt($id));
        // // dd($data);
        // return view('Admin.setting.role.permission', ['data' => $data, 'pageTitle'=>"Roles & Permission"]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Role::find(decrypt($id));
        // dd($data);
        return view('Admin.setting.role.create_edit', ['data' => $data]);
    }

    /**
     * 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:roles,id,'.$id
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }
        $input = $request->input();
        unset($input['_token']);
        unset($input['_method']);


        Role::where("id", $id)->update($input);
       
        Helper::successMsg("update", "Role");
        return redirect()->route('role.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Role::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "Role");
        return redirect()->back();
    }
    public function delete($id)
    {
        Role::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "Role");
        return redirect()->back();
    }
    public function status(Request $request, $id)
    {
        Role::where("id",decrypt($id))->update(array("status"=>$request->status,"updated_at"=>date("Y-m-d H:i:s")));
        Helper::successMsg("Status", "Role");
        return redirect()->back();
    }
    public function data(Request $request)
    {
        $where = array();
        //filters
        if($request->filters != ""){
            foreach($request->filters as $k=>$v){
                // $where[$v['name']] = $v['value'];
            }
            
        }

        if(empty($where)){
            $where = array(["id", ">", 0]);
        }
        session(["whereExportFilter" => ['whereExport' => $where]]);
        // dd($where);
        $start = $request->has('start')?(int)$request->start:0;
        $perPage = $request->has('length')?(int)$request->length:10;

        $totalRecord = Role::where($where)->count();
        $tableData = Role::where($where)->orderBy('id', 'asc')->offset($start)->limit($perPage)->get();
        // dd($tableData);
        $datatable = DataTables::of($tableData)
            ->skipPaging()
            ->setTotalRecords($totalRecord)
            ->editColumn('selectbox', function ($val) {
                return '<input type="checkbox" name="checkedboxes[]" value="'.$val->id.'"/>';
            })
            ->addIndexColumn()
           
            ->addColumn('status', function ($val) {
                $encrypt = encrypt($val->id);
                $status = "";
                
                if($val->status == "0"){
                    //disable
                    $status .= '<button type="button" style="" class="btn btn-sm status_btn btn-danger btn-link" data-next_click="1" data-status_link="' . route('role.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Deactive"><i class="fas fa-times" aria-hidden="true"></i></button>';
                }else{
                    $status .= '<button type="button" style="" class="btn btn-sm status_btn btn-success btn-link" data-next_click="0" data-status_link="' . route('role.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Active"><i class="fas fa-check" aria-hidden="true"></i></button>';
                }
                return $status;
            })
            ->addColumn('action', function ($val) {
                $encrypt = encrypt($val->id);
                $action = "";
                
                $action .= '<a class="btn btn-sm btn-primary btn-link" href="' . route('role.edit', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Edit"><i class="fas fa-pen" aria-hidden="true"></i></a>';
                $action .= '&nbsp;<a class="btn btn-sm btn-info btn-link" href="' . route('permission.show', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Permission"><i class="fas fa-shield-alt" aria-hidden="true"></i></a>';
                // $action .= '<button type="button" style="" class="btn btn-sm delete_btn btn-danger btn-link" data-delete_link="' . route('role.delete', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Delete"><i class="fas fa-trash" aria-hidden="true"></i></button>';
                
                return $action;
            })
            ->rawColumns(['selectbox','status','action'])
            ->make(true);
        return $datatable;
    }
    public function export(Request $request)
    {
        $where = array(["id", ">", 0]);
        
        if(session()->has('whereExportFilter')){
            $where = session()->get('whereExportFilter')['whereExport'];
        }
        $data = Role::where($where)->orderBy('id', 'asc')->get();
        return Excel::download(new CustomExport("Admin.setting.role.export", ["data"=>$data, "title"=>"Roles"]),  'role.xlsx');
    }
    public function multiDelete(Request $request){
        $rolesIds = $request->has('checkedboxes')?$request->checkedboxes:array();
        if(count($rolesIds) > 0){
            Role::whereIn("id", $rolesIds)->delete();
            Helper::successMsg("delete", "Role");
        }else{
            Helper::failarMsg("custom", "Not Allowed to delete Multi records!");
        }
        return redirect()->back();
    }
}
