<?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');
				$this->load->model('customer_model');
	}
	
		public function deleteUser(){

          $id = $this->input->post("userId");




		$response = $this->customer_model->delete_customer($id);
		if (!$response) {
				$data['success']=0;
				$data['msg']="Something Error Occured";
				echo json_encode($data);
				exit;
		}
		$response = $this->common->deletedatamodel("Users", $id);
		$x=$this->common->readdatafromcollectionbetween2where("Posts","userId","=",$id);
		foreach ($x as $key => $value) {
		  //echo $key."<br>";
		  $this->common->deletedatamodel("Posts", $key);
	  }

	
		$data['success']=1;
				$data['msg']="User has been deleted";
				echo json_encode($data);
				exit;

		}


	public function index()
	{
		
		if (!empty($this->session->userdata('session_data'))) {
			$url = base_url('dashboard');
			header("location: $url");
		} else {
			$this->load->view('login');
		}
	}
	public function errorpage(){
		$this->load->view('errorpage');
	}
	public function login_link(){
		$userOrUid=$this->input->get('user_id');
		$data['timespan']=$this->input->get('timespan');
		$data['time']=time()*1000;
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		try {
			$user = $auth->getUser($userOrUid);
		
			$admin=$this->common->readdatadocument("Users",$userOrUid);		
			
				$session_data = array(
					'userId' => $userOrUid,
					'name' => $admin["name"],
					'email' => $admin["email"],

				);
				$this->session->set_userdata('session_data', $session_data);
				$this->session->set_userdata('reslist', false);
				redirect(base_url('dashboard'));
			
			

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


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

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

		$auth = $firebase->createAuth();
		try {
			$signInResult = $auth->signInWithEmailAndPassword($email, $password);
			$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('reslist', false);
				redirect(base_url('dashboard'));
			} else {
				$this->session->set_flashdata('warningmessage', 'Invalid email and/or password');
				redirect(base_url('login'));
			}
			

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




	}	
	public function login_action()
	{

		$email = $this->input->post("email");
		$password = $this->input->post("password");
		$resdata=$this->common->readdatafromcollectionwhereclause("Restaurant", "uniqueid", "=", $email);
		

		if(empty($resdata)){
			$this->session->set_flashdata('warningmessage', 'Invalid UserId !');
			redirect(base_url('login'));
		
		}else{
			 $resId = array_keys($resdata)[0];
			if($resdata[$resId]['association']==false){
				$this->session->set_flashdata('warningmessage', 'You have no right to access this portal');
				redirect(base_url('login'));
			
			}else if($resdata[$resId]['expire_at']<date("Y-m-d")){
				$this->session->set_flashdata('warningmessage', 'Your Subsription has been Expired ');
				redirect(base_url('login'));
			}else if($resdata[$resId]['pwd']!=$password){
				$this->session->set_flashdata('warningmessage', 'Invalid Password ');
				redirect(base_url('login'));
			}else{
				$session_data = array(
					'userId' => $resId,
					'name' => $resdata[$resId]['name'],
					'email' => '',
					'adminId' => $resId,
					'country'=>$resdata[$resId]['country']
				);
				$this->session->set_userdata('session_data', $session_data);
	
				redirect(base_url('dashboard'));

			}
		

		}
		
		
	}

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