<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

use Google\Cloud\Firestore\FirestoreClient;

class Customer_model extends CI_Model
{
	public  function update_customerpassword($id, $pwd)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

		$auth = $firebase->createAuth();
		try {
			$updatedUser = $auth->changeUserPassword($id, $pwd);
			return True;
		} catch (\Throwable $th) {
			return False;
		}
	}


	public function add_customer($data)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

		$auth = $firebase->createAuth();
		$userProperties = [
			'email' => $data['email'],
			'emailVerified' => false,

			'password' => $data['password'],
			'displayName' => $data['name'],
			'disabled' => false,
		];

		try {
			$createdUser = $auth->createUser($userProperties);
		} catch (\Throwable $th) {
			return false;
		}

		$signInResult = $auth->signInWithEmailAndPassword($userProperties['email'], $userProperties['password']);
		$my = $signInResult->data();

		$x = $this->config->item('firebase_app_key');
		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$batch = $firestore->collection('Users')->document($my['localId']);
		$response = $batch->create($data);
		return TRUE;
	}

	public function add_coach($data)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

		$auth = $firebase->createAuth();
		$userProperties = [
			'email' => $data['email'],
			'emailVerified' => false,

			'password' => $data['password'],
			'displayName' => $data['name'],
			'disabled' => false,
		];

		try {
			$createdUser = $auth->createUser($userProperties);
		} catch (\Throwable $th) {
			return false;
		}

		$signInResult = $auth->signInWithEmailAndPassword($userProperties['email'], $userProperties['password']);
		$my = $signInResult->data();

		$x = $this->config->item('firebase_app_key');
		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$batch = $firestore->collection('Coaches')->document($my['localId']);
		$response = $batch->create($data);
		return TRUE;
	}


		public function add_admin($data,$alladminlist)
	{
		// echo "<pre>";
		// print_r($data);
		// print_r($alladminlist);
		// echo "</pre>";
		$flag=0;

		foreach ($alladminlist as $key => $value) {
			if($value['email']==$data['email']){
				//echo "found";
				$flag=1;
			}
		}


		// echo $flag;
		// exit;
		if($flag==0){
        	$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

		$auth = $firebase->createAuth();
        $x = $this->config->item('firebase_app_key');
		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);
		$myid=time();

		$batch = $firestore->collection('Users')->document($myid);
		$response = $batch->create($data);
		return TRUE;

		}else{
			return false;
		}


	


		
	}


	public function delete_customer($id)
	{
		// echo "yes";
		// exit;
		 $firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		try {
			$auth->deleteUser($id);
			return TRUE;
		} catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
			return FALSE;
		} catch (\Kreait\Firebase\Exception\AuthException $e) {
			return FALSE;
		}

	}
	public function getall_sch()
	{
		//		return $this->db->select('*')->from('customers')->order_by('c_id','desc')->get()->result_array();

		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$citiesRef = $db->collection('ScheduledRides');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				//echo json_encode($document->data(), JSON_PRETTY_PRINT);
				$path = substr($document->path(), 6);
				$output[$path] = $document->data();
			}
		}
		//$output;
		return $output;
	}
	public function getall_emergency()
	{

		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$citiesRef = $db->collection('Emergency');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				//echo json_encode($document->data(), JSON_PRETTY_PRINT);
				$path = substr($document->path(), 6);
				$output[$path] = $document->data();
			}
		}
		//$output;
		return $output;
	}

	public function getall_vendor()
	{
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		
		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);
		
		$citiesRef = $db->collection('Users')->where('userRole', '=', 'seller');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$output[$document->id()] = $document->data();
			}
		}
		return $output;	
	}	
	public function getall_customer()
	{

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$citiesRef = $db->collection('Users')->where('userRole', '=', 'user');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$output[$document->id()] = $document->data();
				$user = $auth->getUser($document->id());
				$u = json_decode(json_encode($user), true);
				$output[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
			}
		}
		return $output;
	}

	public function getall_coaches()
	{

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$citiesRef = $db->collection('Users')->where('userRole', '=', 'coach');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$output[$document->id()] = $document->data();
		//		$user = $auth->getUser($document->id());
	//			$u = json_decode(json_encode($user), true);
	//			$output[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
			}
		}
		return $output;
	}

	public function get_coachdetails($c_id)
	{
		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);
		$document = $db->collection('Coaches')->document($c_id)->snapshot()->data();

		return $document;
	}

	public function getall_freelancers()
	{

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$citiesRef = $db->collection('Users')->where('userRole', '=', 'freelancer');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$output[$document->id()] = $document->data();
				$user = $auth->getUser($document->id());
				$u = json_decode(json_encode($user), true);
				$output[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
			}
		}
		$da['user'] = $output;
		return $da;
	}


	public function getall_drivers()
	{

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$citiesRef = $db->collection('ServiceProvider');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$output[$document->id()] = $document->data();

			}
		}
		$da['user'] = $output;
		return $da;
	}
	public function getall_admin()
	{

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$citiesRef = $db->collection('Users')->where('userRole', '=', 'admin');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$output[$document->id()] = $document->data();
				$user = $auth->getUser($document->id());
				$u = json_decode(json_encode($user), true);
				$output[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
			}
		}
		$da['user'] = $output;
		return $da;
	}
	public function get_chatcustomers()
	{

		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		$thisAdminID = $this->session->userdata["session_data"]["adminId"];

		$x = $this->config->item('firebase_app_key');
		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$staffRef = $firestore->collection('Users')->where('userRole', '=', 'user');
		$documents = $staffRef->documents();
		$myChatStaff = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$chatStaffRef = $firestore->collection('AdminChats')->where('chatType', '=', 'one')->where('participants.' . $document->id(), '=', true)->where('participants.' . $thisAdminID, '=', true)->limit(1);
				$chatStaffDocs = $chatStaffRef->documents();
				foreach ($chatStaffDocs as $chatStaffDoc) {
					if ($document->exists()) {
						$conversationData = $chatStaffDoc->data();
						$myChatStaff[$document->id()] = $document->data();
						$myChatStaff[$document->id()]['conversationID'] = $conversationData['conversationID'];

						$user = $auth->getUser($document->id());
						$u = json_decode(json_encode($user), true);
						$myChatStaff[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
					}
				}
			}
		}

		return $myChatStaff;
	}
	public function get_customerdetails($c_id)
	{
		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);
		$document = $db->collection('Users')->document($c_id)->snapshot()->data();

		return $document;
	}
	
	public function update_customer($data)
	{
		$x = $this->config->item('firebase_app_key');
		$db = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($x), true)
		]);
		try {
			$citiesRef = $db->collection('Users')->where('email', '=', $data["old"]["email"]);
			$documents = $citiesRef->documents();
			$documentId = NULL;
			foreach ($documents as $documentId => $document) {
				$documentId = $document->id();
			}
			if (empty($documentId)) {
				return False;
			}
			$customerData = array();
			foreach ($data["new"] as $key => $value) {
				$d['path'] = $key;
				$d['value'] = $value;
				array_push($customerData, $d);
			}

			$batch = $db->collection('Users')->document($documentId);
			$response = $batch->update($customerData);
		} catch (\Throwable $th) {
			return False;
		}
		return TRUE;
	}
}