<?php namespace App\Http\Controllers;

use Auth\AuthController;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use View;
use DB;
use Hash;
use App\Http\Requests\UserRequest;
use Illuminate\Http\Request;
use Validator;

 
class UsersController extends Controller {
 
    private $menu='acces';
    private $submenu='utilisateurs';

    public function verif_user()
    {
        $user = Auth::user();
        if(!$user) return Redirect::route( 'login' );

        return $user;
    }

    public function index()
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("consulter utilisateurs")) return Redirect::route('home');


        $user=$this->verif_user() ; //Vérification $user 
        $users_list = User::all();
        $t_user=array();
        if(!$user->hasRole("ADMINISTRATEUR")) {
            foreach($users_list as $u) {
                if(!$u->hasRole("ADMINISTRATEUR")) $t_user[]=$u->id;
            }
            $users_list = User::wherein('id',$t_user)->get();
        } 
        return View::make('acces.users.index', 
            ['user' => $user,
            'menu' => $this->menu,'submenu' => $this->submenu,
            'users_list'=>$users_list,
            'user'=>$user]);

    }
 
    public function create()
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("ajouter utilisateurs")) return Redirect::route('home');

        if(!$user) return Redirect::route( 'login' );

        $liste_roles=Role::pluck("name","id")->toArray();
        $mode="create";
        return View::make('acces.users.create',
            [ 'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu, "mode"=>$mode,
                'liste_roles' => $liste_roles,
        ]);
    }
 
    public function store(UserRequest $request)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("ajouter utilisateurs")) return Redirect::route('home');

        //REcherche 
        $user_emailexiste=User::where('email','=',$request->email)->first();
        if(  $user_emailexiste) {
            return redirect()->back()->withInput()->withErrors(
                ['message1'=>'Cet email est déjà utilisé par une autre utilisateur ('.$user_emailexiste->NomComplet.')']);   
        }
        $user_nomexiste=User::where('name','=',$request->name)->first();
        if($user_nomexiste) {
            return redirect()->back()->withInput()->withErrors(
                ['message1'=>'Ce Nom est déjà utilisé par une autre utilisateur']);   
        }

        $user=$this->setData($request);

        $msg="Le compte de l'utilisateur ".$user->NomComplet." a été créé";
        return Redirect::to('/users')->with('success', $msg); 
    }
 
    public function edit($id,$mode="edit")
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("modifier utilisateurs")) return Redirect::route('home');

        $user = Auth::user();
        if(!$user) return Redirect::route( 'login' );
        $user_sel = User::find($id);


        if(!$user->hasRole("ADMINISTRATEUR")) $liste_roles = Role::where('name',"<>","ADMINISTRATEUR")->pluck("name","id")->toArray();
        else $liste_roles = Role::pluck("name","id")->toArray();

        $t_getroles=DB::table('model_has_roles')
            ->where('model_id', '=', $user_sel->id)
            ->where('model_type','=','App\Models\User')
            ->pluck("role_id")
            ->toArray();
        return View::make('acces.users.'.$mode, [ 
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu, "mode"=>$mode,
            'user_sel' => $user_sel ,
            't_getroles' => $t_getroles, 
            'liste_roles' => $liste_roles
        ]);
    }
 
    public function update($id,UserRequest $request)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("modifier utilisateurs")) return Redirect::route('home');

        //Si mot de passe change on vérifie
        $user_maj = User::find($id);
        $old_password=$user_maj->password;
        if($request->password=='') $user_maj->password=$old_password;
        else {
            $v = Validator::make($request->all(), ['password' => 'required|min:3',]);
            if ($v->fails()) return redirect()->back()->withErrors($v->errors());   
            $user_maj->password   = Hash::make($request->password); 
        }
        $user_maj = $this->setData($request,$id);

        $msg="Le compte de l'utilisateur ".$user_maj->NomComplet." a été mis à jour";
        return Redirect::to('/users')->with('success', $msg); 
    }
 
    public function show($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("consulter utilisateurs")) return Redirect::route('home');
        return $this->edit($id,"show");
    }

    public function destroy($id)
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        if(!$user->hasRole('ADMINISTRATEUR')) if(!$user->can("supprimer utilisateurs")) return Redirect::route('home');

        $user=User::find($id);
        $nom=$user->NomComplet;
        if(count($user->getRoleNames())>0)  return Redirect::to('/users');;
        if($user->hasAnyDirectPermission()) return Redirect::to('/users');;
        User::destroy($id);
        
        $msg="Le compte de l'utilisateur ".$nom." a été supprimé";
        return Redirect::to('/users')->with('success', $msg); 
    }
 

    public function setData($request,$id="") 
    {
        if($id) $user_maj = User::find($id);
        else $user_maj = new User;

        $user_maj->name = strtoUpper($request->name);
        $user_maj->email      = strtolower($request->email);
        $user_maj->actif = ($request->actif=='')?0:1;
        $user_maj->enseignant = $request->enseignant;
        $user_maj->change_pwd = ($request->change_pwd=='')?0:1;
        if($id) {
            $old_password=$user_maj->password;
            if($request->password=='') $user_maj->password=$old_password;
            else $user_maj->password   = Hash::make($request->password);
        }
        else $user_maj->password   = Hash::make($request->password);   
        $user_maj->save();

        //Attache les rôles
        $t_users_role = $request->users_role;
        if($id) {
            //Détache les anciens rôles
            $roles=$user_maj->getRoleNames();
            foreach($roles as $role) $user_maj->removeRole($role);   
        }
        if($t_users_role) $user_maj->assignRole($t_users_role);

        return $user_maj;
    }

     /* Reset passord */
    public function resetpassword()
    { 
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        return View::make('auth.reset', [ 'user' => $user,'message'=>'' ]);
    }


    /* Reset passord */
    public function postReset(Request $request)
    {   
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        $password=$request->password;
        $confirm_password=$request->password_confirmation;
        $t_error=array();

        if((count($t_error)==0) && (($password=="") || ($confirm_password=="")) ) {
            $t_error[0]='Le mot de passe doit être saisi dans les deux champs';
            return redirect()->back()->withInput()->withErrors($t_error);
        }
        if( (count($t_error)==0) && ($password!=$confirm_password) ) {
            $t_error[0]='Les mots de passe saisis ne sont pas identiques';
            return redirect()->back()->withInput()->withErrors($t_error);
        }
        if( (count($t_error)==0) && (strlen($password.$confirm_password)<8) ) {
            $t_error[0]="Les mots de passe doivents avoir au moins 8 caractères.";
            return redirect()->back()->withInput()->withErrors($t_error);
        } 

        $pattern = '/^(?=.*\d)(?=.*[@#\-_$%^&+=§!\?])(?=.*[a-z])(?=.*[A-Z])[0-9A-Za-z@#\-_$%^&+=§!\?]{8,12}$/';
        if( (count($t_error)==0) && (!preg_match($pattern,$password)) ) {
            $t_error[0]="Le mot de passe ne correspond pas aux critères indiqués.";
        }

        //Si erreur retour
        if (count($t_error)>0) {
            return redirect()->back()->withInput()->withErrors($t_error);
        }

        //Enregistrement
        $user = \Auth::user();
        $user->password = Hash::make($password);//bcrypt($password);
        $user->change_pwd = 0;//bcrypt($password);
        $user->save();
        Session::flash('nom_compte2', "Le nouveau mot de passe a été enregistré. Vous pouvez fermer la fenêtre");
        return redirect( '/home' );     
    }

}