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

use Kreait\Firebase\Exception\FirebaseException;
//use Throwable;

class Login extends CI_Controller
{
	//To load initial libraries, functions
	function __construct()
	{
		parent::__construct();
		$this->load->helper('url');
		$this->load->helper('directory');
		$this->load->helper('form');
		$this->load->library('form_validation');
		$this->load->model('common');
		$this->load->library('session');
	}


	public function index()
	{

		if (!empty($this->session->userdata('session_data'))) {
			$url = base_url('dashboard');
			header("location: $url");
		} else {
			$this->load->view('login');
		}
	}

	public function signup()
	{


		$this->load->view('signup');
	}


	public function login_action()
	{
		$email = $this->input->post("email");
		$password = $this->input->post("password");

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

		try {
			// Attempt to sign in with email and password
			$signInResult = $auth->signInWithEmailAndPassword($email, $password);
		} catch (FirebaseException $e) {
			// Authentication failed
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password!');
			$this->session->set_flashdata('email', $email);
			redirect(base_url('login'));
		}

		$my = $signInResult->data();
		$userId = $my['localId'];

		$admin = $this->common->readdatadocument("Users", $userId);

		if (isset($admin["userType"]) && $admin["userType"] !== 'user') {
			$this->session->set_flashdata('warningmessage', 'You are not authorized to log in!');
			redirect(base_url('login'));
		}

		if (!empty($my["idToken"])) {
			$session_data = array(
				'userId' => $userId,
				'name' => $admin["name"],
				'email' => $admin["email"],
				'u_image' => $admin["u_image"],
				'firebaseToken' => $my["idToken"],
				'userType' => $admin["userType"],
			);
			// echo '<pre>';
			// print_r($session_data);
			// echo '<pre>';
			// die;
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);

			redirect(base_url('dashboard'));
		} else {
			// Fallback in case of unexpected issues
			$this->session->set_flashdata('warningmessage', 'Something went wrong! Please try again.');
			$this->session->set_flashdata('email', $email);
			redirect(base_url('login'));
		}
	}

	public function signup_action()
	{
		$this->form_validation->set_rules('fName', 'First Name', 'required');
		$this->form_validation->set_rules('lName', 'Last Name', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
		$this->form_validation->set_rules('phone', 'Phone', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
	
		if ($this->form_validation->run() == FALSE) {
			$this->session->set_flashdata('error', validation_errors());
			redirect(base_url('Login/signup'));
		}
	
		$data = [
			'name' => $this->input->post('fName') . ' ' . $this->input->post('lName'),
			'email' => $this->input->post('email'),
			'phone' => $this->input->post('phone'),
			'password' => $this->input->post('password'),
			'userType' => 'user',
		];
	
		$this->load->model('User_model');
		$result = $this->User_model->signup_user($data);
	
		if ($result) {
			// Fetch user information (replace with appropriate data retrieval logic)
			$firebase = $this->firebase->init();
			$auth = $firebase->createAuth();
	
			try {
				$signInResult = $auth->signInWithEmailAndPassword($data['email'], $data['password']);
				$userRecord = $auth->getUserByEmail($data['email']);
				$userId = $userRecord->uid;
	
				// Prepare session data
				$session_data = [
					'userId' => $userId,
					'name' => $data['name'],
					'email' => $data['email'],
					'u_image' => '', // Update this if a user image is available
					'firebaseToken' => $signInResult->data()["idToken"],
					'userType' => $data['userType'],
				];
	
				// Set session data
				$this->session->set_userdata('session_data', $session_data);
				$this->session->set_userdata('authenthicate', true);
	
				$this->session->set_flashdata('success', 'Signup successful! Welcome to the platform.');
				redirect(base_url('dashboard'));
			} catch (Exception $e) {
				$this->session->set_flashdata('error', 'Login failed after signup! ' . $e->getMessage());
				redirect(base_url('Login/signup'));
			}
		} else {
			$this->session->set_flashdata('error', 'Signup failed! Please try again.');
			redirect(base_url('Login/signup'));
		}
	}
	
	




	//To logout session from browser
	public function logout()
	{
		// Removing session data
		$sess_array = array('userId' => '');
		$this->session->unset_userdata('session_data', $sess_array);
		$this->session->sess_destroy();
		$this->session->set_flashdata('successmessage', 'Successfully Logged out !');
		redirect(base_url('login'));
	}
}
