<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Userdetail;
use App\Service\CreateuserService;
use Auth;
use App\Models\UserMobile;
use Hash;
use App\Service\AddressService;
use App\Service\MobileService;
use App\Service\ProfileImageService;
use Validator;
use App\Service\IdProofService;
use App\Service\ProfileService;
use App\Service\OpeningLedgerService;
use App\Service\NewCompanyService;
use Log;

class ProfileController extends Controller
{
    public function updateprofile(Request $request){
        $user = $request->user();
        if($user['email']==null){
            if(isset($request['email'])==0){
                $user['email']=$request['email'];
            }
        }
        
        if($user['adhar']==0 && isset($request['adhar'])){
            $user['adhar']=$request['adhar'];
        }
       
        if(isset($request['password'])){
            $user['password']=Hash::make($request['password']);
            $user['cpassword']=$request['password'];
        }
		$keys = ['name'];
		foreach($keys as $k){
			if(isset($request[$k])){
				$user[$k]=$request[$k];
			}
		}
		$user->update();
        $response = [
			'access_token'=>null,
			'user'=>null,
			'success' => false,
			'message' => '',
			'redirect'=>''
		];
        $user = User::where('id',$user['id'])->first();
        $accessToken = $user->createToken('my-app-token')->plainTextToken;
		$redirect='';
		$response = [
				'access_token'=>$accessToken,
				'user'=>$user,
				'success' => true,
				'message' => '',
				'redirect'=>$redirect
		];
    	return response()->json($response);
    }

    // Function to get logged in user by token
    public function getuser(Request $request){
        $user = $request->user();
        $response = [
            'user'=>null,
            'success' => true,
            'message' => ''
        ];
        if($user!=null){
            // getting user details and access token from the database.
            $service = new ProfileService;
            $user = $service->getuser($user['id']);
            $response = [
                'user'=>$user,
                'success' => true,
                'message' => ''
            ];
        }
        return response()->json($response);
    }

    public function updateProfileByAdmin(Request $request){
        $loggedinuser = $request->user();
        //if id does not comes and user has to change the password of himself
        if($loggedinuser==null){
            $loggedinuser=Auth::user();
        }
        if($request['id']>0){//need to check if authenticated user has the access to update other profile

            try{
                
                $user = User::findOrFail($request['id']);

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                // Return error message in JSON if ID not found
                return response()->json(['message' => 'Invalid Id to update '], 404);
            }

        } else {
            if($request['id']==0){
                //if user is new
                $user = null;
            } else {
                $user = User::where('id',$loggedinuser['id'])->first();
            }
        }
        // $errorres = $this->validaterequest($user,$request,$loggedinuser);
        
        if(isset($request['password'])){
            $user['password']=Hash::make($request['password']);
            $user['cpassword']=$request['password'];
        } 
        if(isset($request['username'])){
            $user['username']=$request['username'];
            //$user['vpass']=Hash::make($request['password']);
        }
    
        if(isset($request['email'])){
            $user['email']=$request['email'];
            //$user['vpass']=Hash::make($request['password']);
        }
    
		$keys = ['firstname','lastname','name','mobileno','state','city',
                'occuption','zipcode','photo','address','issupplier',
                'isagent','iscustomer','isuser'];
		foreach($keys as $k){
			if(isset($request[$k])){
				$user[$k]=$request[$k];
			}
		}
        $profileservice = new ProfileService;
        if($user!=null && isset($user['id']) && $user['id']>0){
            if($user['role']>2){
                $user=$profileservice->createupdateProfile($user,$request);
		        $user->update();
            } 
        }
        else{
            $user = User::create($user);
            $user['cpassword']=$request['password'];
            
            $user=$profileservice->createupdateProfile($user,$request);
            $user->update();
        }
        if(isset($request['mobiles'])){
            $service= new MobileService;
            $service->updateMobile($user,$request['mobiles']);
        }
        $user = $profileservice->getuser($user['id']);
        
        $response = [
			'user'=>$user,
			'success' => true,
			'message' => '',
			'redirect'=>''
		];
    	return response()->json($response);
    }
    
    

    public function validaterequest($user,$request,$loggedinuser){
        
        $response['status']=true;
        if(isset($user['id']) && $user['id']>0){
            //need to check if aadhar is changed or not
            $validator = Validator::make($request->all(), [
            ]);
            if(isset($request['email'])){
                $foundemail = User::where('email',$request['email'])->where('companyid',$loggedinuser['companyid'])->where('id','<>',$user['id'])->first();
                if($foundemail!=null){
                    if($foundemail['email']==null){
                    
                    }else{
                        $validator->errors()->add('email', 'Email Id already exist');
                        $response['status']=false;
                    }
                }
            }
            if(isset($request['username'])){
                $foundemail = User::where('username',$request['username'])->where('companyid',$loggedinuser['companyid'])->where('id','<>',$user['id'])->first();
                
                if($foundemail!=null){
                    if($foundemail['username']==null){
                    
                    }else{
                        $validator->errors()->add('username', 'UserId already exist');
                        $response['status']=false;
                    }
                }
            }
            $response['errors']=$validator->errors();
        } else {
            //need to check if aadhar, email exist or not
            $validator = Validator::make($request->all(), [
            ]);
            if(isset($request['username'])){
                $foundemail = User::where('username',$request['username'])->where('companyid',$loggedinuser['companyid'])->first();
                if($foundemail!=null){
                    if($foundemail['username']==null){
                    
                    }else{
                        $validator->errors()->add('username', 'UserId already exist');
                        $response['status']=false;
                    }
                }
            }
            if(isset($request['email'])){
                $foundemail = User::where('email',$request['email'])->where('companyid',$loggedinuser['companyid'])->first();
                if($foundemail!=null){
                    if($foundemail['email']==null){
                    
                    }else{
                        $validator->errors()->add('email', 'Email Id already exist');
                        $response['status']=false;
                    }
                }
            }
            // $foundgst=User::where('gst',$request['gst'])->where('companyid',$loggedinuser['companyid'])->first();
            // if($foundgst!=null){
            //     if($foundgst['gst']==null || $foundgst['gst']==0){
                    
            //     }else{
            //     $validator->errors()->add('gst', 'GST number already exist');
            //     $response['status']=false;
            //     }
            // }
            if(isset($request['adhar'])){
                $foundadhar=User::where('adhar',$request['adhar'])->where('companyid',$loggedinuser['companyid']);
                if(isset($request['isparty']) && $request['isparty']==1){
                    $foundadhar->where('isparty',1);
                } else if(isset($request['iscustomer']) && $request['iscustomer']==1){
                    $foundadhar->where('iscustomer',1);
                } else if(isset($request['isemployee']) && $request['isemployee']==1){
                    $foundadhar->where('isemployee',1);
                }
            
                $foundadhar=$foundadhar->first();
                if($foundadhar!=null){
                    if($foundadhar['adhar']==null){

                    }else{
                    $validator->errors()->add('adhar', 'Adhar number already exist');
                    $response['status']=false;
                    }
                }
            }
            /*if($validator->fails()){
                //if mobile has prefix + then match the complete mobile
                $response['status']=false;
            }*/
            $response['errors']=$validator->errors();
        }
        return $response;
    }
}
