<?php


namespace App\Http\Controllers\Administrator;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
use Gate;
use GuzzleHttp\Client;
use DataTables;
use App\PositionModel;
use App\ProvinceModel;
use App\VillageModel;
use App\DistrictModel;
use App\CommuneModel;
use Auth;
use App\Fun\Fun;
use Illuminate\Support\Facades\Crypt;
use Image;
use session;
use App\UserGroupModel;
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
 	function __construct()
    {
        $this->middleware('permission:User-List');
        $this->middleware('permission:User-Create', ['only' => ['create','store']]);
        $this->middleware('permission:User-Edit', ['only' => ['edit','update']]);
        $this->middleware('permission:User-Actived', ['only' => ['actived_users']]);
        $this->middleware('permission:User-Block-Item', ['only' => ['setup_user']]);
    }
    public function index(){
        
		return view('administrator.users.index');
    }
    public function datatable_get_users(){
       
        $users = User::leftjoin('nso007_position','nso007_position.id', '=', 'users.position_id')
        ->where('users.branch_id', \Branch::branch_id())
        ->where(function($query){
            $query->orwhere('users.user_status',0);
            $query->orwhere('users.user_status',1);
        })
        ->select(
            'nso007_position.name',
            'users.id',
            'users.block_permission',
            'users.user_firstname',
            'users.user_lastname',
            'users.email',
            'users.user_dob',
            'users.user_phone',
            'users.user_gender',
            'users.address',
            'users.user_status')->get();
        $arrayRole = [];
        foreach($users as $user){
            $roleName = $user->getRoleNames();
            array_push($arrayRole,$roleName);
        }
        // dd($arrayRole);
		return  Datatables::of($users)
            ->addIndexColumn()
            ->editColumn('action', function ($user) {
                $btn_edit ='';
                
                if(Gate::check('User-Edit')){
                    $btn_edit = '<a href="'.Route("users.edit",Crypt::encrypt($user->id)).'" class="button_success"><i class="fa fa-edit"></i></a>';
                }else{
                    $btn_edit = '';
                }
                if(Gate::check('User-Block-Item'))
                {
                    if(empty($user->block_permission)){
                        $btn_edit .= '<span data-id="'.Crypt::encrypt($user->id).'" class="btn-allow-block-item button_info" data-toggle="tooltip" data-placement="top" title="Allow to block Items"><i class="fa fa-lock" aria-hidden="true"></i>
                        <span>';
                    }else{
                        $btn_edit .= '<span data-id="'.Crypt::encrypt($user->id).'" class="btn-allow-block-item button_info" data-toggle="tooltip" data-placement="top" title="Allow to block Items"><i class="fa fa-unlock" aria-hidden="true"></i>
                        <span>';
                    }
                }
                return $btn_edit;
            })
            ->addColumn('status', function($user){
                $btn_edit ='';
                if(Gate::check('User-Actived')) {
                    if (Auth::user()->id !== $user->id) {
                        if ($user->user_status == 0) {
                            return ' <a style="color:red" href="#" class="viewPopLink" role="button" data-id="' . $user->id . '" data-status="' . $user->user_status . '" data-toggle="modal tooltip" data-target="#myModal" data-placement="top" title="Done"><span class="fa fa-check"></span> Disactive</a>';
                        } else {
                            return ' <a  href="#" class="viewPopLink" role="button" data-id="' . $user->id . '" data-status="' . $user->user_status . '"  data-toggle="modal tooltip" data-target="#myModal" data-placement="top" title="Done"><span class="fa fa-check"></span> Active</a>';
                        }
                    } else {
                        return ' <span class="fa fa-check"></span> Actived';
                    }
                }
            })
            ->editColumn('role',function($user){
                $roleName = $user->getRoleNames();
                if(!empty($roleName[0])){
                    return $roleName[0];
                }
                return "";
            })
            ->editColumn("user_dob",function($user){
                return date("d-m-Y",strtotime($user->user_dob));
            })
            ->editColumn('user_name', function(User $user) {
                $itisyou = '';
                if(Auth::user()->id == $user->id){$itisyou = '<span class="label label-success">It is you</span>';}
                return  $user->user_firstname .' '. $user->user_lastname .' '. $itisyou;
            })
            ->rawColumns(['status' => 'status','action' => 'action','user_name'=>'user_name','email'=>'email'])
            ->make(true);
    }

    public function org_chart(){
         $users = DB::select("SELECT 
            users.id,
            users.parent_id,
            users.name_en,
            users.avatar,
            nso007_type_of_staff.name as emp_position_type,
            nso007_position.name as position_title
            FROM `users` 
            INNER JOIN nso007_position ON nso007_position.id = users.position_id
        ");
        return view('administrator.users.chart',compact('users'));
    }


    /**
     * Show the form for creating a new resource.
     *
     * functin Genertator 
     */
 
    public function create(Request $request)
    {
    
        $positions = PositionModel::where('branch_id',\Branch::branch_id())->select(
			DB::raw('CONCAT(id," ",name) AS position_mixed'),'id')
            ->pluck('position_mixed','id')
            ->prepend('Please Select', '');
       
        $roles = Role::where('branch_id',\Branch::branch_id())
        ->pluck('name','name')
        ->all();

        return view('administrator.users.create',compact('roles','positions'));
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,$Digit = 4)
    {
		$user = new User;
		$this->validate($request, [
			
			'user_firstname' 	=> 'required',
			'user_lastname' 	=> 'required',
			'user_gender' 	=> 'required',
			'user_dob' 	=> 'required',
			'user_cardid' 	=> 'required',
			'user_phone' 	=> 'required',
			'user_reference' 	=> 'required',
            'position_id'   => 'required',
            'address'   => 'required',
			'email'     => 'required|email|max:255|unique:users,email',
            'password'  => 'required|same:confirm_password|string|min:8'
		
        ]);
		
		$user->user_firstname 	= $request->user_firstname;
		$user->user_lastname 	= $request->user_lastname;
		$user->user_gender 	= $request->user_gender;
		$user->user_dob 	= date('Y-m-d',strtotime($request->user_dob));
        $user->user_cardid 	= $request->user_cardid;
        
        if(isset($request->user_phone)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->user_phone, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }

            $user->user_phone      =  $phone_insert;
        }
        
		$user->user_reference 	= $request->user_reference;
        $user->position_id  = $request->position_id;
		$user->address 	= $request->address;
        $user->email        = $request->email;
		$user->branch_id 	    =\Branch::branch_id();
        $user->role     = 'Administrator';
        $user->user_activity     = 1;
        $user->user_status     = 1;

        $user->password = Hash::make($request['password']);

        $file       = $request->file('image');
        if($request->file('image')== null){
            $original_name = "none";
        }else{
            $original_name = $file->getClientOriginalName();
            $original_name = date('ymdhis').$original_name;
            $destinationPath = 'assets/images/resize';
            $thum = Image::make($file->getRealPath())->resize(150, 150);
            $thum->save($destinationPath.'/'.$original_name,80);
          
        }

        $user->avatar  = $original_name;

		$user->save();
		$user->assignRole($request->input('roles'));
		
        \LogActivity::addToLog('User created successfully!');
        return redirect()->route('users.index')
                        ->with('success','User created successfully!');
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return view('administrator.users.show');
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        
         $decrypt_id = Crypt::decrypt($id);
        $user = User::find($decrypt_id);

        $positions = PositionModel::where('branch_id',\Branch::branch_id())->select(
			DB::raw('CONCAT(id," ",name) AS position_mixed'),'id')
            ->pluck('position_mixed','id')
            ->prepend('Please Select', '');
       
       
        $roles = Role::where('branch_id',\Branch::branch_id())->pluck('name','name')->all();
        return view('administrator.users.edit',compact('roles','user','positions'));
    }

	public function update(Request $request, $id)
    {
		$user = User::find($id);
        $this->validate($request, [
            'user_firstname' 	=> 'required',
			'user_lastname' 	=> 'required',
			'user_gender' 	=> 'required',
			'user_dob' 	=> 'required',
			'user_cardid' 	=> 'required',
			'user_phone' 	=> 'required',
			'user_reference' 	=> 'required',
			'position_id' 	=> 'required',
            'address'   => 'required',
			'email'     => 'required|email|max:255|unique:users,email,'.$id,

        ]);
        $oldImage = $request->hidden_image_name;
        if($request->file('image') == null){
            $file_name = $oldImage;
        }else{
            $newfile = $request->file('image');
            $file_name = $newfile->getClientOriginalName();
            if(file_exists(public_path().'/assets/images/resize'.$oldImage)){
                unlink(public_path().'/assets/images/resize'.$oldImage);
            }
            $file_name     = date('his'). $file_name ;
            $destinationPath = 'assets/images/resize';
            $get_img = Image::make($newfile->getRealPath())->resize(150, 150);
            $get_img->save($destinationPath.'/'.$file_name);
        }
        $user->avatar     = $file_name;
		$user->user_firstname 	= $request->user_firstname;
		$user->user_lastname 	= $request->user_lastname;
		$user->user_gender 	= $request->user_gender;
		$user->user_dob 	= date('Y-m-d',strtotime($request->user_dob));
		$user->user_cardid 	= $request->user_cardid;
		if(isset($request->user_phone)){
            $phone="";$phone_insert="";
            preg_match_all('!\d+!', $request->user_phone, $phone);
            foreach($phone[0] as $key=>$value)
            {
                if($key==0) $phone_insert.=$value;
                else $phone_insert.="-".$value;
            }

            $user->user_phone      =  $phone_insert;
        }
		$user->user_reference 	= $request->user_reference;
        $user->position_id  = $request->position_id;
        $user->address  = $request->address;
        $user->email 	= $request->email;
        $user->branch_id        = \Branch::branch_id();
        $user->role     = 'Administrator';
        $user->user_activity 	= 1;



        $input = $request->all();
        if(!empty($input['password'])){
            $input['password'] = Hash::make($input['password']);
        }else{
            $input = array_except($input,array('password'));
        }
        $user->update($input);

        DB::table('model_has_roles')->where('model_id',$id)->delete();
		$user->assignRole($request->input('roles'));
        \LogActivity::addToLog('User updated successfully!');
        return redirect()->route('users.index')
                        ->with('success','User updated successfully');
    }

    public function destroy(Request $request,$id)
    {
        $status = $request->status;
        $change_status = 0;
        if($status == 0){
            $change_status = 1;
        }else{
            $change_status = 0;
        }
        DB::table('users')->where('id',$id)->update(['user_status' =>$change_status ]);
        return response()->json([
            'success' => 'Record deleted successfully!'
        ]);
    }
    public function block_allowance($code){
        $id = Crypt::decrypt($code);
        $user = User::find($id);
        if($user->block_permission==1){
            $user->block_permission = null;
        }else{
            $user->block_permission = 1;
        }
        $user->save();
        return back()->with('success','User Accessibility was updated successfully');
    }

    public function delete_users(Request $request, $id){
        $status = $request->status;
        $change_status = 0;
        if($status == 0){
            $change_status = 1;
        }else{
            $change_status = 0;
        }
        DB::table('users')
            ->where('id',$id)
            ->update(['user_status'=> $change_status]);
        \LogActivity::addToLog('Disactived user successfully!');
        return redirect()->back();
    }
    public function setup_user($id){
        if($id>0){
            $user = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
                ->where('id',$id)->pluck('name','id')->prepend('Please select', '');
        }else{
            $user = User::select(DB::raw('CONCAT(user_firstname," ",user_lastname) AS name'), 'id')
                ->where('group_id',null)->pluck('name','id')->prepend('Please select', '');
        }
        $group = UserGroupModel::pluck('group_name','id')->all();
        return view('administrator.users.setup_user',compact('user','group','id'));
    }
    public function datatable_user(Request $request){
        $data = User::where('group_id','!=',null)->get();
        if ($request->isMethod('get')) {

            return DataTables::of($data)
                ->editColumn('agent_id',function ($data){
                    return $data->user_firstname.' '.$data->user_lastname;
                })
                ->editColumn('group_id',function ($data){
                    return optional($data->group)->group_name;
                })
                ->editColumn('department_id',function ($data){
                    return optional($data->department)->department_name;
                })
                ->editColumn('leader_id',function ($data){
                    if($data->leader_id){
                        $pr = User::find($data->leader_id);
                        return $pr->user_firstname.' '.$pr->user_lastname;
                    }else{
                        $pr = User::find($data->id);
                        $gr = UserGroupModel::where('leader_group_id',$pr->id)->first();
                        if($gr){
                            if($gr->leader_group_id){
                                return '<label class="label label-success">Leader</label>';
                            }else{
                                return '<label class="label label-danger">N/A</label>';
                            }
                        }else{
                            return '<label class="label label-danger">N/A</label>';
                        }
                    }

                })
                ->addColumn('action', function ($data) {
                    $check_language = Fun::lang();
                    if ($check_language == 'km') {
                        $delete = "ចាកចេញពីក្រុម";
                    } else {
                        $delete = "Leave Group";
                    }
                    if(Gate::check('User-Group-Delete')){
                        return '<button type="button" class="button_danger delete_products" data-toggle="modal" data-id="' . $data->id . '" > ' . $delete . ' </button>';
                    }
                    return '';
                })
                ->addIndexColumn()
                ->rawColumns(['action' => 'action','leader_id'=>'leader_id'])
                ->make(true);
        }
    }
    public function setup_user_store(Request $request){

        $user = User::find($request->user);
        $user->group_id = $request->group;
        $dep = '';
        $g = UserGroupModel::find($request->group);
        $g_ld = UserGroupModel::where('leader_group_id',$g->leader_group_id)->first();
        $dep = $g->department_id;
        $user->department_id = $dep;
        if($request->position == 'leader'){

            $user->role = 'Leader';
            $g->leader_group_id = $user->id;
            $set_id = User::where('group_id',$request->group)->get();

            if($set_id->count()>0){
                foreach ($set_id as $item) {
                    $item->leader_id = $user->id;
                    $item->update();
                }
            }
        }else{
            $user->leader_id = $g_ld->leader_group_id;
            $user->role = 'Staff';
        }
        if($user->update()){
            $g->update();
        }
        return redirect()->route('user.setup-user',0)->with('success','Setup group for user successfully...');
    }
    public function get_leader(){
        $get_leader = UserGroupModel::find($_GET['id']);
        echo json_encode($get_leader);
    }
    public function delete_setup_group(Request $request){
        $user = User::find($request->id);
        $u = $user->group_id;
        $user->group_id  = null;
        $user->department_id  = null;
        if($user->role == 'Leader'){
            $clearuser = User::where('leader_id',$request->id)->get();
            foreach ($clearuser as $item){
                $u_id = $item->id?$item->id:'';
                $user_ld = User::find($u_id);
                $user_ld->leader_id = null;
                $user_ld->update();
            }
            $group = UserGroupModel::find($u);
            if($group->leader_group_id){
                $group ->leader_group_id = null;
                $group->update();
            }
        }
        $user->update();
    }

    public function staff_chart()
    {
        $data = User::all();
        return view('administrator.users.chart',compact('data'));
    }
}