<?php
namespace App\Services;
use Carbon\Carbon;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;

use App\Models\Users\UsersModel;
use App\Models\Users\CustomersModel;
// use App\Models\Users\CustomerDetailsModel;
use App\Models\Users\CustomersAddressModel;
use App\Models\Users\tokenModel;
use App\Models\Users\CustomersFavoritesModel;
use App\Models\Users\PeoplesModel;
use App\Models\Users\UserLogsModel;
use App\Models\Sales\SalesNotificationsModel;

class CustomersService {
	/*
	 *
	 * gets the user details
	 */
	public function getCustomer($id,$all_details=false){
		if(!$all_details){
			$person = UsersModel::where('person_id',$id)->first();
			if($person && $person->person_id)
				return CustomersModel::with(['login_details'])->where('person_id',$person->person_id)->first();
			else
				return false;
		}
		else{
			return UsersModel::with(['customer_details.customer_addresses','person_details'])
					->where('person_id',$id)->first();
		}
	}
	/*
	 *
	 * gets the temporary user details
	 */
	public function getTempCustomer($id,$details=array()){
		$customer = CustomersModel::where('temp_id',$id)->first();
		if(!$customer && !empty($details) ){ # IF TEMP CUSTOMER IS NOT FOUND CREATE NA NEW CUSTOMER
			$person = new PeoplesModel();
			$person->first_name = $details->first_name;
			$person->last_name = $details->last_name;
			$person->phone_number = (isset($details->phone) ? $details->phone : '');
			$person->email = (isset($details->email) ? $details->email : '');
			$person->address_1 = '';
			$person->address_2 = '';
			$person->city = '';
			$person->state = '';
			$person->zip = '';
			$person->country = '';
			$person->comments = '';
			$person->save();

			$customer = new CustomersModel();
			$customer->person_id = $person->person_id;
			$customer->temp_id = $id;
			$customer->company_name = $details->first_name." ".$details->last_name;
			$customer->taxable = 1;
			$customer->balance = 0;
			$customer->save();
		}
		return $customer;
	}

	/*
	 *
	 * gets the temporary user details
	 */
	public function addCustomer($details=array(),$temp_user=null){
		$person = new PeoplesModel();
		$person->first_name = $details->first_name;
		$person->last_name = $details->last_name;
		$person->email = $details->email;
		$person->phone_number = $details->phone;
		// echo var_dump($details->birthdate);die();
		if(isset($details->birthdate ))
			$person->birthdate = $details->birthdate;
		$person->address_1 = '';
		$person->address_2 = '';
		// if(isset($details->other ))
		// 	$person->address_2 = $details->other;
		// if(isset($details->work ))
		// 	$person->work_address = $details->work;
		$person->city = '';
		$person->state = '';
		$person->zip = '';
		$person->country = '';
		$person->comments = '';
		$person->save();

		$user_id = null;
		// echo var_dump($person->id && isset($details->email) && isset($details->password));
		if($person->person_id && (((isset($details->email) && isset($details->password)) && !$details->third_party_signup_token) || (isset($details->email) && $details->third_party_signup_token))) {
			$user = new UsersModel();
			$user->username = $details->email;
			$user->password = trim(md5($details->password));
			$user->person_id = $person->person_id ;
			$user->is_shopper = 1;
            $user->is_verified = 1;//temporary verify automatically the user
			$user->language = 'english';
			if(isset($details->loyalty_card_num ))
				$user->loyalty_card_num = $details->loyalty_card_num;
			if(isset($details->loyalty_card_email ))
				$user->loyalty_card_email = $details->loyalty_card_email;
			if(isset($details->loyalty_card_tier ))
				$user->loyalty_card_tier = $details->loyalty_card_tier;
			$user->save();
			$user_id = $user->id;
		}

		$customer = null;

		if($temp_user != null){
			$customer = CustomersModel::where('temp_id',$temp_user)->first();
		}

		if(!$customer)
			$customer = new CustomersModel();

		$customer->company_name = $details->first_name." ".$details->last_name;
		$customer->person_id = $person->person_id ;
		$customer->taxable = 1;
		$customer->balance = 0;
		$customer->save();


		return $customer;
	}

	/*
	 *
	 * validate new customer
	 */
	public function customerIsUnique($email,$phone){
		$error = "";

		if(UsersModel::where('username',$email)->exists() ){
			$error = "Email is already registered.";
		}
		// else if(PeoplesModel::where('phone_number',$phone)->exists() ){
		// 	$error = "Phone number is already registered.";
		// }
		return $error;
	}

