<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use Validator;
use App\Models\CompanyModel;
use App\Models\Role;
class UsersController extends Controller
{
    public function index(){

        $data['title'] = "User management";
        $data['all'] = User::orderBy('utype')->get();
        $data['client_list']=CompanyModel::where('status',2)->get();
        $data['roles']=Role::orderBy('name','ASC')->get();
        return view('admin.users',$data);

        /*
        1=Created;
        2=in process;
        3=Completed;
        4=checking;
        5=bugfixing;
        5=done;
        */
    }

    public function add_user(Request $req){

        $name = $req->name;
        $email = $req->email;
        $mob = $req->mob;
        $address = $req->address;
        $company = $req->company;
        $website = $req->website;
        $user_type = $req->user_type;
        $password = bcrypt($req->password);

        $sav = new User;
        $sav->employee_id=  $req->e_id;
        $sav->designation=  $req->designation;
        $sav->name = $name;
        $sav->email = $email;
        $sav->mob = $mob;
        $sav->address = $address;
        $sav->company = $company;
        $sav->website = $website;
        $sav->utype = $user_type;
        $sav->password = $password;
        $sav->active = 1;
        $sav->save();
        if (!empty($req->input('role'))) {
            $sav->attachRole($req->role);
        }

        return redirect()->back()->with('msg','Data saved !!');

    }
    public function user_active($id)
    {
        $user = User::find($id);
        if($user->active == 0){
            $user->active = 1;
            $status = 'published';
        }else{
            $user->active = 0;
            $status = 'unpublished';
        }
        $user->update();
        return back();

    }

    public function change_user_pass(Request $req){

        $id = $req->user_id;
        $password = $req->password;

        $data = [
            'password' => $req->password,
            'password_confirmation' => $req->password_confirmation,
        ];

        $validator = Validator::make($data, [
            'password' => 'required|min:6|confirmed',
        ]);

        if($validator->fails()){
            return redirect()->back()->with('msg','Operation failed');
        }
        else{
            $sav = User::find($id);
            $sav->password = bcrypt($password);
            $sav->save();

            return redirect()->back()->with('msg','Password changed successfully !');
        }
    }
}
