<?php namespace App\Http\Controllers;

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


class UsersController extends Controller {
    private $menu='acces';
    private $submenu='users';
    private $menu_home="acces";

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

        $users = User::all();

        if($user_actif->SysAdmin) $users = User::all();
        else $users = User::where('name','<>','ADMINISTRATEUR')->get();
        return View::make('acces.users.index',
            [
                'users' => $users,'menu_home' => $this->menu_home,'user' => $user_actif,'menu' => $this->menu,'submenu' => $this->submenu,
                'user_actif'=>$user_actif
            ]);
    }

    public function create($mode="create",$id="")
    {
        if(!($user_actif=Auth::user())) return Redirect::route( 'login' );
        if($mode=="create") if(!$user_actif->hasRole('ADMINISTRATEUR')) if(!$user_actif->can("USR_AJO")) return redirect('home');
        if($mode=="edit") if(!$user_actif->hasRole('ADMINISTRATEUR')) if(!$user_actif->can("USR_MAJ")) return redirect('home');
        if($mode=="show") if(!$user_actif->hasRole('ADMINISTRATEUR')) if(!$user_actif->can("USR_VISU")) return redirect('home');


        $liste_roles=Role2::pluck("name", "id")->toArray();

        $user_sel ="";$t_getroles=[];
        if($id) {
            $user_sel = User::find($id);
            $t_getroles=$user_sel->getRoleNames()->toArray();
        }

        return View::make('acces.users.'.$mode, [
                'menu_home' => $this->menu_home,'user' => $user_actif,'menu' => $this->menu,'submenu' => $this->submenu,'mode' => $mode,
                'user_sel' => $user_sel,
                't_getroles' => $t_getroles,
                'liste_roles' => $liste_roles]);
    }


    public function store(UserRequest $request)
    {
        $v = Validator::make($request->all(), [
            'password' => 'required|min:5',
            //'password_confirmation' => 'required|min:3|same:password',
        ]);
        if ($v->fails()) return Redirect::back()->withInput()->withErrors($v->errors());
        $user_maj = $this->setData($request,Hash::make($request->password));

        return Redirect::to('/users');
    }


    public function edit($id)
    {
        return $this->create("edit",$id);
    }


    public function update($id,UserRequest $request)
    {
        $user_maj = User::find($id);
        //Garde ancien mot de passe par defaut
        $old_password=$user_maj->password;
        $change_pwd=($request->password!='');
        $password="";
        if($change_pwd || !$id) {
            $v = Validator::make($request->all(), [
                'password' => 'required|min:5',
                //'password_confirmation' => 'required|min:3|same:password',
            ]);
            if ($v->fails()) return Redirect::back()->withInput()->withErrors($v->errors());
            $password   = Hash::make($request->password);
        }
        $user_maj = $this->setData($request,$password,$id);
        return Redirect::to('/users');
    }


    public function setData($request,$password,$id="")
    {
        if(!($user_actif=Auth::user())) return Redirect::route( 'login' );

        if($id) $user_maj = User::find($id);
        else  $user_maj = new User;
        if($password) $user_maj->password   = $password;
        $user_maj->name  = strtoupper($request->name);
        $user_maj->email      = strtolower($request->email);
        $user_maj->change_pwd = (!$request->change_pwd)?0:1;
        $user_maj->actif = (!$request->actif)?0:1;
        $user_maj->save();

        //Attache & Détache les anciens rôles
        $t_users_role = $request->users_role;

        $user_maj->syncRoles($t_users_role);

        return $user_maj;
    }

    public function show($id)
    {
        return $this->create("show",$id);
    }


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

        $user_sel=User::find($id);
        User::destroy($id);
        return Redirect::to('/users');
    }

     /* 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';
        }
        if( (count($t_error)==0) && ($password!=$confirm_password) ) {
            $t_error[0]='Les mots de passe saisis ne sont pas identiques';
        }
        if( (count($t_error)==0) && (strlen($password.$confirm_password)<8) ) {
            $t_error[0]="Les mots de passe doivents avoir au moins 8 caractères.";
        }

        $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('message', "Le nouveau mot de passe a été enregistré. Il devra être utilisé lors de la prochaine connexion");
        return redirect( '/home' );
    }


}
