<?php

namespace App\Modules\User\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use App\Modules\User\Models\Modules_user;
use Spatie\Permission\Models\Role;
use Yajra\Datatables\Datatables;
use DB;
class ModulesController extends Controller
{
    protected $table;
    protected $table_pivot = 'modules_has_rol';
    protected $role;

    function __construct(){
        $this->middleware('auth');
        $this->table = new Modules_user();
        $this->role = new Role();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {       
        $roles = $this->role::all();
        return view('User.views.modules',['roles'=>$roles]);
    }
    /**
     * Display a listing of the datatables list.
     *
     */
    public function getTable()
    {   
        $table = Datatables::of($this->table::all());
        $table->addColumn('action', function($row){
            return view('layouts.buttons.buttons-admin')->with('url',url('user/config/modules'))->with('id',$row['id'])->with('modal','1');
        })->addColumn('url', function($row){
            return url($row['url']);
        })
        ->rawColumns(['action']);
        return $table->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       if ($request->has('action')) {
           $data = $request->all();
           switch ($data['action']) {
                case 'showtable':
                    return $this->getTable();    
                break;
                case 'add':
                    $validator = Validator::make($request->all(),[
                        'name' => 'required',
                    ]);
                    if ($validator->fails()) {
                        return response()->json(['error'=>$validator->errors()->all()]);
                    }else{
                        if ($this->table::where('name', '=', $data['name'])->count() > 0) {
                            return response()->json(['error'=>array('El rol '.$data['name'].' ya existe')]);
                        }else{
                            $this->table->name = $data['name'];
                            $this->table->url = $data['url'];
                            $this->table->save();

                            if ($request->has('roles')) {
                                for ($i=0; $i <count($data['roles']) ; $i++) { 
                                   DB::table($this->table_pivot)->insert([ 
                                        'modules_user_id'=> $this->table->id,
                                        'role_id' => $data['roles'][$i]
                                   ]);
                                }
                            }
                           $request->session()->flash('success', 'Registro agregado con exito!');
                           return response()->json(['success'=>'Registro agregado con exito','url'=>url('user/config/modules')]);
                        }
                    }

                break;
                case 'reloadurl':
                   $all = $this->table::all();
                   foreach ($all as $o) {
                       $o->url = $o->url;
                       $o->save();
                   }
                   return response()->json(['success'=>'Registro agregado con exito','tablereload'=>'1']);
                break;
                default:
                   # code...
                break;
           }
       }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function get_permission_by_role($id){
        $get = DB::table($this->table_pivot)->where('modules_user_id',$id)->get();
        $data = array();
        foreach ($get as $g) {
            $role = Role::find($g->role_id);
            $data[] = (Object)array('name'=>$role->name,'id'=>$role->id);
        }
        return $data;
    }
    public function show($id)
    {
        $data = $this->table::find($id);
        $roles = Role::all();
        $role = $this->get_permission_by_role($id);
        if (!empty($data)) {
            return view('User.views.edit.module',['data'=>$data,'roles'=>$roles,'roles_by_id'=>$role]);
        }else{

        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
 
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $data = $this->table::find($id);
        if (!empty($data)) {
            $datos = $request->all();
            if ($request->has('roles')) {
                $get = DB::table($this->table_pivot)->where('modules_user_id',$id)->delete();
                for ($i=0; $i <count($datos['roles']) ; $i++) { 
                    DB::table($this->table_pivot)->insert([ 
                        'modules_user_id'=> $id,
                        'role_id' => $datos['roles'][$i]
                    ]);
                }
            }
            unset($datos['roles']);
            $datos['url'] = $datos['url'];
            $data->fill($datos)->save();
            $request->session()->flash('success', 'Registro agregado con exito!');
            return response()->json(['success'=>'Registro actualizado con exito','url'=>url('user/config/modules')]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = $this->table::find($id);
        if (!empty($data)) {
            $get = DB::table($this->table_pivot)->where('modules_user_id',$id)->delete();
            $data->delete();
            return response()->json(['success'=>'Registro eliminado con exito']);
        }
    }
}
