<?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_owner($data)
	{
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
	
		// Step 1: Add user to Firebase Authentication
		$userProperties = [
			'email' => $data['email'],
			'emailVerified' => false,
			'password' => $data['password'],
			'displayName' => $data['name'],
			'disabled' => false,
		];
	
		try {
			$createdUser = $auth->createUser($userProperties);
		} catch (\Throwable $th) {
			return false; 
		}
	
		$firebaseUid = $createdUser->uid;

		$firestore = new FirestoreClient([
			'projectId' => $this->config->item('firebase_project_id'),
			'keyFile' => json_decode(file_get_contents($this->config->item('firebase_app_key')), true)
		]);
	
		$firestoreData = [
			'firstName' => explode(' ', $data['name'])[0],
			'lastName' => explode(' ', $data['name'], 2)[1] ?? '',
			'email' => $data['email'],
			'phone' => $data['phone'],
			// 'imageUrl' => $data['photo'] ?? '',
			'userType' => $data['userType'],
			'isActive' => true,
		];
	
		$firestore->collection('Users')->document($firebaseUid)->set($firestoreData);
	

		// $dbData = [
		// 	'firebaseUid' => $firebaseUid,
		// 	'name' => $data['name'],
		// 	'email' => $data['email'],
		// 	'phone' => $data['phone'],
		// 	// 'photo' => $data['photo'],
		// 	'type' => $data['userType'],
		// 	'status' => 'Active',
		// ];
	
		// $this->db->insert('Users', $dbData);
	
		return true; 
	}
	


	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_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)
	{
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		try {
			$auth->deleteUser($id);
		} catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
			return FALSE;
		} catch (\Kreait\Firebase\Exception\AuthException $e) {
			return FALSE;
		}
		return TRUE;
	}
	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_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('userType', '=', 'onwer');
	// 	$documents = $citiesRef->documents();
	// 	$output = array();
	// 	foreach ($documents as $document) {
	// 		// print_r($document->id());
	// 		// 	die();
	// 		if ($document->exists()) {
	// 			$output[$document->id()] = $document->data();
	// 			$user = $auth->getUser($document->id());

	// 			$u = json_decode(json_encode($user), true);
	// 			// print_r($u);
	// 			// die();
	// 			$output[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
	// 		}
	// 	}
	// 	$da['user'] = $output;
	// 	// print_r($da);
	// 	// die();
	// 	return $da;
	// }

	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)
    ]);

    $ownersRef = $db->collection('Users')->where('userType', '=', 'owner');
    $documents = $ownersRef->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);
            $lastLogin = isset($u['metadata']['lastRefreshAt']) ? substr($u['metadata']['lastRefreshAt']['date'], 0, 19) : 'Never';
            $output[$document->id()]['userLastLogin'] = $lastLogin;
        }
    }

    $data['user'] = $output;
    return $data;
}



	public function getall_trainer()
	{

		$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('userType', '=', 'owner');
		$documents = $citiesRef->documents();
		$output = array();
		foreach ($documents as $document) {
			// print_r($document->id());
			// 	die();
			if ($document->exists()) {
				$output[$document->id()] = $document->data();
				$user = $auth->getUser($document->id());

				$u = json_decode(json_encode($user), true);
				// print_r($u);
				// die();
				$output[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
			}
		}
		$da['user'] = $output;
		// print_r($da);
		// die();
		return $da;
	}

	// 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();
	// 			try {
	// 				$user = $auth->getUser($document->id());
	// 				$u = json_decode(json_encode($user), true);
	// 				$output[$document->id()]['userLastLogin'] = substr($u['metadata']['lastRefreshAt']['date'], 0, 19);
	// 			} catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) {
	// 				// print_r($document->id());
	// 				// die();
	// 				$output[$document->id()]['userLastLogin'] = 'User not found';
	// 			}
	// 		}
	// 	}
	// 	$da['user'] = $output;
	// 	print_r($da);
	// 	die();
	// 	return $da;
	// }


	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('userType', '=', '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 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('Users')->where('userRole', '=', 'driver');
		$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_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;
	}
}
