<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
use Google\Cloud\Firestore\FirestoreClient;

class User_model extends CI_Model
{



	public function add_user($data)
	{
		$userins = $data['basic'];
		$userins['u_password'] = md5($data['basic']['u_password']);
		$this->db->insert('login', $userins);
		$uid = $this->db->insert_id();
		$role = $data['permissions'];
		$role['lr_u_id'] = $uid;
		return  $this->db->insert('login_roles', $role);
	}

	public function seed_admin_user()
	{
		// Prepare the data for the user
		$data = [
			'basic' => [
				'name' => 'test user',
				'first_name' => 'test',
				'last_name' => 'user',
				'phone' => 'random_phone_number',
				'password' => '1234',
				'image' => '',
				'role' => 'admin',
				'createdAt' => 'timestamp'
			],
		];

		// Call the add_user method to insert the user data
		return $this->add_user($data);
	}
	public function getall_user()
	{
		return $this->db->select('*')->from('login')->order_by('u_id', 'desc')->get()->result_array();
	}
	public function get_userdetails($u_id)
	{
		$this->db->select("*");
		$this->db->from('login');
		$this->db->join('login_roles', 'login.u_id=login_roles.lr_u_id');
		$this->db->where('login.u_id', $u_id);
		$query = $this->db->get();
		return $query->result_array();
	}
	public function update_user($data)
	{
		$userup = $data['basic'];
		if (isset($data['basic']['u_password'])) {
			$userup['u_password'] = md5($data['basic']['u_password']);
		}
		$this->db->where('u_id', $data['basic']['u_id']);
		$this->db->update('login', $userup);
		$role = $data['permissions'];

		$this->db->where('lr_u_id', $data['basic']['u_id']);
		return $this->db->update('login_roles', $role);
	}

	public function signup_user($data)
	{
		// Initialize Firebase Authentication
		$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) {
			log_message('error', 'Firebase User Creation Failed: ' . $th->getMessage());
			return false; // Firebase user creation failed
		}

		$firebaseUid = $createdUser->uid;

		// Step 2: Add user details to Firestore
		$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'],
			'userType' => $data['userType'] ?? 'user', // Default user type
			'isActive' => true,
			'createdAt' => date('Y-m-d H:i:s'),
		];

		try {
			$firestore->collection('Users')->document($firebaseUid)->set($firestoreData);
		} catch (\Throwable $th) {
			// Rollback Firebase Authentication user if Firestore fails
			$auth->deleteUser($firebaseUid);
			log_message('error', 'Firestore User Creation Failed: ' . $th->getMessage());
			return false; // Firestore user creation failed
		}

		return true; // Successfully created user
	}
}
