<?php
namespace App\Http\Controllers;

use App\Http\Controllers\MainController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; 
use App\Models\Users\AccessTokensModel;
use App\Models\Users\UsersModel;
use App\Models\Users\PeoplesModel;
use App\Models\Users\CustomersAddressModel;
use App\Models\Users\CustomersModel;
use App\Services\CustomersService;

class UsersController extends MainController{
	public $customersSrv;	 
	public function __construct(
	  CustomersService $customersSrv
	){
	  $this->customersSrv = $customersSrv;
	}
	/*
		GETS THE LIST OF ORDERS IF HAS CUSTOMER OR NOT
	*/
	public function login(Request $request){
		$json = []; $status = 200; $error = "";

		$user = UsersModel::where('username', $request->email);

		if(!$request->third_party_signin_token)
			$user = $user->where('password', (md5($request->password)));
				
		$user = $user->first();
		//echo str_replace_array('?',$user->getBindings(),$user->toSql());
		if($user){
			if($request->sign_in_as && $request->sign_in_as == 'store'){
				if($user->is_cashier == 0){
					$error = "You have no access.";
				}
			}
			else if($request->sign_in_as && $request->sign_in_as == 'rider'){
				if($user->is_rider == 0){
					$error = "You have no access.";
				}
			}
			else if($request->sign_in_as && $request->sign_in_as == 'user'){
				if($user->is_shopper == 0){
					$error = "You have no access.";
				}
			}
			

			if($error == ""){
				$get_token = AccessTokensModel::where('employee_id',$user->id)
				->where(function($query){
					$query->whereNull('expires_at');
					$query->orWhereRaw('expires_at <= NOW()');
				})
				->where('revoked',0)
				->orderBy('created_at','desc')
				->first();

				if($get_token && isset($get_token->id) && $get_token->id){
					$api_key = $get_token->id;
				}
				else{			
					$api_key = base64_encode(str_random(40));
					$token = AccessTokensModel::insert(['id'=>$api_key,'employee_id'=>$user->id,'created_at'=>DB::raw('NOW()')]);
				}
				
				#SET USER ROLES
				$roles = [];
				if($user->is_cashier)
					$roles[] = 'cashier';

				if($user->is_shopper){
					$roles[] = 'customer';
					$customer = $this->customersSrv->getCustomer($user->person_id,true);
					// echo "<pre>",print_r($customer),"</pre>";die();
					$json['customer_details'] = $customer;
				}

				if($user->is_rider)
					$roles[] = 'rider';

				$json['key'] = $api_key;
				$json['roles'] = $roles;
				$json['user'] = $user;
			}
		} else {
			$error = "Wrong email or password";
		}		

		return $this->apiResponse($json,$status,$error);
	}
	public function userRegister(Request $request){
		$json =[];$status = 200;$error = "";
		$no_account = true;
		$no_account_details = "";
		$details = json_decode($request->details);
		$user = UsersModel::with(['customer_details'])->where('username',$details->email)->first();
		if($user){
			$verified = $user->is_verified;
			$user_status = $user->customer_details->deleted;
			$no_account = false;
		}else{
			$verified = "";
			$user_status = "";
			$no_account = true;
		}
		$json['user'] = $user;
		$json['no_account'] = $no_account;
		$json['verified'] = $verified;
		$json['user_status'] = $user_status;
		$json['no_account_details'] = $no_account_details;
		return $this->apiResponse($json,$status,$error);
	}
	public function userGuest(Request $request){
		$json =[];$status = 200;$error = "";
		$no_account = true;
		$no_account_details = "";
		$details = json_decode($request->details);
		$user = UsersModel::with(['customer_details'])->where('username',$details->email)->first();
		$no_account_details = "Email address is already registered.";
		if(isset($user)){
			if($user->is_verified == 1 && $user->customer_details->deleted != 1){
				$no_account = false;
			}
			if($user->customer_details->deleted != 1 ){
				$no_account = false;
			}else{
				$no_account = true;
			}
			if($user->is_verified  == 0 && $user->customer_details->deleted== 0){
				$no_account = true;	
			}
		}else{
			$no_account = true;
		}
		// $people = PeoplesModel::where('phone_number',$details->phone)->first();
		// if($people){
		// 	$no_account = false;
		// 	$no_account_details = "Mobile Number is already registered.";
		// }
		// echo "<pre>",print_r($people),"</pre>";die();
		// $json['is_valid'] = !empty($user) ? $user->is_verified: 0;
		// $json['customer_status'] = !empty($user) ? $user->customer_details->deleted : 0;
		$json['no_account'] = $no_account;
		$json['no_account_details'] = $no_account_details;
		return $this->apiResponse($json,$status,$error);
	}
	public function changePassCheck(Request $request){
		$json =[];$status = 200;$error = "";
		$no_account = false;
		$no_account_details = "";
		$details = json_decode($request->details);
		$user = UsersModel::where('username',$details->email)->first();
		if($user){
			$json['user'] = $user;
		}else{
			$no_account = true;
			$no_account_details = "Account not found.";
		}
		$json['no_account'] = $no_account;
		$json['no_account_details'] = $no_account_details;

		return $this->apiResponse($json,$status,$error);
	}
	public function changePass(Request $request){
		$json =[];$status = 200;$error = "";
		$no_account = false;
		$no_account_details = "";
		$details = json_decode($request->details);
		$token_status = $this->customersSrv->verifyTokenPassword($details,$request->token);
		if($token_status){
			$json['verification_status'] = "success";
		}else{
			$json['verification_status'] = "Token is expired, do you want to resend verification email?.";
		}
		return $this->apiResponse($json,$status,$error);
	}
	public function addressCheck(Request $request){
		$json =[];$status = 200;$error = "";
		$no_address = true;
		$address_error = "";
		$user = $request->user;

		if($user){
			$details = json_decode($request->details);
			$customer_details = CustomersModel::where('person_id',$details->user_id)->first();
			$customer_address = CustomersAddressModel::where('customer_id',$customer_details->id)->where('lat',$details->lat)->where('lng',$details->lng)->first();
			// echo "<pre>",print_r($customer_address),"</pre>";die();
			if($customer_address){
				$no_address = false;
				$address_error = "Address is already added.";
			}
		}
		else
			$error = "User not found.";
		// echo "<pre>",print_r($people),"</pre>";die();
		$json['no_address'] = $no_address;
		$json['address_error'] = $address_error;
		return $this->apiResponse($json,$status,$error);
	}
}
