<?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');
		$this->load->database();
	}
	//To load login page
	public function index()    //Login Controller
	{
	  if (isset($this->session->userdata['session_data'])) {
            $url = base_url() . "admin";
            header("location: $url");
        } else {
            $this->load->view('login');
        }
	}
	
	//To login functionality check
	public function login_action()
	{
		$email = trim((string)$this->input->post("email"));
		$password = trim((string)$this->input->post("password"));

		$firebaseUser = null;
		try {
			$firebase = $this->firebase->init();
			$auth = $firebase->createAuth();
			$signInResult = $auth->signInWithEmailAndPassword($email, $password);
			$my = $signInResult->data();
			$firebaseUser = $my;
		} catch (\Throwable $e) {
			$firebaseUser = null;
		}

		if ($firebaseUser && !empty($firebaseUser["idToken"])) {
			$admin = $this->common->readdatadocument("users", $firebaseUser['localId']);
			if (!is_array($admin) || empty($admin)) {
				$admin = $this->common->readdatadocument("user", $firebaseUser['localId']);
			}
			$displayName = !empty($admin['name']) ? $admin['name'] : (!empty($admin['userName']) ? $admin['userName'] : $email);

			$session_data = array(
				'userId' => $firebaseUser["localId"],
				'name' => $displayName,
				'email' => isset($admin["email"]) ? $admin["email"] : $email,
				'userRole' => isset($admin["userRole"]) ? $admin["userRole"] : 'admin',
				'firebaseToken' => $firebaseUser["idToken"]
			);
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);
			redirect(base_url('admin'));
			return;
		}

		// Fallback: Authenticate directly against Firestore `users` collection
		$users = $this->staffcheckin->get_users();
		foreach ($users as $uId => $u) {
			if (isset($u['email']) && strtolower(trim($u['email'])) === strtolower(trim($email)) && isset($u['password']) && (string)$u['password'] === (string)$password) {
				$session_data = array(
					'userId' => $uId,
					'name' => isset($u['name']) ? $u['name'] : 'Mr.admin',
					'email' => $u['email'],
					'userRole' => isset($u['userRole']) ? $u['userRole'] : 'admin',
					'firebaseToken' => 'direct_session'
				);
				$this->session->set_userdata('session_data', $session_data);
				$this->session->set_userdata('authenthicate', true);
				redirect(base_url('admin'));
				return;
			}
		}

		// Default admin fallback for admin@gmail.com / 123456
		if (strtolower(trim($email)) === 'admin@gmail.com' && (string)$password === '123456') {
			$session_data = array(
				'userId' => 'admin_default',
				'name' => 'Mr.admin',
				'email' => 'admin@gmail.com',
				'userRole' => 'admin',
				'firebaseToken' => 'admin_default_token'
			);
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);
			redirect(base_url('admin'));
			return;
		}

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