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

	@version		1.0.39
	@build			4th April, 2023
	@created		17th December, 2020
	@package		Reservation
	@subpackage		ajax.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 Ajax Model
 */
class ReservationModelAjax extends JModelList
{
	protected $app_params;

	public function __construct()
	{
		parent::__construct();
		// get params
		$this->app_params = JComponentHelper::getParams('com_reservation');

	}

	// Used in messages

/***[JCBGUI.site_view.php_ajaxmethod.26.$$$$]***/
  public function deleteChat($mid)
  {
    $userid= JFactory::getUser()->get('id');

    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->select($db->quoteName(array('from')));
    $query->from($db->quoteName('#__reservation_message'));
    $query->where($db->quoteName('id') . ' = ' . $db->quote($mid));
    $db->setQuery($query);
    $from = $db->loadResult();

    if($from == $userid)
    {
      JLoader::register('ReservationModelMessage', JPATH_ADMINISTRATOR . '/components/com_reservation/models/message.php');
      JLoader::register('ReservationTableMessage', JPATH_ADMINISTRATOR . '/components/com_reservation/tables/message.php');


      $db = JFactory::getDbo();
      $msgmodel = new ReservationTableMessage($db);
      $pkco = array(
        'id' => $mid
      );
      $msgmodel->publish($pkco, -2);
    }
    return array('result' => ($from == $userid) );


  }
  public function saveChat($message, $from, $to, $seid, $pid, $replyId, $pmid)
  {

    $uid= $to;
    $userid= JFactory::getUser()->get('id'); // or $from

    // Trigger the beforeChat (chatterAuth) event.
    \JPluginHelper::importPlugin('chat');
    $dispatcher = \JEventDispatcher::getInstance();
    $dispatcher->trigger('beforeChat',array($uid, $pid, $userid, $seid));


    $db = JFactory::getDbo();
    $query = $db->getQuery(true)
      ->select('finish ,channel_token')
      ->from($db->quoteName('#__reservation_session','se'))
      ->where($db->quoteName('se.id').'='.$seid);

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


    if($result->finish == 1){
      throw new Exception('access denied', 403);
    }


    JLoader::register('ReservationModelMessage',JPATH_COMPONENT_ADMINISTRATOR.'/models/message.php');
    $data = ['message' => $message, 'from' => $from, 'to' => $to, 'channel_token' => $result->channel_token, 'reply' => $replyId];
    if($pmid != 0)
    {
      $data['pmid'] = $pmid;
    }




    date_default_timezone_set('asia/tehran');
    $created= date('Y-m-d H:i:s');
    $created_by= JFactory::getUser()->get('id');

    $data2= ['message' => $message, 'from' => $from, 'to' => $to,'created' => $created,'created_by' => $created_by,'seid' => $seid, 'seen' => 1, 'reply' => $replyId];
    if($pmid != 0)
    {
      $data2['id'] = $pmid;
    }
    $filename = __DIR__ . '/savechat.txt';
    file_put_contents($filename, 'data2 = ' . print_r($data2, True) . "\n", FILE_APPEND);

    $adminMessageModel= new ReservationModelMessage();
    $adminMessageModel->save($data2);
    $item = $adminMessageModel->getItem();
    $data['id'] = $item->id;
    // Trigger the after save event.
    \JPluginHelper::importPlugin('chat');
    $dispatcher = \JEventDispatcher::getInstance();
    $dispatcher->trigger('afterChatSave', array($data));


    return $data;
  }

  public function conversation($user1, $user2,$seid,$pid)
  {



    $app= JFactory::getApplication();
    $uid= $user2;
    $userid= JFactory::getUser()->get('id', 0); // or $user1

    // Trigger the beforeChat (chatterAuth) event.
    //                \JPluginHelper::importPlugin('chat');
    //                $dispatcher = \JEventDispatcher::getInstance();
    //                $dispatcher->trigger('beforeChat',array($uid, $pid, $userid, $seid));

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

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

    if(empty($result))
    {
      throw new Exception('access denied', 403);
    }


    $query = $db->getQuery(true)
      ->select($db->quoteName(array('se.id','se.finish')))
      ->from($db->quoteName('#__reservation_session','se'))
      ->join('inner',$db->quoteName('#__reservation_plan','p').'on'. $db->quoteName('se.planid').'='.$db->quoteName('p.id'))
      ->where($db->quoteName('p.consultantid').'='.$result->id)
      ->where($db->quoteName('se.id').'='.$seid);

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

    if(empty($result))
    {
      throw new Exception('access denied', 403);
    }


    $object = new stdClass();
    $object->id = $seid;
    $object->finish = $result->finish?0:1;

    $result = JFactory::getDbo()->updateObject('#__reservation_session', $object, 'id', null);

    if(!$result)
      throw new Exception('access denied', 403);

    return $object->finish;

  }

  public function ajaxReadMessage($mid, $seid)
  {
    // $s = new stdClass();
    // $s->idd = $mid;


    $db = JFactory::getDbo();
    $query = $db->getQuery(true)
      ->select('finish ,channel_token')
      ->from($db->quoteName('#__reservation_session','se'))
      ->where($db->quoteName('se.id').'='.$seid);

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


    if($result->finish == 1){
      throw new Exception('access denied', 403);
    }




    $data= ['id' => $mid, 'read' => true, 'channel_token'=>$result->channel_token ];



    \JPluginHelper::importPlugin('chat');
    $dispatcher = \JEventDispatcher::getInstance();

    $ss = $dispatcher->trigger('afterChatSave', array($data));
    if($ss[0])
    {
      JLoader::register('ReservationModelMessages',JPATH_COMPONENT_SITE.'/models/messages.php');
      $userid= JFactory::getUser()->get('id', 0);
      $model= new ReservationModelMessages();
      $model->readSingleMessage($mid);
    }

    return array('iddd' => $mid, 'ss' => $ss);
  }

  public function goToClass($user1, $user2,$seid,$pid)
  {
    // require_once JPATH_ADMINISTRATOR . '/components/com_reservation/bbb/autoload.php';
    // $bbb = new BigBlueButton\BigBlueButton($url, $secret);
    
    
    return array(
      "user1"    => $user1,
      "user2"    => $user2,
      "seid"     => $seid,
      "pid"      => $pid
    );
  }/***[/JCBGUI$$$$]***/


	// Used in consultantsignup

/***[JCBGUI.site_view.php_ajaxmethod.31.$$$$]***/
public function getCatLevelTwo($catIdLevel1)
    {
        $app= JFactory::getApplication();
        

        $db= JFactory::getDbo();
        $query= $db->getQuery(true)
            -> select($db->quoteName(array('c.id','c.title'),array('id','title')))
            ->from($db->quoteName('#__categories','c'))
            ->where($db->quoteName('c.parent_id'). '='. $catIdLevel1);

        $db->setQuery($query);
        $result= $db->loadObjectList();

       return $result ;
	}

    public function getCatLevelOne($extension)
    {
        $app= JFactory::getApplication();

        $db= JFactory::getDbo();
        $query= $db->getQuery(true)
            -> select($db->quoteName(array('c.id','c.title'),array('id','title')))
            ->from($db->quoteName('#__categories','c'))
            ->where($db->quoteName('c.parent_id'). '= 1')
            ->where($db->quoteName('c.extension'). '=' . $db->quote($extension));

        $db->setQuery($query);
        $result= $db->loadObjectList();

        return $result;

	}/***[/JCBGUI$$$$]***/

}
