<?php namespace App\Http\Controllers;

use Auth\AuthController;
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;
use App\Http\Controllers\Logs;
//use SimpleSoftwareIO\QrCode\Facades\QrCode;
//use BaconQrCode\QrCode\Facades\QrCode;

class UsersController extends Controller {
 
    /**
     * Display a listing of the user.
     *
     * @return Response
     */
    public function index()
    {
        $user_actif=User::where('id','=',Session::get('id'))->first();
        $users = User::all();


        if($user_actif->SysAdmin) {
            $users = User::all();
        }
        else {
            $users = User::where('login','<>','admin')->get();
        }
        return View::make('acces.users.index', 
            ['users' => $users,'user_actif'=>$user_actif,'user'=>$user_actif]);
    }
 

     public function show($id)
    {
        $user_actif=User::where('id','=',Session::get('id'))->first();
        $user = User::find($id);
        $liste_roles=Role2::pluck("name", "id")->toArray();
        return View::make('acces.users.show', [ 'user' => $user,'user_actif'=>$user_actif , 
            'liste_roles' => $liste_roles]);
    }


    /**
     * Show the form for creating a new user.
     *
     * @return Response
     */
    public function create()
    {
        return View::make('acces.users.create');
    }
 
    /**
     * Store a newly created user in storage.
     *
     * @return Response
     */
    public function store(UserRequest $request)
    {
        $user = new User;
 
        $user->prenom = ucfirst ($request->prenom);
        $user->nom  = strtoupper($request->nom);
        $user->login   = strtolower($request->login);
        $user->email      = strtolower($request->email);
        $user->password   = Hash::make($request->password);
 
        $user->save();
        //LOG de la transaction
        $user->log_transaction($request->url(),'I');
        
        return Redirect::to('/acces/users');
    }
 
    /**
     * Show the form for editing the specified user.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $user = User::find($id);
        if(!$user) return Redirect::route( 'login' );

        $liste_roles=Role2::pluck("name", "id")->toArray();
        $user_sel = User::find($id);
        $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.edit', [ 
            'user' => $user , 'user_sel' => $user_sel ,
            't_getroles' => $t_getroles, 
            'liste_roles' => $liste_roles]);
    }
 
    /**
     * Update the specified user in storage.
     *
     * @param  int  $id
     * @return Response
     */
    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!='');
        if($change_pwd) {
            $v = Validator::make($request->all(), [
                'password' => 'required|min:5',
                //'password_confirmation' => 'required|min:3|same:password',
            ]);
            if ($v->fails())
                return redirect()->back()->withErrors($v->errors());
            $user_maj->password   = Hash::make($request->password);
        }
        $user_maj->prenom = ucfirst ($request->prenom);
        $user_maj->nom  = strtoupper($request->nom);
        $user_maj->login   = strtolower($request->login);
        $user_maj->email      = strtolower($request->email);
        $user_maj->change_pwd = ($request->change_pwd=='')?0:1;
        $user_maj->save();

        //LOG de la transaction
        $user_maj->log_transaction($request->url(),'U');

        //Attach rôles
        $t_users_role = $request->users_role;

        //Détache les anciens rôles
        $roles=$user_maj->getRoleNames();
        foreach($roles as $role) $user_maj->removeRole($role);
        $user_maj->assignRole($t_users_role);

        //LOG
        $values="";
        foreach($t_users_role as $role) $values.=(($values=="")?"":",").$role;
        $log=new Logs;
        $log->addlog(['url'=>$request->url(),'table'=>'role_user' ,'operation'=>'I','values'=>$role]);

        //Détache les anciens rôles
        /*
        DB::table('role_user')->where('user_id', '=', $user->id)->delete();
        if($t_users_role) {
            //Attache les nouveaux
            foreach($t_users_role as $role_id) {
                $role = Role2::find($role_id);
                $user->attachRole( $role );
                //LOG de la transaction
                $log=new Logs;
                $values="user_id=>".$user->id.";role_id=>".$role_id;
                $log->addlog(['url'=>$request->url(),'table'=>'role_user' ,'operation'=>'I','values'=>$values]);
            }
        }
        */




        return Redirect::to('/acces/users');
    }
 
    /**
     * Remove the specified user from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $user_actif=User::where('id','=',Session::get('id'))->first();
        $user=User::find($id);
        if( ($user_actif->can("USR_SUP") || $user_actif->hasrole("ADMINISTRATEUR")) 
            &&
            (!$user->hasrole("ADMINISTRATEUR")) 
            && ($user->getroles()=="")
        )
        {           
            User::destroy($id);
            //LOG de la transaction
            $user_actif->log_transaction('','D');
        }
 
        return Redirect::to('/acces/users');
    }
 
     /* Reset passord */
    public function resetpassword()
    { 
        $user=Auth\AuthController::getUserCnx(); 
        return View::make('auth.reset', [ 'user' => $user,'message'=>'' ]);
    }


    /* Reset passord */
    public function postReset(Request $request)
    {   

        $user=Auth\AuthController::getUserCnx();
        $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('nom_compte2', "Le nouveau mot de passe a été enregistré. Vous pouvez fermer la fenêtre");
        return redirect( '/accueil' );     
    }

    /* Change PWD passord */
    public function change_pwd()
    {   
        $user=Auth\AuthController::getUserCnx(); 
        return View::make('auth.reset', [ 'user' => $user,'message'=>'' ]);
    }

    /* QRCode */
    /*
    public function QRCode()
    { 
        $cle="lma3cwxfngfylpab3ucepgivluzccaobkwzteqxhn3474dm6dvn6fik2";

        $image=url("/img/logo_mini.png");
        $image="http://127.0.0.1/sysinfo/sipre/public/img/logo_mini.png";

        $qrcode = new QrCode;
        return $qrcode->size(300)->generate($cle);

        $qrcode->color(255,0,255);
        $qrcode->backgroundColor(255,255,0);

        //QrCode::format('png')->merge($image);
        //QrCode::format('png')->mergeString(Storage::get($image), .3)->generate();

        return $qrcode->size(300)->generate($cle);

        return QrCode::format('png')
                ->merge('http://127.0.0.1/sysinfo/sipre/public/img/logo_mini.png',
                 .3, 
                 true)
                ->generate();
        dd('e');
        //return QrCode::format('png')->merge($image,.3,true)->generate();
        //return QrCode::size(300)->generate($cle);
    }
    */

    /* QRCode */
    /*
    public function QRCodeIdentification()
    { 
        return QrCode::size(300)->generate('http:\\sipre.cpswf.wf\identQR');
    }
    */


}