<?php

if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdmin extends pjAppController
{
	public $defaultUser = 'admin_user';
	
	public $requireLogin = true;
	
	protected $adminBooking = 'Admin_Booking';
	
	public function __construct($requireLogin=null)
	{
		$this->setLayout('pjActionAdmin');
		
		if (!is_null($requireLogin) && is_bool($requireLogin))
		{
			$this->requireLogin = $requireLogin;
		}
		
		if ($this->requireLogin)
		{
			if (!$this->isLoged() && !in_array(@$_GET['action'], array('pjActionLogin', 'pjActionVerify2FA','pjActionForgot', 'pjActionPreview', 'pjActionMessages', 'pjActionExportFeed')))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
			}
		}
	}
	
	public function afterFilter()
	{
		parent::afterFilter();
		$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
	}
	
	public function beforeRender()
	{
		
	}
	public function pjActionTest()
	{
	    list($year, $month, $day) = explode("-", date("Y-n-j"));
	    $queryString = http_build_query(array(
	        'created' => array(
	            'gte' => mktime(0, 0, 0, $month, $day, $year),
	            'lte' => mktime(23, 59, 59, $month, $day, $year),
	        ),
	    ), null, '&');
	    
	    $http = new pjHttp();
	    
	    $http->setMethod("GET");
	    $url = "https://api.stripe.com/v1/events?" . $queryString;
	    
	    $http
	    ->addHeader("Authorization: Basic " . base64_encode($this->option_arr['o_stripe_secret_key'] . ":"))
	    ->curlRequest($url);
	    
	    $error = $http->getError();
	    if ($error)
	    {
	        echo 'error'; exit;
	    }
	    
	    if (method_exists($http, 'getHttpCode') && $http->getHttpCode() != 200)
	    {
	        return array('status' => 'ERR', 'code' => 101, 'text' => 'HTTP Code: ' . $http->getHttpCode());
	        echo 'HTTP Code: ' . $http->getHttpCode(); exit;
	    }
	    
	    $response = $http->getResponse();
	    $response = json_decode($response, true);
	    
	    $events = $response;
	    foreach ($events['data'] as $item)
	    {
	        if ($item['data']['object']['object'] == 'checkout.session')
	        {
	            
                echo '<pre>';
                print_r($item);
                echo '</pre>';
	           
	        }
	    }
	    /* echo '<pre>';
	    print_r($response);
	    echo '</pre>'; */
	    exit;
	}
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
		{
			$pjUserModel = pjUserModel::factory();
			$pjBookingModel = pjBookingModel::factory();
			$pjBookingSlotModel = pjBookingSlotModel::factory();
			$calendar_table = pjCalendarModel::factory()->getTable();
			
			$info_arr = pjAppModel::factory()
				->prepare(sprintf("SELECT 1,(SELECT COUNT(*) FROM `%2\$s` WHERE 1 LIMIT 1) AS `users`", 
					$pjBookingSlotModel->getTable(),
					$pjUserModel->getTable()
				))
				->exec()
				->getData();
			$cond = '';
			if ($this->isOwner()) {
				$cond = sprintf("AND TB.calendar_id IN(SELECT TC.id FROM `%2\$s` AS `TC` WHERE `TC`.user_id=%1\$u)", $this->getUserId(), $calendar_table);
			}
			$today_arr = $pjBookingSlotModel
			->where(sprintf("`booking_date` = CURDATE() AND `booking_id` IN (SELECT TB.id FROM `%1\$s` AS TB WHERE (TB.booking_status='pending' OR TB.booking_status='confirmed') $cond)", $pjBookingModel->getTable()))->findAll()->getDataPair("booking_id", "booking_id");
			$week_arr = $pjBookingSlotModel
			->reset()
			->where(sprintf("WEEKOFYEAR(`booking_date`) = WEEKOFYEAR(CURDATE()) AND `booking_id` IN (SELECT TB.id FROM `%1\$s` AS TB WHERE (TB.booking_status='pending' OR TB.booking_status='confirmed') $cond)", $pjBookingModel->getTable()))
			->findAll()
			->getDataPair("booking_id", "booking_id");
			
			$user_arr = $pjUserModel
				->orderBy('t1.last_login DESC')
				->limit(5)
				->findAll()
				->getData();
				
			if($this->isOwner())
			{
			    $pjBookingModel->where(sprintf("(t1.calendar_id IN(SELECT `TC`.id FROM `%s` AS `TC` WHERE `TC`.user_id=%u) )", $calendar_table, $this->getUserId()));
			}
			$latest_arr = $pjBookingModel
				->select('t1.*, t2.content as calendar')
				->join('pjMultiLang', "t2.model='pjCalendar' AND t2.foreign_id=t1.calendar_id AND t2.field='title' AND t2.locale='".$this->getLocaleId()."'", 'left outer')
				->orderBy('t1.created DESC')
				->limit(5)
				->findAll()
				->getData();
			
			$pjBookingSlotModel = $pjBookingSlotModel->reset();
			if($this->isOwner())
			{
			    $pjBookingSlotModel->where(sprintf("(t2.calendar_id IN(SELECT `TC`.id FROM `%2\$s` AS `TC` WHERE `TC`.user_id=%1\$u))", $this->getUserId(), $calendar_table));
			}
			// $upcoming_arr = $pjBookingSlotModel
			// 	->select('t1.*, t2.customer_name')
			// 	->join('pjBooking', 't2.id=t1.booking_id', 'inner')
			// 	->where("(t1.booking_date = CURDATE())")
			// 	->groupBy('t1.booking_id, t1.booking_date')
			// 	->orderBy('t1.booking_date ASC, t1.start_ts ASC')
			// 	->limit(5)
			// 	->findAll()
			// 	->getData();
			$upcoming_arr = $pjBookingSlotModel
			->select('t1.*, t2.customer_name')
			->join('pjBooking', 't2.id=t1.booking_id', 'inner')
			->where("(t1.booking_date = CURDATE())")
			->groupBy('t1.id, t1.booking_id, t1.booking_date, t1.start_ts, t1.end_ts, t2.customer_name')
			->orderBy('t1.booking_date ASC, t1.start_ts ASC')
			->limit(5)
			->findAll()
			->getData();

				
			$this
				->set('info_arr', $info_arr)
				->set('today_arr', $today_arr)
				->set('week_arr', $week_arr)
				->set('user_arr', $user_arr)
				->set('latest_arr', $latest_arr)
				->set('upcoming_arr', $upcoming_arr);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionForgot()
	{
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['forgot_user']))
		{
			if (!isset($_POST['forgot_email']) || !pjValidation::pjActionNotEmpty($_POST['forgot_email']) || !pjValidation::pjActionEmail($_POST['forgot_email']))
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			}
			$pjUserModel = pjUserModel::factory();
			$user = $pjUserModel
				->where('t1.email', $_POST['forgot_email'])
				->limit(1)
				->findAll()
				->getData();
				
			if (count($user) != 1)
			{
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=AA10");
			} else {
				$user = $user[0];
				
				$Email = new pjEmail();
				$Email
					->setTo($user['email'])
					->setFrom($user['email'])
					->setSubject(__('emailForgotSubject', true));
				
				if ($this->option_arr['o_send_email'] == 'smtp')
				{
					$Email
						->setTransport('smtp')
						->setSmtpHost($this->option_arr['o_smtp_host'])
						->setSmtpPort($this->option_arr['o_smtp_port'])
						->setSmtpUser($this->option_arr['o_smtp_user'])
						->setSmtpPass($this->option_arr['o_smtp_pass'])
					;
				}
				
				$body = str_replace(
					array('{Name}', '{Password}'),
					array($user['name'], $user['password']),
					__('emailForgotBody', true)
				);

				if ($Email->send($body))
				{
					$err = "AA11";
				} else {
					$err = "AA12";
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionForgot&err=$err");
			}
		} else {
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}
	
	public function pjActionMessages()
	{
		$this->setAjax(true);
		header("Content-Type: text/javascript; charset=utf-8");
	}
	
	public function pjActionLogin00()
	{
		
		$this->setLayout('pjActionAdminLogin');
		
		if (isset($_POST['login_user']))
		{
			if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
				!pjValidation::pjActionEmail($_POST['login_email']))
			{
				// Data not validate
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
			}
			$pjUserModel = pjUserModel::factory();

			$user = $pjUserModel
				->where(sprintf("t1.email = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeStr($_POST['login_email']), PJ_SALT))
				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeStr($_POST['login_password']), PJ_SALT))
				->limit(1)
				->findAll()
				->getData();

			if (count($user) != 1)
			{
				# Login failed
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
			} else {
				$user = $user[0];
				if ($user['locked'] == 'T')
				{
					# Login forbidden
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=8");
				}
				if ($user['password'] != $_POST['login_password']) {
					if ($user['role_id'] == 1) {
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=5");
					} else {
						if ((int)$user['cnt_login_fails'] < 2) {
							$err = 6;
						} else {
							$err = 7;
						}
						$data = array();
						$data['cnt_login_fails'] = (int)$user['cnt_login_fails'] + 1;
						$data['last_login_fails'] = date('Y-m-d H:i:s');
						if ($data['cnt_login_fails'] == 3) {
							$data['locked'] = 'T';
						}
						$pjUserModel->reset()->set('id', $user['id'])->modify($data);
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=".$err);
					}
				}
				
				unset($user['password']);
															
				if (!in_array($user['role_id'], array(1,2,3)))
				{
					# Login denied
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
				}				
				if ($user['status'] != 'T')
				{
					# Login forbidden
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=3");
				}
				if ($user['locked'] == 'T')
				{
					# Login forbidden
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=8");
				}
			
				# Login succeed
				$last_login = date("Y-m-d H:i:s");
    			$_SESSION[$this->defaultUser] = $user;
    			
    			# Update
    			$data = array();
    			$data['last_login'] = $last_login;
    			$data['cnt_login_fails'] = 0;
    			$pjUserModel->reset()->set('id', $user['id'])->modify($data);

				$calendar = pjCalendarModel::factory()->where('t1.user_id', $user['id'])->limit(1)->findAll()->getDataPair(NULL, 'id');
    			if (count($calendar) === 1)
    			{
    				$this->setForeignId($calendar[0]);
    			}
				
    			if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
    			{ pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
    			}
			}
		} else {
			$this->set('admin_email', $this->getAdminEmail());
			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
			$this->appendJs('pjAdmin.js');
		}
	}

	// public function pjActionLogin()
	// 	{ 
	// 		$this->setLayout('pjActionAdminLogin');

	// 		if (isset($_POST['login_user'])) {
	// 			if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
	// 			!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
	// 			!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
	// 			!pjValidation::pjActionEmail($_POST['login_email']))
	// 			{
	// 				// Data not validate
	// 				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
	// 			}
	// 			$pjUserModel = pjUserModel::factory();

	// 			$user = $pjUserModel
	// 				->where(sprintf("t1.email = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeStr($_POST['login_email']), PJ_SALT))
	// 				->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeStr($_POST['login_password']), PJ_SALT))
	// 				->limit(1)
	// 				->findAll()
	// 				->getData();

	// 			if (count($user) != 1) {
					
	// 				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
	// 			} else {

				
	// 				$user = $user[0];

	// 				if ($user['locked'] == 'T') {
	// 					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=8");
	// 				}
	// 				if ($user['password'] != $_POST['login_password']) {
	// 					if ($user['role_id'] == 1) {
	// 						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=5");
	// 					} else {
	// 						if ((int)$user['cnt_login_fails'] < 2) {
	// 							$err = 6;
	// 						} else {
	// 							$err = 7;
	// 						}
	// 						$data = array();
	// 						$data['cnt_login_fails'] = (int)$user['cnt_login_fails'] + 1;
	// 						$data['last_login_fails'] = date('Y-m-d H:i:s');
	// 						if ($data['cnt_login_fails'] == 3) {
	// 							$data['locked'] = 'T';
	// 						}
	// 						$pjUserModel->reset()->set('id', $user['id'])->modify($data);
	// 						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=".$err);
	// 					}
	// 				}
					
	// 				unset($user['password']);

	// 				if (!in_array($user['role_id'], array(1,2,3)))
	// 				{
	// 					# Login denied
	// 					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
	// 				}				
	// 				if ($user['status'] != 'T')
	// 				{
	// 					# Login forbidden
	// 					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=3");
	// 				}
	// 				if ($user['locked'] == 'T')
	// 				{
	// 					# Login forbidden
	// 					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=8");
	// 				}
					
					
	// 				// If 2FA is not enabled, proceed with normal login
	// 					if ($user['2FA_status'] == 'T') 
	// 					{
	// 						// Generate 2FA token
	// 						$token = random_int(100000, 999999);
	// 						$expiry = date('Y-m-d H:i:s', time() + 300); // Token expires in 5 minutes

	// 						// Save token to database
	// 						$pjUserModel->reset()->set('id', $user['id'])->modify([
	// 							'two_factor_token' => $token,
	// 							'two_factor_token_expiry' => $expiry
	// 						]);

	// 						// Send 2FA email
	// 						//$this->send2FAEmail($user['email'], $token);
							
	// 						// Redirect to 2FA verification page
	// 						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionVerify2FA");
							
	// 					} 
	// 					else 
	// 					{
	// 						$last_login = date("Y-m-d H:i:s");
	// 						$_SESSION[$this->defaultUser] = $user;
	// 						$data = [
	// 							'last_login' => $last_login,
	// 							'cnt_login_fails' => 0
	// 						];
	// 						$pjUserModel->reset()->set('id', $user['id'])->modify($data);
	// 						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");

	// 					}				

	// 			}
	// 		} else {
	// 			$this->set('admin_email', $this->getAdminEmail());
	// 			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
	// 			$this->appendJs('pjAdmin.js');
	// 		}
	// 	}

	// private function send2FAEmail($email, $token)
	// 	{
	// 		$link = PJ_INSTALL_URL . "?controller=pjAdmin&action=pjActionVerify2FA&token=$token";
	// 		$subject = "Your Two-Factor Authentication Code";
	// 		$body = "Click the link below to complete your login:\n\n$link";
		
	// 		// Check if email was sent
	// 		$isSent = mail($email, $subject, $body); // Replace with PHPMailer for production
		
	// 		if ($isSent) {
				
	// 			return true; // Email sent successfully
	// 		} else {
				
	// 			error_log("Failed to send 2FA email to $email"); // Log the error for debugging
	// 			return false; // Email sending failed
	// 		}
			
	// 	}
		
	// public function pjActionVerify2FA()
	// 	{   
	// 		$this->setLayout('pjActionAdminLogin');
			
	// 		if (isset($_POST['2FA_token'])) {
	// 			$token = $_POST['login_token'];
	// 			$pjUserModel = pjUserModel::factory();
		
	// 			$user = $pjUserModel
	// 				->where('two_factor_token', $token)
	// 				->where('two_factor_token_expiry > NOW()')
	// 				->limit(1)
	// 				->findAll()
	// 				->getData();
					
	// 				if (count($user) != 1) {
					
	// 					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionVerify2FA&err=9");

	// 				} else {
	// 				$user = $user[0];
		
	// 				# Login succeed
	// 				$last_login = date("Y-m-d H:i:s");
	// 				$_SESSION[$this->defaultUser] = $user;
					
	// 				# Update
	// 				$data = array();
	// 				$data['last_login'] = $last_login;
	// 				$data['cnt_login_fails'] = 0;
	// 				$data['two_factor_token'] = 'null';
	// 				$data['two_factor_token_expiry'] = '1970-01-01 00:00:00';
					
	// 				$pjUserModel->reset()->set('id', $user['id'])->modify($data);

	// 				$calendar = pjCalendarModel::factory()->where('t1.user_id', $user['id'])->limit(1)->findAll()->getDataPair(NULL, 'id');
	// 				if (count($calendar) === 1)
	// 				{
	// 					$this->setForeignId($calendar[0]);
	// 				}
					
	// 				if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
	// 				{
	// 					 pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
	// 				}
	// 			}
	// 		} else {
	// 			$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
	// 			$this->appendJs('pjAdmin.js');
	// 		}
	// 	}
		public function pjActionLogin()
		{ 
			$this->setLayout('pjActionAdminLogin');
			if (isset($_POST['login_user'])) {

				// Trim and validate email and password
				$email = trim($_POST['login_email']);
				$password = trim($_POST['login_password']);
				// Optional: Username validation (if used instead of email)
				// if (isset($_POST['login_email'])) {
				// 	$raw_uname = trim($_POST['login_email']);
				// 	if (!preg_match('/^[A-Za-z0-9_ ]{3,30}$/', $raw_uname)) {
				// 	pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&error1");
				// 	}
				// }

				if (!isset($_POST['login_email']) || !isset($_POST['login_password']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_email']) ||
				!pjValidation::pjActionNotEmpty($_POST['login_password']) ||
				!pjValidation::pjActionEmail($_POST['login_email']))
				{
					// Data not validate
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
				}
				$pjUserModel = pjUserModel::factory();

				$user = $pjUserModel
					->where(sprintf("t1.email = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeStr($_POST['login_email']), PJ_SALT))
					->where(sprintf("t1.password = AES_ENCRYPT('%s', '%s')", $pjUserModel->escapeStr($_POST['login_password']), PJ_SALT))
					->limit(1)
					->findAll()
					->getData();

				if (count($user) != 1) {
					
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=4");
				} else {

				
					$user = $user[0];

					if ($user['locked'] == 'T') {
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=8");
					}
					if ($user['password'] != $_POST['login_password']) {
						if ($user['role_id'] == 1) {
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=5");
						} else {
							if ((int)$user['cnt_login_fails'] < 2) {
								$err = 6;
							} else {
								$err = 7;
							}
							$data = array();
							$data['cnt_login_fails'] = (int)$user['cnt_login_fails'] + 1;
							$data['last_login_fails'] = date('Y-m-d H:i:s');
							if ($data['cnt_login_fails'] == 3) {
								$data['locked'] = 'T';
							}
							$pjUserModel->reset()->set('id', $user['id'])->modify($data);
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=".$err);
						}
					}
					
					unset($user['password']);

					if (!in_array($user['role_id'], array(1,2,3)))
					{
						# Login denied
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=2");
					}				
					if ($user['status'] != 'T')
					{
						# Login forbidden
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=3");
					}
					if ($user['locked'] == 'T')
					{
						# Login forbidden
						pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=8");
					}
					
					// If 2FA is not enabled, proceed with normal login
						if ($user['2FA_status'] == 'T') 
						{
							// Generate 2FA token
							$token = random_int(100000, 999999);
							$expiry = date('Y-m-d H:i:s', time() + 300); // Token expires in 5 minutes

							// Save token to database
							$pjUserModel->reset()->set('id', $user['id'])->modify([
								'two_factor_token' => $token,
								'two_factor_token_expiry' => $expiry
							]);

							$_SESSION['2FA_user_email'] = $user['email'];
							$_SESSION['additional_email'] = $user['additional_email'];

							// Send 2FA email
							
							$this->send2FAEmail($user['email'], $token);
						
							if (!empty($user['additional_email'])) {
								$additionalEmails = explode(',', $user['additional_email']);
								
								foreach ($additionalEmails as $email) {
									$trimmedEmail = trim($email); // Remove any extra spaces
									if (!empty($trimmedEmail)) {
										$this->send2FAEmail($trimmedEmail, $token);
									}
								}
							}
							
							// Redirect to 2FA verification page
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionVerify2FA");
							
						} 
						else 
						{
							$last_login = date("Y-m-d H:i:s");
							$_SESSION[$this->defaultUser] = $user;
							$data = [
								'last_login' => $last_login,
								'cnt_login_fails' => 0
							];
							$pjUserModel->reset()->set('id', $user['id'])->modify($data);
							pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");

						}				

				}
			} else {
				$this->set('admin_email', $this->getAdminEmail());
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdmin.js');
			}
		}
		
	private function send2FAEmail($email, $token)
		{
			$link = PJ_INSTALL_URL . "?controller=pjAdmin&action=pjActionVerify2FA&token=$token";
			$subject = "Your Two-Factor Authentication Code";
			$body = "Click the link below to complete your login:\n\n$link";
			// Check if email was sent
			$isSent = mail($email, $subject, $body); // Replace with PHPMailer for production
			if ($isSent) {
				return true; // Email sent successfully
			} else {
				error_log("Failed to send 2FA email to $email"); // Log the error for debugging
				return false; // Email sending failed
			}
		}


	private function user2FAEmail($email)
	    {
			return $email;
		}	
	public function pjActionVerify2FA()
		{   
		   // echo "<pre>"; print_r($_POST); 	echo "</pre>";  echo "<pre>";   print_r($_GET); echo "</pre>"; echo "<pre>";  print_r($_REQUEST);  die('2fa');
		    
			$this->setLayout('pjActionAdminLogin');
			 // Retrieve email from session if available
			 if (isset($_SESSION['2FA_user_email'])) {
				$userEmail = $this->user2FAEmail($_SESSION['2FA_user_email']);
				$this->set('useremail', $userEmail);
			}
			
			if (isset($_GET['token'])) {
				$token = $_GET['token'];
				$pjUserModel = pjUserModel::factory();
		
				$user = $pjUserModel
					->where('two_factor_token', $token)
					->where('two_factor_token_expiry > NOW()')
					->limit(1)
					->findAll()
					->getData();
					
					if (count($user) != 1) {
					    
					   pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin&err=8");
						//pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionVerify2FA&err=9");

					} else {
					$user = $user[0];
					unset($_SESSION['2FA_user_email']);
					# Login succeed
					$last_login = date("Y-m-d H:i:s");
					$_SESSION[$this->defaultUser] = $user;
					
					# Update
					$data = array();
					$data['last_login'] = $last_login;
					$data['cnt_login_fails'] = 0;
					$data['two_factor_token'] = 'null';
					$data['two_factor_token_expiry'] = '1970-01-01 00:00:00';
					
					$pjUserModel->reset()->set('id', $user['id'])->modify($data);

					$calendar = pjCalendarModel::factory()->where('t1.user_id', $user['id'])->limit(1)->findAll()->getDataPair(NULL, 'id');
					if (count($calendar) === 1)
					{
						$this->setForeignId($calendar[0]);
					}
					
					if ($this->isAdmin() || $this->isEditor() || $this->isOwner())
					{
						 pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionIndex");
					}
				}
			} else {
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdmin.js');
			}
		}

	public function pjActionLogout()
	{
		if ($this->isLoged())
        {
        	unset($_SESSION[$this->defaultUser]);
        }
       	pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionLogin");
	}
	
	public function pjActionProfile()
	{
		$this->checkLogin();
		
		if (!$this->isAdmin())
		{
			if (isset($_POST['profile_update']))
			{
				$pjUserModel = pjUserModel::factory();
				$arr = $pjUserModel->find($this->getUserId())->getData();
				$data = array();
				$data['role_id'] = $arr['role_id'];
				$data['status'] = $arr['status'];
				$post = array_merge($_POST, $data);
				if (!$pjUserModel->validates($post))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA14");
				}
				$pjUserModel->set('id', $this->getUserId())->modify($post);
				
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdmin&action=pjActionProfile&err=AA13");
			} else {
				$this->set('arr', pjUserModel::factory()->find($this->getUserId())->getData());
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdmin.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionRedirect()
	{
		if (isset($_GET['calendar_id']) && (int) $_GET['calendar_id'] > 0)
		{
			if ((int) pjCalendarModel::factory()->where('t1.id', $_GET['calendar_id'])->findCount()->getData() == 1)
			{
				$this->setForeignId($_GET['calendar_id']);
			}
		}
		
		$qs = NULL;
		if (isset($_GET['nextParams']) && !empty($_GET['nextParams']))
		{
			parse_str($_GET['nextParams'], $params);
			if (!empty($params))
			{
				$qs = http_build_query($params);
				$qs = "&" . $qs;
			}
		}

		pjUtil::redirect(sprintf("%sindex.php?controller=%s&action=%s%s", PJ_INSTALL_URL, $_GET['nextController'], $_GET['nextAction'], $qs));
		exit;
	}

	protected function getSlots($calendar_id, $iso_date, $hash=NULL)
	{
		$t_arr = pjAppController::getDailySlots($calendar_id, $iso_date, $this->option_arr);
		if ($t_arr['is_dayoff'] == 'T')
		{
			# It's Day off
			$this->set('dayoff', true);
			return;
		}
		
		$this->set('price_arr', pjAppController::getPricesDate($calendar_id, $iso_date, $this->option_arr));
		
		$pjBookingSlotModel = pjBookingSlotModel::factory();
		
		# Get booked slots for given date.
		# If 24h, include next date
		$d_arr = array($pjBookingSlotModel->escapeStr($iso_date));
		if ($t_arr['end_ts'] < $t_arr['start_ts'])
		{
			$d_arr[] = date("Y-m-d", strtotime($iso_date) + 86400);
		}
		
		$bs_arr = $pjBookingSlotModel
			->join('pjBooking', sprintf("t2.id=t1.booking_id AND t2.calendar_id='%u' AND t2.booking_status IN ('pending', 'confirmed')", $calendar_id), 'inner')
			->whereIn('t1.booking_date', $d_arr)
			->where('t2.booking_status !=', 'cancelled')
			->findAll()
			->getData();
		
		$_arr = array();
		if (isset($hash) && !empty($hash) &&
			isset($_SESSION[$this->adminBooking]) && isset($_SESSION[$this->adminBooking][$hash])
		)
		{
			foreach ($_SESSION[$this->adminBooking][$hash] as $key => $slot)
			{
				if ($slot['booking_date'] == $iso_date)
				{
					$_arr[] = $slot;
				}
			}
		}
		
		$bs_arr = array_merge($bs_arr, $_arr);
		
		$this->set('bs_arr', $bs_arr);
		$this->set('t_arr', $t_arr);
	}
}
?>