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

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' );
        $users = User::all();

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

    public function create($mode="create",$id="")
    {
        if(!($user_actif=Auth::user())) return Redirect::route( 'login' );
        $liste_roles=Role2::pluck("name", "id")->toArray();

        $user_sel ="";$t_getroles=[];
        if($id) {
            $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.'.$mode, [
                'user' => $user_actif , 'user_sel' => $user_sel ,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,'mode' => $mode,
                '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->prenom = ucfirst ($request->prenom);
        $user_maj->nom  = strtoupper($request->nom);
        $user_maj->login   = strtolower($request->login);
        $user_maj->email      = strtolower($request->email);
        $user_maj->fonction      = strtoupper($request->fonction);
        $user_maj->change_pwd = (!$request->change_pwd)?0:1;
        $user_maj->actif = (!$request->actif)?0:1;
        $user_maj->save();
        //LOG de la transaction
        $user_actif->log_transaction($request->url(),(!$id)?'I':'U');

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

        //LOG
        $values="";
        if($t_users_role) {
            foreach($t_users_role as $role) $values.=(($values=="")?"":",").$role;
            $log=new Logs;
            $log->addlog(['url'=>$request->url(),'table'=>'role_user' ,'operation'=>'I','values'=>$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' );
        $user_sel=User::find($id);
        if($user_sel->IsSupprimable ) {
            User::destroy($id);
            //LOG de la transaction
            $user_actif->log_transaction('','D');
        }
        return Redirect::to('/users');
    }

     /* Reset passord */
    public function resetpassword()
    {
        if(!($user=Auth::user())) return Redirect::route( 'login' );
        return View::make('auth.reset', [
            'user' => $user,'menu' => $this->menu,'submenu' => $this->submenu,'menu_home' => $this->menu_home,
            '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' );
    }

    /* 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');
    }
    */


}
