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

use Google\Cloud\Firestore\FirestoreClient;

class Staff_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_staff($data)
	{
		$firebase = $this->firebase->init();

		$auth = $firebase->createAuth();


		$userProperties = [
			'email' => $data['email'],
			'name' => $data['firstName'],
			'password' => $data['password'],
		];

		try {
			$auth->createUser($userProperties);
		} catch (Throwable $e) {
			echo 'An error has occurred: ' . $e->getMessage;
		}

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


		$x = $this->config->item('firebase_app_key');
		$firebaseProjectID = $this->config->item('firesbase_project_id');
		$firestore = new FirestoreClient([
			'projectId' => $firebaseProjectID,
			'keyFile' => json_decode(file_get_contents($x), true)
		]);
		$batch = $firestore->collection('staff')->document($my['localId']);


		try {
			$batch->set($data);
			return true;
		} catch (Throwable $e) {
			echo 'A firestore error has occurred: ' . $e->getMessage;
		}
	}

	public function addpreferred_staff($data)
	{
		$x = $this->config->item('firebase_app_key');
		$firebaseProjectID = $this->config->item('firesbase_project_id');
		$firestore = new FirestoreClient([
			'projectId' => $firebaseProjectID,
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$batch = $firestore->collection('preferredStaff');


		try {
			$batch->add($data);
			return true;
		} catch (Throwable $e) {
			echo 'A firestore error has occurred: ' . $e->getMessage;
		}
	}

	public function removepreferred_staff($data)
	{

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

		$prefRef = $firestore->collection('preferredStaff')->where('staffID', '=', $data["staffID"])->where('clientID', '=', $data["clientID"])->limit(1);
		$prefDocuments = $prefRef->documents();
		foreach ($prefDocuments as $prefDocument) {
			$firestore->collection("preferredStaff")->document($prefDocument->id())->delete();
		}
	}
	public function rate_staff($data)
	{

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

		$staffRef = $firestore->collection('staff')->document($data["staffID"]);
		$staffRef->update([
			["path" => "ratings", "value" => $data["rating"]]
		]);
	}

	public function delete_customer($id)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

		$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 get_allstaff()
	{

		$thisClientID = $this->session->userdata["session_data"]["userId"];
		$x = $this->config->item('firebase_app_key');
		$firebaseProjectID = $this->config->item('firesbase_project_id');
		$firestore = new FirestoreClient([
			'projectId' => $firebaseProjectID,
			'keyFile' => json_decode(file_get_contents($x), true)
		]);

		$staffRef = $firestore->collection('staff')->where('userRole', '=', 'staff');
		$documents = $staffRef->documents();
		$output = array();
		foreach ($documents as $document) {
			if ($document->exists()) {
				$output[$document->id()] = $document->data();

				// preferred staff
			//	$prefRef = $firestore->collection('preferredStaff')->where('staffID', '=', $document->id())->where('clientID', '=', $thisClientID)->limit(1);
			//	$prefDocuments = $prefRef->documents();
			//	foreach ($prefDocuments as $prefDocument) {
			//		$output[$document->id()]["isPreferred"] = true;
			//	}
			}
		}
		$da['staff'] = $output;

		return $da;
	}


	public function get_preferredstaff()
	{
		$thisClientID = $this->session->userdata["session_data"]["userId"];

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

		$prefRef = $db->collection('preferredStaff')->where("clientID", "=", $thisClientID);
		$prefDocuments = $prefRef->documents();
		$output = array();
		foreach ($prefDocuments as $prefDocument) {
			$prefData = $prefDocument->data();
			$staffID = $prefData["staffID"];
			$staffDocument = $db->collection('staff')->document($staffID);

			$output[$staffDocument->id()] = $staffDocument->snapshot()->data();
		}

		$data["prefStaff"] = $output;

		return $data;
	}

	public function get_customerdetails($c_id)
	{
		$x = $this->config->item('firebase_app_key');
		$firebaseProjectID = $this->config->item('firesbase_project_id');
		$db = new FirestoreClient([
			'projectId' => $firebaseProjectID,
			'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');
		$firebaseProjectID = $this->config->item('firesbase_project_id');
		$db = new FirestoreClient([
			'projectId' => $firebaseProjectID,
			'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;
	}
}