<?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 getanylatics() {
  		$data=$this->common->getanylatics();
  		echo "<pre>";
  		print_r($data);
  		echo "</pre>";



  }

  public function verify() {
            $this->load->library('GoogleAuthenticator');
              $google2fa = new GoogleAuthenticator();
    
       // $google2fa = new Google2FA();

	   $settings = $this->common->readdatafromcollectionbetween("Settings");
	   $secretKey = "" ;
	   foreach($settings as $setting) {
		$secretKey = $setting['secretKey2FA'] ;
	   }
		if(empty($secretKey)) {
			$secretKey = "NQI2RJUDS3KAA3OI" ;
		}
        
        $oneTimePassword = 166306;
   		$token = $google2fa->getCode($secretKey);

		//$token="1234";

        if ($token == $this->input->post('code')) {
		$this->session->set_userdata('authenthicate', true);
           redirect(base_url('dashboard'));
            // User authenticated successfully
        } else {
       
            // User authentication failed
     	$this->session->set_flashdata('warningmessage', 'Invalid Code !');
			redirect(base_url('login/googleauthenticate'));
        }
    }

	function googleauthenticate(){
		$this->load->view('googleauthenticate');


            
}



	public function index()
	{

		if (!empty($this->session->userdata('session_data'))) {
			$url = base_url('dashboard');
			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();
		/*
			$adminlist = $this->common->readdatafromcollectionwhereclause("Users", 'userRole', '=', 'admin');
			echo "<pre>";
		print_r($adminlist);
		echo "</pre>";
		exit;
			$flag=0;
			foreach ($adminlist as $key => $value) {
				if($value['email']==$email && $value['password']==$password){
					$flag==$key;
			$session_data = array(
				'userId' => $key,
				'name' => $value["name"],
				'email' => $value["email"],
				'permissions' => $value["permissions"],
				'firebaseToken' => ''
			);
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);
		//	redirect(base_url('login/googleauthenticate'));					
			exit;
				}
			}
			if($flag==0){
$this->session->set_flashdata('warningmessage', 'Invalid email and/or password1 !');
			redirect(base_url('login'));
			}
*/


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

		} catch (FirebaseException $e) {
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password3 !');
			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'));
		}



	}

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