<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OS CCK
* @copyright 2020 OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/

class InstanceManagerRent{

  static function edit_rent($option, $eiid){
      
    global $db, $os_cck_configuration, $user, $Itemid, $entityFieldLists, $app;
    $db = new os_cckDb();
    //$Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
    $session = JFactory::getSession();;
    $input = $app->input;

    if (empty($eiid)) {
      echo "<script> alert('Select an instance to rent'); window.history.go(-1);</script>\n";
      exit;
    }
    
    $select="SELECT a.*, cc.name AS category, l.id as rent_id, cl.params as lay_params,ce.name AS entity, l.rent_from as rent_from, " .
        "\n l.rent_return as rent_return, l.rent_until as rent_until, " .
        "\n l.user_name as user_name, l.user_email as user_email, " .
        "\n cc.rent_request AS for_rent" .
        "\n FROM #__os_cck_entity_instance AS a" .
        "\n LEFT JOIN #__os_cck_categories_connect AS CC_rel ON CC_rel.fk_eiid = a.eiid" .
        "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = CC_rel.fk_cid" .
        "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = a.fk_lid ".
        "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = a.fk_eid ".
        "\n LEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = a.eiid" .
        "\n WHERE a.eiid = " . $eiid . " GROUP BY rent_id ORDER BY l.id DESC";
    $db->setQuery($select);
    if (!$db->execute()) {
      echo "<script> alert('" . addslashes($db->getErrorMsg()) . "'); window.history.go(-1); </script>\n";
      exit ();
    };
    $instances = $db->loadObjectList();
    $show_fields = $entityEaaray = $history_instance = $return_instance =array();
    if(count($instances)>0){
      foreach ($instances as $instance) {
        if($instance->rent_return){
          $history_instance[] = $instance;
        }else if($instance->rent_until){
          $return_instance[] = $instance;
        }
        $lay_params = unserialize($instance->lay_params);
        $entityEaaray[] = $instance->fk_eid;
        $layoutArray[] = $instance->fk_lid;
      }

      

      foreach(array_unique($entityEaaray) as $key => $value){
        $entity = new os_cckEntity($db->_db);
        $entity->load($value);
        $layout = new os_cckLayout($db->_db);
        $layout->load($layoutArray[$key]);
        $bootstrap_version = $session->get( 'bootstrap','2');
        $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
        $layout_params = unserialize($layout->params);
        $extra_fields_list = $entityFieldLists[$entity->eid];
  
        foreach($extra_fields_list as $Fieldvalue){

          $field_settings = $Fieldvalue->params;
          $field_settings = json_decode($field_settings, true);
          $field_settings = (isset($field_settings['allowed_value']))?$field_settings['allowed_value']:$field_settings['default_value'];
          
    
          if(isset($field_settings->show_in_instance_menu) && $field_settings->show_in_instance_menu
              && strpos($layout_html,"{|f-".$Fieldvalue->fid."|}")){
            $show_fields[$value][]= $Fieldvalue;
          }
        }

      }
      ksort($show_fields);
    }
    //for rent or not
    $count = count($instances);
    // get list of categories
    $userlist[] = JHTML::_('select.option','-1', 'Select User');
    $db->setQuery("SELECT id AS value, email, name AS text from #__users ORDER BY name");
    $user_array = $db->loadObjectList();
    $userlist = array_merge($userlist, $user_array);
    $usermenu = JHTML::_('select.genericlist',$userlist, 'userid',
                         'class="inputbox" size="1" onchange="fill_user(this.value)"', 'value', 'text', '-1');
    $type = 'instance_manager_rent_edit';
    
    $option_from_layout = 'com_os_cck';
      require getLayoutPathCCK::getLayoutPathCom($option_from_layout, $type);
  }


  static function rent_return($option, $lids){
      rentReturnCCK($option, $lids);
  }

  static function saveRent($option, $eiid,$task = ""){
      saveRentCCK($option, $eiid,$task);
  }

