<?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'))) {
			$role = $this->session->userdata('session_data')['role'];
			if ($role == 'fleet') {
				$url = base_url('FleetOwnerDashboard');
			} else {
				$url = base_url('dashboard/live');
			}
			header("location: $url");		


		
		
		} else {
			$this->load->view('login');
		}
	}

	public function login_action()
	{

		$email = $this->input->post("email");
		$password = $this->input->post("password");
		

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

		$auth = $firebase->createAuth();
		

		try {
			$signInResult = $auth->signInWithEmailAndPassword($email, $password);

		} catch (FirebaseException $e) {
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password !');
			redirect(base_url('login'));
		}

		$my = $signInResult->data();
		
		
		$dispatcher = $this->common->readdatadocument("Users",$my['localId']);		


		if ($dispatcher['userRole'] == 'fleet') {

			$session_data = array(
				'userId' => $my["localId"],
				'name' => $dispatcher["fullname"],
				'email' => $dispatcher["email"],
				'role' => $dispatcher["userRole"],
				'firebaseToken' => $my["idToken"]
			);
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);
			redirect(base_url('FleetOwnerDashboard'));
		} else {
			$this->session->set_flashdata('warningmessage', 'You are not authorized to access dispatcher panel!');
			redirect(base_url('login'));
		}



	}

	//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'));
	}
}