<?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 update_customeremail($id, $email)
	{
		$firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

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

	public function add_agent($data)
	{
		$firebase = $this->firebase->init();

		$auth = $firebase->createAuth();
		$userProperties = [
			'email' => $data['email'],
			'password' => $data['password'],
			'displayName' => $data['fullname'],
		];

		try {
			$auth->createUser($userProperties);
		} catch (\Throwable $error) {
			var_dump($error);die;
			return false;
		}

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

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

		$data['id'] = $my['localId'];
		$data['isActive'] = false;
		$data['timestamp'] = time();
		
		try{
			$batch = $firestore->collection('Agents')->document($my['localId']);
			$batch->set($data);
			return true;
		}catch (\Throwable $error){
			throw new Exception($error, 1);
		}
		
	}
	public function add_customer($data)
	{
		$firebase = $this->firebase->init();

		$auth = $firebase->createAuth();
		$userProperties = [
			'email' => $data['email'],
			'password' => $data['password'],
			'displayName' => $data['fullname'],
		];

		try {
			$auth->createUser($userProperties);
		} catch (\Throwable $error) {
			var_dump($error);die;
			return false;
		}

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

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

		$data['id'] = $my['localId'];
		$data['isActive'] = false;
		$data['timestamp'] = time();
		
		try{
			$batch = $firestore->collection('Users')->document($my['localId']);
			$batch->set($data);
			return true;
		}catch (\Throwable $error){
			throw new Exception($error, 1);
		}
		
	}

	public function update_customer($data)
	{
		$x = $this->config->item('firebase_app_key');
        $firebaseProjectID = $this->config->item('firebase_project_id');
        $firestore = new FirestoreClient([
            'projectId' => $firebaseProjectID,
            'keyFile' => json_decode(file_get_contents($x), true)
        ]);
		
		try {
			$docRef = $firestore->collection('Users')->document($data['id']);
			$docRef->set($data, ['merge' => true]);
		} catch (\Throwable $th) {
			return false;
		}
		return true;
	}

	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 getall_emergency()
	{
		//		return $this->db->select('*')->from('customers')->order_by('c_id','desc')->get()->result_array();

		$x = $this->config->item('firebase_app_key');
        $firebaseProjectID = $this->config->item('firebase_project_id');
        $db = new FirestoreClient([
            'projectId' => $firebaseProjectID,
            '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()
	{
		//		return $this->db->select('*')->from('customers')->order_by('c_id','desc')->get()->result_array();

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

		$citiesRef = $db->collection('Users')->where('userType', '=', 'User');
		$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();
			}
		}
		$da['user'] = $output;
		return $da;
	}
	public function get_customerdetails($c_id)
	{
		$x = $this->config->item('firebase_app_key');
        $firebaseProjectID = $this->config->item('firebase_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;
	}

	
}