  static function users_rent_history($option){
    global $db,$os_cck_configuration, $user, $mainframe ,$Itemid, $moduleId, $entityFieldLists;
    $db = new os_cckDb();
    $input = JFactory::getApplication()->input;
    $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
    $user = JFactory::getUser();
    if($input->get('option', 'com_os_cck') == 'com_simplemembership'){
        $plugin = JPluginHelper::getPlugin('simplemembership', 'plg_simplemembership_get_cck_user_instances');
        $params = new JRegistry($plugin->params);
    }else{
        if(!$moduleId){
          // Params(cck component menu)
          if (version_compare(JVERSION, '3.0', 'ge')) {
            $menu = new JTableMenu($db->_db);
            $menu->load($Itemid);
            $params = new JRegistry;
            if($menu->params){
                $params->loadString($menu->params);
            }
          } else {
            $app = JFactory::getApplication();
            $menu = $app->getMenu();
            $params = new JRegistry;
            $params = $menu->getParams( $Itemid );
          }//end
        }else{
          $mod_row =  JTable::getInstance ( 'Module', 'JTable' );//load module tables and params
          if (! $mod_row->load ( $moduleId )) {
            
            throw new Exception($mod_row->getError (), 500);
          }
          //module params
          if (version_compare(JVERSION, '3.0', 'ge')) {
            $params = new JRegistry;
            $params->loadString($mod_row->params);
          } else {
            $params = new JRegistry($mod_row->params);
          }//end
        }
    }
    $session = JFactory::getSession();
    $owner = $user->id; //add nik    
    $rows = $show_fields = array();
    if($owner !=-1){
      $select="SELECT a.*, cc.name AS category, l.id as rent_id, cl.params as lay_params,ce.name AS entity, l.rent_from as rent_from, " .
          "\n l.rent_return as rent_return, l.rent_until as rent_until, " .
          "\n l.user_name as user_name, l.user_email as user_email, " .
          "\n cc.rent_request AS for_rent" .
          "\n FROM #__os_cck_entity_instance AS a" .
          "\n LEFT JOIN #__os_cck_categories_connect AS CC_rel ON CC_rel.fk_eiid = a.eiid" .
          "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = CC_rel.fk_cid" .
          "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = a.fk_lid ".
          "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = a.fk_eid ".
          "\n LEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = a.eiid" .
          "\n WHERE l.fk_userid=".$db->Quote($owner).
          "\n OR l.user_name=".$db->Quote($owner)." ORDER BY l.id DESC";
      $db->setQuery($select);
      if (!$db->execute()) {
        echo "<script> alert('" . addslashes($db->getErrorMsg()) . "'); window.history.go(-1); </script>\n";
        exit ();
      }
      $instances = $db->loadObjectList();

      $show_fields = $entityEaaray = array();


      if(count($instances)>0){
        foreach ($instances as $row) {
          $lay_params = unserialize($row->lay_params);
          $entityEaaray[] = $row->fk_eid;
          $layoutArray[] = $row->fk_lid;
        }
        foreach(array_unique($entityEaaray) as $key => $value){
          $entity = new os_cckEntity($db->_db);
          $entity->load($value);
          $layout = new os_cckLayout($db->_db);
          $layout->load($layoutArray[$key]);
          $bootstrap_version = $session->get( 'bootstrap','2');
          $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
          $layout_params = unserialize($layout->params);
          $extra_fields_list = $entityFieldLists[$entity->eid];


        foreach($extra_fields_list as $Fieldvalue){

          $field_settings = $Fieldvalue->params;
          $field_settings = json_decode($field_settings, true);
          $field_settings = (isset($field_settings['allowed_value']))?$field_settings['allowed_value']:$field_settings['default_value'];
          if(isset($field_settings->show_in_instance_menu) && $field_settings->show_in_instance_menu
              && strpos($layout_html,"{|f-".$Fieldvalue->fid."|}")){
            $show_fields[$value][]= $Fieldvalue;
          }
        }
        }
        ksort($show_fields);
      }
    }

    $userlist[] = JHTML::_('select.option','-1', 'Select User');
    $db->setQuery("SELECT DISTINCT fk_userid AS value, user_name AS text from #__os_cck_rent ORDER BY user_name");
    $userlist = array_merge($userlist, $db->loadObjectList());
    foreach ($userlist as $value) {
        if(!$value->value)
            $value->value = $value->text;
    }
    $usermenu = JHTML::_('select.genericlist',$userlist, 'owner_id', 'class="inputbox input-medium" size="1" 
        onchange="document.adminForm.submit();"', 'value', 'text', $owner);
    if ($option == 'com_simplemembership'){
        $option = 'com_os_cck';
    }
    $type = 'instance_manager_rent_history';
    require getLayoutPathCCK::getLayoutPathCom($option, $type);
  }

}