	/*
	 *
	 * gets the temporary user details
	 */
	public function addAddress($customer_id,$details=array(),$default=false){
		// die();
		$address = new CustomersAddressModel();
		$address->name = $details->name;
		if(isset($details->address_type))
			$address->address_type = $details->address_type;
		$address->customer_id = $customer_id;

		if(isset($details->house_no))
			$details->street1 = $details->house_no." ".$details->street1;

		$address->actual_address = $details->actual_address;
		$address->street_1 = trim($details->street1);
		$address->street1 = trim($details->street1);
		$address->street_2 = $details->street2;
		$address->street2 = $details->street2;
		$address->city = $details->city;
		$address->city_solo = $details->city_solo;
		$address->sublocality= $details->sublocality;
		$address->administrative_area = $details->administrative_area;
		$address->zip = $details->zip;
		$address->lat = $details->lat;
		$address->lng = $details->lng;
		if($default)
			$address->default = 1;

		$address->save();
		return $address;
	}

	/*
	 *
	 * gets the temporary user details
	 */
	public function setDefaultAddress($customer_id,$address_id){
		# REmove defaults on all customer address
		CustomersAddressModel::where('customer_id',$customer_id)->update(['default'=>0]);

		# SET CURRENT ADDTRES TO DEFAULT
		$update = CustomersAddressModel::where('id',$address_id)
		->where('customer_id',$customer_id)
		->update(['default'=>1]);

		return $update;
	}

	/*
	 *
	 * gets the temporary user details
	 */
	public function deleteAddress($customer_id,$address_id){
		# SET CURRENT ADDTRES TO DEFAULT
		$delete = CustomersAddressModel::where('id',$address_id)
		->where('customer_id',$customer_id)
		->delete();

		return $delete;
	}

	/*
	 *
	 * gets the temporary user details
	 */
	public function getSalesNotifications($customer_id,$seen_only=false,$max=10,$after_id=false){
		return SalesNotificationsModel::with(['sales_log'])
			->where('person_id',$customer_id)
			->where(function($query) use ($seen_only){
				if($seen_only){
					$query->where('is_seen',1);
				}
			})
			->where(function($query) use ($after_id){
				if($after_id){
					$query->where('id','>',$after_id);
				}
			})
			->orderBy('id','desc')
			->get()->take($max);
	}

	public function seenSalesNotifications($customer_id,$notif_ids=array()){
		$seen = [];
		if(count($notif_ids) > 0){
			foreach ($notif_ids as $notif_id) {
				$notif = SalesNotificationsModel::with(['sales_log'])
					->where('id',$notif_id)
					->where('person_id',$customer_id)
					->first();
				$notif->is_seen = 1;
				$notif->seen_at = DB::raw('NOW()');
				$notif->save();
				$seen[] = $notif;
			}

		}
		return $seen;
	}


	public function getFavorites($customer_id){
		return CustomersFavoritesModel::where('customer_id',$customer_id)->get();
	}

	public function addToFavorites($customer_id,$brand_id,$menu_id){
		return CustomersFavoritesModel::insert([
			'customer_id' => $customer_id,
			'brand_id' => $brand_id,
			'item_id' => $menu_id,
		]);
	}
	/*
		UPDATES THE ORDER STATUS, RIDERS, DELIVERIES
	*/
	public function removeToFavorites($customer_id,$brand_id,$menu_id){
		return CustomersFavoritesModel::where('customer_id',$customer_id)
		->where('brand_id',$brand_id)
		->where('item_id',$menu_id)
		->delete();
	}
	/*
		UPDATES THE ACCOUNT DETAILS
	*/
	public function updateAccount($data){
		#UPDATE THE PEOPLE TABLE
		PeoplesModel::where('person_id',$data->user_id)
		->update([
			'first_name'=>$data->first_name,
			'last_name'=>$data->last_name,
			'phone_number'=>$data->mobile,
		]);
		if($data->birthdate != "null"){
			PeoplesModel::where('person_id',$data->user_id)
			->update([
				'birthdate'=>$data->birthdate,
			]);
		}

		#UPDATE THE USERS TABLE
		// if(isset($data->loyalty_card_email) && isset($data->loyalty_card_num) ){
			UsersModel::where('person_id',$data->user_id)->update(['loyalty_card_email'=>$data->loyalty_card_email,'loyalty_card_num'=>$data->loyalty_card_num,'loyalty_card_tier'=>$data->loyalty_card_tier]);
		// }

		return "Account Updated";
	}
	//UPDATE ADDRESS
	public function updateAddress($data){
		#UPDATE THE PEOPLE TABLE
		CustomersAddressModel::where('id',$data->location_id)
		->update([
			'name'=>$data->address_name,
			'actual_address'=>$data->actual_address,
			'street_1'=>$data->street1,
			'street_2'=>$data->street2,
			'street1'=>$data->street1,
			'street2'=>$data->street2,
			'city'=>$data->city,
			'city_solo'=>$data->city_solo,
			'sublocality'=>$data->sublocality,
			'administrative_area'=>$data->administrative_area,
			'zip'=>$data->zip,
			'lat'=>$data->lat,
			'lng'=>$data->lng,
		]);


		return "Account Updated";
	}

