<?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 Yajra\Datatables\Datatables;
use App\User;
use Spatie\Permission\Models\Role;
use Storage;
use DB;
class UserController extends Controller
{
    protected $table;
    protected $table_pivot ='model_has_roles';
    protected $role;

    function __construct(){
        $this->middleware('auth');
        $this->table = new User();
        $this->role = new Role();
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('User.views.user');

    }
 
    /**
     * Display a listing of the datatables list.
     *
     */
    public function getTable()
    {   
        $table = Datatables::of(User::with('roles')->where('id','!=',Auth::id())->get());
        $table->addColumn('action', function($row){
            return view('layouts.buttons.buttons-admin')->with('url','user')->with('id',$row['id']);
        })->addColumn('roles',function($row){
            $roles = '';
            foreach ($row['roles'] as $r) {
                $roles .= " <span class='text-uppercase'>".$r->name." <i class='icon-bookmark2'></i></span>";
            }
            return $roles;
        })->rawColumns(['action','roles']);
        return $table->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $roles = $this->role::all();
        return view('User.views.add.user',['role'=>$roles]);
    }

    /**
     * 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',
                        'ruc' => 'required',
                        'email' => 'required',
                        'roles' => 'required',
                    ]);
                    if ($validator->fails()) {
                        return response()->json(['error'=>$validator->errors()->all()]);
                    }else{
                        if ($this->table::where('ruc', '=', $data['ruc'])->count() > 0) {
                            return response()->json(['error'=>array('El ruc '.$data['ruc'].' ya existe')]);
                        }else if ($this->table::where('email', '=', $data['email'])->count() > 0) {
                            return response()->json(['error'=>array('El email '.$data['email'].' ya existe')]);
                        }else{
                            $user = User::create([
                                'name' => $data['name'],
                                'email' => $data['email'],
                                'password'=>Hash::make($data['password']),
                                'nempresa'=>$data['nempresa'],
                                'direccion'=>$data['direccion'],
                            ]);
                            if ($request->has('roles')) {
                                for ($i=0; $i <count($data['roles']) ; $i++) { 
                                    $user->assignRole($data['roles'][$i]);
                                }
                            }
                           $request->session()->flash('create', 'Registro agregado con exito!');
                           return response()->json(['success'=>'Registro agregado con exito','url'=>url("user/")]);
                        }
                    }

                break;
                default:
                   # code...
                break;
           }
       }
    }

    /**
     * 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)
    {
        $roles = $this->role::all();
        $user = $this->table::with('roles')->find($id);
        return view('User.views.edit.user',['user'=>$user,'role'=>$roles]);
    }

    /**
     * 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::with('roles')->find($id);
        if (!empty($data)) {
            $datos = $request->all();

            if ($request->has('roles')) {
                DB::table($this->table_pivot)->where('model_id',$id)->delete();
                for ($i=0; $i <count($datos['roles']) ; $i++) { 
                    $data->assignRole($datos['roles'][$i]);
                }
            }
            $datos['password'] = (!empty($datos['password'])) ?  $datos['password'] : $data->password;
            $data->fill($datos)->save();
            $request->session()->flash('update', 'Registro actualizado con exito!');
            return response()->json(['success'=>'Registro actualizado con exito','url'=>url('user/'.$id.'/edit')]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {

        if (substr($id, 0,4) == 'user') {
            $ex = explode('-', $id);
            $data = $this->table::find($ex[1]);
            $data->removeRole($ex[2]);
            return response()->json(['success'=>'Registro eliminado con exito']);
        }else{
            $data = $this->table::find($id);
            if (!empty($data)) {
                DB::table($this->table_pivot)->where('model_id',$id)->delete();
                $data->delete();
                return response()->json(['success'=>'Registro eliminado con exito']);
            }
        }
    }
}
