<?php
/*----------------------------------------------------------------------------------|  www.vdm.io  |----/
				fdsh 
/-------------------------------------------------------------------------------------------------------/

	@version		1.0.39
	@build			4th April, 2023
	@created		17th December, 2020
	@package		Reservation
	@subpackage		login.php
	@author			farhad shahbazi <http://farhad.com>	
	@copyright		Copyright (C) 2015. All Rights Reserved
	@license		GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
  ____  _____  _____  __  __  __      __       ___  _____  __  __  ____  _____  _  _  ____  _  _  ____ 
 (_  _)(  _  )(  _  )(  \/  )(  )    /__\     / __)(  _  )(  \/  )(  _ \(  _  )( \( )( ___)( \( )(_  _)
.-_)(   )(_)(  )(_)(  )    (  )(__  /(__)\   ( (__  )(_)(  )    (  )___/ )(_)(  )  (  )__)  )  (   )(  
\____) (_____)(_____)(_/\/\_)(____)(__)(__)   \___)(_____)(_/\/\_)(__)  (_____)(_)\_)(____)(_)\_) (__) 

/------------------------------------------------------------------------------------------------------*/

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

use Joomla\Utilities\ArrayHelper;

/**
 * Reservation Login Controller
 */
class ReservationControllerLogin extends JControllerForm
{
	/**
	 * Current or most recently performed task.
	 *
	 * @var    string
	 * @since  12.2
	 * @note   Replaces _task.
	 */
	protected $task;

