<?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'))) {
			$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();

		try {
			// Attempt to sign in with email and password
			$signInResult = $auth->signInWithEmailAndPassword($email, $password);
		} catch (FirebaseException $e) {
			// Authentication failed
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password!');
			$this->session->set_flashdata('email', $email);
			redirect(base_url('login'));
		}

		$my = $signInResult->data();
		$userId = $my['localId'];

		$admin = $this->common->readdatadocument("Users", $userId);

		if (isset($admin["userType"]) && $admin["userType"] !== 'coach') {
			$this->session->set_flashdata('warningmessage', 'You are not authorized to log in!');
			redirect(base_url('login'));
		}

		if (!empty($my["idToken"])) {
			$session_data = array(
				'userId' => $userId,
				'name' => $admin["name"],
				'firstName' => $admin["firstName"],
				'lastName' => $admin["lastName"],
				'email' => $admin["email"],
				'dob' => $admin["dob"],
				'phone' => $admin["phone"],
				'address' => $admin["address"],
				'u_image' => $admin["u_image"],
				'firebaseToken' => $my["idToken"],
				'userType' => $admin["userType"],
			);
			// echo '<pre>';
			// print_r($session_data);
			// echo '<pre>';
			// die;
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_userdata('authenthicate', true);

			redirect(base_url('dashboard'));
		} else {
			// Fallback in case of unexpected issues
			$this->session->set_flashdata('warningmessage', 'Something went wrong! Please try again.');
			$this->session->set_flashdata('email', $email);
			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'));
	}

	public function send_reset_email()
	{
		$email = $this->input->post('email');

		if (!$email) {
			$this->session->set_flashdata('warningmessage', 'Please enter a valid email.');
			redirect(base_url());
		}

		$user = $this->common->getUserByEmail($email);


		if (!$user) {
			$this->session->set_flashdata('warningmessage', 'Email not found.');
			redirect(base_url());
		}

		// Generate new password
		$newPassword = preg_replace('/\s+/', '', substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 8));

		// Update password in Firebase
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();

		try {
			$auth->changeUserPassword($user->userId, $newPassword);
		} catch (Exception $e) {
			$this->session->set_flashdata('warningmessage', 'Firebase Error: ' . $e->getMessage());
			redirect(base_url());
		}

		// Update password in your DB
		$this->common->updatedatamodel('Users', $user->userId, ['password' => $newPassword]);

		// Send new password to user
		if ($this->sendNewPasswordEmail($user->name, $user->email, $newPassword)) {
			$this->session->set_flashdata('successmessage', 'A new password has been sent to your email.');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to send email.');
		}

		redirect(base_url());
	}


	private function sendNewPasswordEmail($name, $email, $newPassword)
	{
		$this->load->library('email');

		$config = array(
			'protocol' => 'smtp',
			'smtp_host' => 'ssl://mail.buzzwaretech.com',
			'smtp_user' => 'testweb@buzzwaretech.com',
			'smtp_pass' => ',j8Og2d1Ty1%',
			'smtp_port' => 465,
			'mailtype'  => 'html',
			'charset'   => 'utf-8',
			'wordwrap'  => TRUE,
			'newline'   => "\r\n"
		);

		$this->email->initialize($config);

		$this->email->from('testweb@buzzwaretech.com', 'My Coach');
		$this->email->to($email);
		$this->email->subject('Your New Password');
		$this->email->message("
			Hello $name,<br><br>
			Your new password is: <span style='display:inline-block;padding:5px 10px;background:#f0f0f0;border:1px solid #ccc;font-family:monospace;'>$newPassword</span><br><br>
			Please login and change it after logging in.
		");


		return $this->email->send();
	}
}
