<?php
defined('BASEPATH') OR exit('No direct script access allowed');
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->library('session');
	
	}
	//To load login page
	public function index()    //Login Controller
	{
	  if (isset($this->session->userdata['session_data'])) {
            $url = base_url() . "dashboard";
            header("location: $url");
        } else {
            $this->load->view('login');
        }
	}
	
	//To login functionality check
	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 (Kreait\Firebase\Auth\SignIn\FailedToSignIn $e) {
            // Another error has occurred
            // echo $e->getMessage();

			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password !');
			redirect(base_url('login'));
        } 
		
	
		$my = $signInResult->data();


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


		if (!empty($my["idToken"])) {

			$session_data = array(
				'userId' => $my["localId"],
				'name' => $admin["name"],
				'email' => $admin["email"],
				'firebaseToken' => $my["idToken"]
			);
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);
			redirect(base_url('dashboard'));
		} else {
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password1 !');
			redirect(base_url('login'));
		}



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