	public function __construct($config = array())
	{
		$this->view_list = 'login'; // safeguard for setting the return view listing to the default site view.
		parent::__construct($config);
	}


/***[JCBGUI.site_view.php_controller.43.$$$$]***/
  public function loginRegister()
  {

    $app = JFactory::getApplication();
    $phoneNumber = $app->input->get('phonenumber', 0);
    $uri = (string)JUri::getInstance();

    $info= [
      'phonenumber' => $phoneNumber,
      'userExist' => false,
      'table' => false,
      'validate' => false
    ];
    $app->setUserState('info',$info );

    Joomla\CMS\Form\Form::addRulePath('administrator/components/com_reservation/models/rules');
    $xml = new SimpleXMLElement('<field name="phonenumber" validate="mobile"/>');
    $rule = JFormHelper::loadRuleType('mobile');
    $validate = $rule->test($xml, $phoneNumber);

    if (!$validate) {
      $app->enqueueMessage('شماره موبایل معتبر وارد نمایید', 'warning');
      $app->redirect($uri);
    }




    //    $view = $this->getView('login', 'html');
    $model= $this->getModel();
    list($userExist, $table)= $model->userExist($phoneNumber);
    // $userExist= $model->userExist($phoneNumber)[0];
    // $table= $model->userExist($phoneNumber)[1];

    $info= [
      'phonenumber' => $phoneNumber,
      'userExist' => $userExist,
      'table' => $table,
      'validate' => $validate,
    ];
    $app->setUserState('info',$info );


    if(!$userExist)
    {
      ReservationHelper::setExpireTime();
      $verify= ReservationHelper::setVerifyCode();


      \JPluginHelper::importPlugin('ejra');
      $dispatcher = \JEventDispatcher::getInstance();
      $dispatcher->trigger('onAfterMobileValidate',array($phoneNumber, $verify));
      $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_register',false));
    }
    else
    {
      $app->setUserState('loginWith', 'password');
      $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_password',false));
    }


  }
  public function register()
  {
    $app= JFactory::getApplication();
    $data= $app->input->get('jform',array(),'array');

    $info= $app->getUserState('info');
    if (!$info['phonenumber'] || !$info['validate'] || $info['userExist'] || !JFactory::getUser()->guest)
      $app->redirect(JRoute::_('index.php?option=com_reservation&view=login',false));

    $app->setUserState('owner.data',$data);

    $xml = new SimpleXMLElement('<field name="password" type="text" required="true" validate="password" minimum_length="4" message="رمز عبور حداقل باید 4 کاراکتر باشد" />');
    $rule = JFormHelper::loadRuleType('password');
    $validate = $rule->test($xml, $data['password']);



    if (empty($data['name']) || !$validate)
    {
      $app->enqueueMessage('اطلاعات خود را به درستی وارد نمایید','warning');
      $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_register',false));
    }

    date_default_timezone_set('asia/tehran');
    $verify= $app->getUserState('verify');
    $expire= $app->getUserState('expire');


    if (strtotime($expire) < time())
    {
      $app->enqueueMessage('زمان کد تایید به پایان رسیده لطفا بر روی ارسال مجدد کد کلیک نمایید','warning');
      $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_register',false));
    }


    if ($data['verify'] != $verify)
    {
      $app->enqueueMessage('کد تایید را به درستی وارد کنید','warning');
      $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_register',false));
    }




    $userdata = array(
      "name"=> $data['name'],
      "username"=> $info['phonenumber'],
      "password"=> $data['password'],
      "password2"=> $data['password'],
      "email"=> 'E_'.$info['phonenumber'].'@gmail.com',
      "block"=> 0,
    );


    jimport('joomla.user.helper');
    $params= $app->getparams('com_Reservation');

    //       $userGroup= $params->get('ownerrgroup');
    $userGroup= 2;



    // if(!isset($userGroup))
    // $userGroup = 2;

    // $userdata["groups"] = [$userGroup];
    // $user = new JUser;


    // if(!$user->bind($userdata)) {
    // $app->enqueueMessage($user->getError(), 'warning');
    // $app->redirect(JRoute::_('index.php?option=com_Reservation&view=login',false));
    // }

    // if (!$user->save()) {
    // $app->enqueueMessage($user->getError(), 'warning');
    // $app->redirect(JRoute::_('index.php?option=com_Reservation&view=login',false));
    // }



    if ( ( ! file_exists( JPATH_SITE . '/libraries/CBLib/CBLib/Core/CBLib.php' ) ) || ( ! file_exists( JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php' ) ) ) {
      echo 'CB not installed';
      return;
    }

    include_once( JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php' );
    cbimport( 'cb.html' );
    global $_CB_framework, $_PLUGINS, $ueConfig;
    $_PLUGINS->loadPluginGroup($data["username"]); // for using cb trigering
    jimport('joomla.user.helper');
    $post = isset($data["post"]) ? $data["post"] : $data;
    $post["name"] = $post["firstname"] . " " . $post["lastname"];



    $_PLUGINS->loadPluginGroup( 'user' );

    $user					=	new \CB\Database\Table\UserTable();
    $user->set( 'username', $userdata['username'] );
    $user->set( 'email', $userdata["email"] );
    // /* $user->set( 'firstName', $post["firstname"] );*/
    // /* $user->set( 'lastName', $post["lastname"] );*/
    $user->set( 'name', $userdata['name'] );
    $user->set( 'gids', array($userGroup) );
    $user->set( 'sendEmail', 0 );
    $user->set( 'registerDate', $_CB_framework->getUTCDate() );
    $user->set( 'password', $user->hashAndSaltPassword($userdata["password"]) );
    $user->set( 'approved', 1 );
    $user->set( 'confirmed', 1 );
    $user->set( 'block', 0 );

    if ( $user->store() ) {
      if ( $user->get( 'confirmed' ) == 0 ) {
        $user->store();
      }
    }
    // dump($user, 'user');
    // dump($userdata, 'userdata');

    $userId= $user->id;

    $sickInfo= array(
      'userid'=> $userId,
      'phonenumber' => $info['phonenumber'],
    );


    JLoader::register('ReservationModelSick', JPATH_COMPONENT_ADMINISTRATOR.'/models/sick.php');
    $sickModel= new ReservationModelSick();
    if(!$sickModel->save($sickInfo))
    {
      $app->enqueueMessage('اطلاعات خود را تصحیح کرده و سپس وارد نمایید', 'warning');
      $app->redirect(JRoute::_('index.php?option=com_Reservation&view=login',false));
    }
    $app->setUserState('info','');


    $credentials = array();
    $credentials['username'] = $info['phonenumber'];
    $credentials['password'] = $data['password'];
    $login_site = JFactory::getApplication('site');
    $login_site->login($credentials, $options=array());
    $redirect = JUri::root();
    $login_site->redirect($redirect);



  }

  public function resetExpireTime()
  {
    $app= JFactory::getApplication();
    $uri= (string)JUri::getInstance();
    $data= $app->input->get('jform',array(),'array');
    $app->setUserState('owner.data',$data);

    date_default_timezone_set('asia/tehran');
    $expire= $app->getUserState('expire');

    if (strtotime($expire) < time())
    {
      ReservationHelper::setExpireTime();
      $verify= ReservationHelper::setVerifyCode();
      $phoneNumber= $app->getUserState('info')['phonenumber'];


      \JPluginHelper::importPlugin('ejra');
      $dispatcher = \JEventDispatcher::getInstance();
      $dispatcher->trigger('onAfterMobileValidate',array($phoneNumber, $verify));
    }

    $app->redirect($uri);
  }
  public function login()
  {


    $app= JFactory::getApplication();
    $info= $app->getUserState('info');
    if (!$info['phonenumber'] || !$info['validate'] || !$info['userExist'] || !JFactory::getUser()->guest)
    {
      $this->app->redirect(JRoute::_('index.php?option=com_reservation&view=login',false));
    }

    $loginWith= $app->getUserState('loginWith');

    $phoneNumber= $app->getUserState('info')['phonenumber'];
    $data= $app->input->get('jform',array(),'array');

    $credentials = array();
    if ($loginWith== 'password')
    {


      $credentials['username'] = $phoneNumber;
      $credentials['password'] = $data['password'];
      $credentials['loginWith'] = 'password';
      $login_site = JFactory::getApplication('site');

    }
    elseif($loginWith== 'verifyCode')
    {

      date_default_timezone_set('asia/tehran');
      $verify= $app->getUserState('verify');
      $expire= $app->getUserState('expire');


      if (strtotime($expire) < time())
      {
        $app->enqueueMessage('زمان کد تایید به پایان رسیده لطفا بر روی ارسال مجدد کد کلیک نمایید','warning');
        $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_password',false));
      }


      if ($data['password'] != $verify)
      {
        $app->enqueueMessage('کد تایید را به درستی وارد کنید','warning');
        $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_password',false));
      }

      $model= $this->getModel();
      $table= $app->getUserState('info')['table'];
      $userid= $model->getUserId($table, $phoneNumber);

      $credentials['username'] = $phoneNumber;
      $credentials['password'] = $data['password'];
      $credentials['userid'] = $userid;
      $credentials['loginWith'] = 'verifyCode';
      $login_site = JFactory::getApplication('site');

    }

    $result= $login_site->login($credentials, $options=array());

    if(!$result)
      $login_site->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_password',false));


    $redirect = JUri::root();
    $app->redirect($redirect);
  }

  public function verifyCode()
  {
    $app= JFactory::getApplication();
    $app->setUserState('loginWith', 'verifyCode');

    ReservationHelper::setExpireTime();
    $verify= ReservationHelper::setVerifyCode();
    $phoneNumber= $app->getUserState('info')['phonenumber'];


    \JPluginHelper::importPlugin('ejra');
    $dispatcher = \JEventDispatcher::getInstance();
    $dispatcher->trigger('onAfterMobileValidate',array($phoneNumber, $verify));

    $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_password',false));
  }
  public function password()
  {
    $app= JFactory::getApplication();
    $app->setUserState('loginWith', 'password');
    $app->redirect(JRoute::_('index.php?option=com_reservation&view=login&layout=default_password',false));
  }
/***[/JCBGUI$$$$]***/


	/**
	 * Method to check if you can edit an existing record.
	 *
	 * Extended classes can override this if necessary.
	 *
	 * @param   array   $data  An array of input data.
	 * @param   string  $key   The name of the key for the primary key; default is id.
	 *
	 * @return  boolean
	 *
	 * @since   12.2
	 */
	protected function allowEdit($data = array(), $key = 'id')
	{
		// to insure no other tampering
		return false;
	}

        /**
	 * Method override to check if you can add a new record.
	 *
	 * @param   array  $data  An array of input data.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	protected function allowAdd($data = array())
	{
		// to insure no other tampering
		return false;
	}

	/**
	 * Method to check if you can save a new or existing record.
	 *
	 * Extended classes can override this if necessary.
	 *
	 * @param   array   $data  An array of input data.
	 * @param   string  $key   The name of the key for the primary key.
	 *
	 * @return  boolean
	 *
	 * @since   12.2
	 */
	protected function allowSave($data, $key = 'id')
	{
		// to insure no other tampering
		return false;
	}

	/**
	 * Function that allows child controller access to model data
	 * after the data has been saved.
	 *
	 * @param   JModelLegacy  $model      The data model object.
	 * @param   array         $validData  The validated data.
	 *
	 * @return  void
	 *
	 * @since   12.2
	 */
	protected function postSaveHook(JModelLegacy $model, $validData = array())
	{
	}
}