	// UPDATE PROFILE PIC
	public function updateProfilePic($id, $photo){
		$customer = PeoplesModel::where('person_id',$id)->first();

		$image = file_get_contents($photo->getRealPath());
		// encode image to base64
		$base64 = base64_encode($image);
		$customer->profile_pic = $base64;
		$customer->save();

		return "Profile picture updated.";
	}
	public function addUserLogs($details=array(), $logs_data){
		$logs = new UserLogsModel();

		$logs->user_id = $details->user_id;
		$logs->temp_user_id = $details->temp_user_id;
		$logs->logs = $logs_data;
		$logs->datetime_added = DB::raw('NOW()');
		$logs->platform = $details->platform;
		$logs->location = $details->location;
		$logs->method = $details->method;
		$logs->brands = $details->brands;
		$logs->shops = $details->shops;
		$logs->referrer = $details->referrer === 'null'? "" : $details->referrer ;

		$logs->save();
		return $logs;
	}
	public function updateUserLogs($details=array(), $logs_data){
		UserLogsModel::where('id', $details->current_log_id)
		->update([
			'user_id'=>$details->user_id,
			'temp_user_id'=>$details->temp_user_id,
			'logs'=>$logs_data,
			"platform" => $details->platform,
			"location" => $details->location,
			"country" => $details->country,
		]);
		// echo "<pre>",print_r($details->brands),"</pre>";die();
		if($details->carts_created){
			UserLogsModel::where('id', $details->current_log_id)
			->update([
				"carts_created" => $details->carts_created
			]);
		}
		if($details->brands){
			UserLogsModel::where('id', $details->current_log_id)
			->update([
				"method" => $details->method,
				"brands" => $details->brands,
				"shops" => $details->shops,
			]);
		}

		$logs = UserLogsModel::where('id',$details->current_log_id)->first();
		return $logs;
	}
	public function updateUserLogsCheckout($details=array()){
		UserLogsModel::where('id', $details->current_log_id)
		->update([
			"carts_created" => 1,
			'checkouts'=>1,
		]);
		$logs = UserLogsModel::where('id',$details->current_log_id)->first();
		return $logs;
	}
	public function updateUserLogsCartsCreated($details=array()){
		UserLogsModel::where('id', $details->current_log_id)
		->update([
			"carts_created" => 1,
		]);
		$logs = UserLogsModel::where('id',$details->current_log_id)->first();
		return $logs;
	}
	public function generateToken($username,$person_id){
		$token_model = new tokenModel();
		$token_code = uniqid(rand(), true);
		$expires_at = Carbon::now()->addDays(1);
		$token_model->token_code = $token_code;
		$token_model->username = $username;
		$token_model->person_id = $person_id;
		$token_model->expires_at = $expires_at;

		$token_model->save();
		return $token_code;
	}
	public function verifyToken($token){
		$token_model = new tokenModel();
		$token_data = $token_model::where("token_code", $token)->where('is_used', '==', 0)->first();
		if($token_data){
			UsersModel::where('person_id', $token_data->person_id)->update(['is_verified' => 1]);
			$token_model::where("token_code", $token)->update(['is_used' => 1]);
			return "true";
		}
	}
	public function verifyTokenPassword($details,$token){
		$token_model = new tokenModel();
		$token_data = $token_model::where("token_code", $token)->where('is_used', '==', 0)->first();
		// echo "<pre>",print_r($details),"</pre>";die();
		if($token_data){
			$user = UsersModel::where('person_id',$token_data->person_id)
			->update([
				'password'=>trim(md5($details->password)),
			]);
			$token_model::where("token_code", $token)->update(['is_used' => 1]);
			return "true";
		}
	}
}
