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

	@version		1.0.39
	@build			4th April, 2023
	@created		17th December, 2020
	@package		Reservation
	@subpackage		firstqst.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 Firstqst Controller
 */
class ReservationControllerFirstqst 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.30.$$$$]***/
  public function save($key = NULL, $urlVar = NULL){
    $app = JFactory::getApplication();
    $input = $app->input;
    $firsttext = $input->get('chatMessage', '', 'string');
    $pid = $input->get('pid', 0);
    //    $uid = $app->input->get('uid', 0);

    $app->setUserState('first_chatMessage', $firsttext);
    //    $app->setUserState('pid', $pid);
    //    $app->setUserState('uid', $uid);


    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select('product_id');
    $query->from($db->quoteName('#__hikashop_product'));
    $query->where($db->quoteName('product_code') . '= "reserve' . $pid.'"');

    $db->setQuery($query);
    $product_id = $db->loadResult();


    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select('id');
    $query->from($db->quoteName('#__reservation_sick'));
    $query->where($db->quoteName('userid') . '=' . $db->quote(JFactory::getUser()->id));
    $db->setQuery($query);
    $sick_id = $db->loadResult();



    JLoader::register('ReservationModelSession', JPATH_ADMINISTRATOR.'/components/com_reservation/models/session.php');
    $data = array(
      'sickid'        => $sick_id,
      'planid'        => $pid,
      'firsttext'     => $firsttext,
      'channel_token' =>  JUserHelper::genRandomPassword(16)
    );

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select(array('id', 'channel_token'));
    $query->from($db->quoteName('#__reservation_session'));
    $query->where($db->quoteName('planid') . '=' . $db->quote($pid));
    $query->where($db->quoteName('sickid') . '=' . $db->quote($sick_id));
    $query->where($db->quoteName('published') . '= 1');
    $db->setQuery($query);
    $session = $db->loadAssoc();
    if($session)
    {
      $data['id'] = $session['id'];
      $data['channel_token'] = $session['channel_token'];
    }

    $session_model = new ReservationModelSession();
    $session_model->save($data);

    //            $app->redirect(JRoute::_('index.php?option=com_reservation&view=payment&seid='.$sessionId));
    $app->redirect(JRoute::_('index.php?option=com_hikashop&ctrl=product&task=show&cid=' . $product_id));




  }

  public function createSession($pid)
  {
    require_once JPATH_SITE.'/components/com_reservation/helpers/reservation.php';
    $app= JFactory::getApplication();
    $firsttext= $app->getUserState('first_chatMessage',0,'string');
    //        $pid= $app->getUserState('pid',0);
    //        $uid= $app->getUserState('uid',0);
    $user_id= JFactory::getUser()->get('id',0);
    //$consultantid= ReservationHelper::exist('#__reservation_consultant', 'userid', JFactory::getUser()->get('id', 0));

    if (!$user_id)
    {
      $app->enqueueMessage('برای رزرو نوبت مشاوره وارد حساب کاربری مخصوص کاربران عادی خود شوید','warning');
      $app->redirect(JUri::root());
    }

    //        if (!$pid || !$uid)
    //        {
    //            $app->enqueueMessage('مراحل خرید به درستی طی نشده است ، لطفا مراحل را مجدد تکرار کنید','warning');
    //            $app->redirect(JUri::root());
    //        }


    $db = JFactory::getDbo();
    $query= $db->getQuery(true)
      ->select('s.id')
      ->from($db->quoteName('#__reservation_sick','s'))
      ->where($db->quoteName('s.userid').'='.$user_id);

    $db->setQuery($query);
    $res= $db->loadObject();


    //        $db = JFactory::getDbo();
    //        $query= $db->getQuery(true)
    //            ->select('c.id')
    //            ->from($db->quoteName('#__reservation_consultant','c'))
    //            ->where($db->quoteName('c.userid').'='.$uid)
    //            ->where('('.$db->quoteName('c.account').'='.$db->quote('consultant').' or '.$db->quoteName('c.account').'='.$db->quote('both').')');
    //
    //        $db->setQuery($query);
    //
    //        $res2= $db->loadObject();


    if(empty($res)) {
      $app->enqueueMessage('برای رزرو نوبت مشاوره وارد حساب کاربری مخصوص کاربران عادی خود شوید','warning');
      JFactory::getApplication()->redirect(JUri::root());
    }

    $sickid = (int)$res->id;
    //        $cid = (int)$res2->id;
    //
    //
    //        $db = JFactory::getDbo();
    //        $query= $db->getQuery(true)
    //            ->select('p.id')
    //            ->from($db->quoteName('#__reservation_plan','p'))
    //            ->where($db->quoteName('p.id').'='.$pid)
    //            ->where($db->quoteName('p.consultantid').'='.$db->quote($cid));
    //
    //        $db->setQuery($query);
    //        $res= $db->loadObject();
    //
    //        if (empty($res)) {
    //
    //            $app->enqueueMessage('از پارامتر های معتبر استفاده کنید','warning');
    //            JFactory::getApplication()->redirect(JUri::root());
    //        }


    $data= [
      'firsttext'=> $firsttext,
      'planid'=> $pid,
      'sickid'=> $sickid,
      'pay' => 0,
      'finish' => 0
    ];

    require_once JPATH_ADMINISTRATOR.'/components/com_reservation/models/session.php';

    $adminSessionModel= new ReservationModelSession;

    if (!$adminSessionModel->save($data))
    {
      $app->enqueueMessage('از پارامتر های معتبر استفاده کنید','warning');
      JFactory::getApplication()->redirect(JUri::root());
    }

    $sessionId=$adminSessionModel->getState('session.id');
    return $sessionId;
  }/***[/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())
	{
	}
}
