<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OS CCK
* @copyright 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
*/
use OrdaSoft\os_lib\os_libMain;
use OrdaSoft\os_lib\os_libPagination;

// if( !class_exists("os_libMain") ){
//     try{
//         $ss = new os_libMain();
//     }catch( Exception $e ){
//         die("Please reinstall OrdaSoft Joomla CCK Package!");
//     }
// }
class AdminRequest{

   static function showRequests($option){
    global $db, $app, $jConf, $entityFieldLists;
    $db = new os_cckDb();
       if(!JFactory::getUser()->authorise('access_to_requests', 'com_os_cck')){
           $app->enqueueMessage("Access denied", 'error');
           return;
       }
    // SORTING parameters start
    $session = JFactory::getSession();
    $item_sort_param = mosGetParam($_GET, 'sort', 'jei.eiid');
    if (is_array($sort_arr = $session->get('eq_itemsort', ''))) {
      if(protectInjectionWithoutQuote('sorting_direction','')){
        if(protectInjectionWithoutQuote('sorting_direction')=="ASC"){
          $sort_arr['sorting_direction'] = "DESC";
        }else{
          $sort_arr['sorting_direction'] = "ASC";
        }
      }elseif($session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $session->get('sorting_direction');
      }else{
        $sort_arr['sorting_direction']="DESC";
      }
      if ($item_sort_param == $sort_arr['field']) {
      } else {
        $sort_arr['field'] = $item_sort_param;
      }
      if($item_sort_param == 'category'){
        $sort_string = 'c.fk_cid' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_entity'){
        $sort_string = 'jei.fk_eid' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_id'){
        $sort_string = 'jei.eiid' . " " . $sort_arr['sorting_direction'];
      }else{
        $sort_string = $sort_arr['field'] . " " . $sort_arr['sorting_direction'];
      }
    } else {

      $sort_arr = array();
      if(protectInjectionWithoutQuote('sorting_direction','')){
        $sort_arr['sorting_direction'] = protectInjectionWithoutQuote('sorting_direction');
      }elseif($session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $session->get('sorting_direction');
      }else{
        $sort_arr['sorting_direction']="DESC";
      }
      if($item_sort_param == 'category'){
        $sort_string = 'c.fk_cid'. " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_entity'){
        $sort_string = 'jei.fk_eid'. " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_id'){
        $sort_string = 'jei.eiid'. " " . $sort_arr['sorting_direction'];
      }else{
        $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
      }
      $sort_arr['field'] = $item_sort_param;
    }
    $session->set('eq_itemsort', $sort_arr);

    //maybe it is search below
    $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
    $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
    $catid = $app->getUserStateFromRequest("catid{$option}", 'catid', '');
    $pub = $app->getUserStateFromRequest("pub{$option}", 'pub', '');
    $search = $app->getUserStateFromRequest("search{$option}", 'search', '');
    
    $entity_id = $app->getUserStateFromRequest("entity_id{$option}", 'entity_id', '');
    $entities = array();
    $entities[] = array('value' => '', 'text' => cck_lang_text('COM_OS_CCK_OPTION_ALL_ENTITIES'));
    $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity  ORDER BY name";          
    $db->setQuery($query);
    $ent = $db->loadObjectList("value");
    if( count($ent) > 1 ){
      $entities = array_merge($entities, (array)$ent) ;
    } else{
      //$entities = $entities;
      //set $entity_id == "" - when we haven 1 entity, and yet one - old was war selected we removed, 
      //for clear old values from $entity_list filter and from $where array
      $entity_id = "";
    }
    $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 
      'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);

    $where = $where2 = array();
    $catwhere = "";
    if ($entity_id != '' && isset($ent[$entity_id])) {
        array_push($where, "jei.fk_eid ='{$entity_id}'");
    }
    if ($pub == "pub") {
      array_push($where, "jei.published = 1");
    } else if ($pub == "not_pub") {
      array_push($where, "jei.published = 0");
    }
    if ($catid > 0) {
      array_push($where, "c.fk_cid='$catid'");
    }
    array_push($where, "cl.type = 'request_instance'");

    //pagination?*
    $selectstring = "SELECT count(jei.eiid) " .
      "\n FROM #__os_cck_entity_instance AS jei" .
      "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
      "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
      "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ";

    if($search || protectInjectionWithoutQuote('sort','')){
      $fieldNames = $session->get('field_names');
      foreach ($fieldNames as $value) {
        foreach ($value['fields'] as $name) {
          if($value['field_type'] == 'categoryfield' && $name == protectInjectionWithoutQuote('sort','')){
            $sort_string = 'cc.title'. " " . $sort_arr['sorting_direction'];
            continue;
          }
          array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
        }
        $selectstring .= "\nLEFT JOIN #__os_cck_content_entity_".$value['ent_name']." ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";
      }
      array_push($where2, "jei.eiid LIKE '%$search%' ");
    }
    $selectstring .=  "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
      "\n LEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
      "\n LEFT JOIN #__users AS u ON u.id = jei.checked_out " .
      (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

    if($search){
      $selectstring .=  (count($where2) ? "\n AND (" . implode(' OR ', $where2).')' : "");
    }
    $db->setQuery($selectstring);
    try {
        $total = $db->loadResult();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
    }

    $limit = intval($limit);
    $pageNav = new os_libPagination($total, $limitstart, $limit);

    $selectstring = "SELECT jei.*, cl.title as lay_title, cl.type as lay_type, cl.params as lay_params, " . 
      "\n GROUP_CONCAT(DISTINCT cc.title SEPARATOR ', ') AS category, ce.name AS entity, " .
      "\n l.id as rentid, l.rent_from as rent_from, l.rent_return as rent_return,l.rent_until as rent_until,u.name AS editor, " . 
      "\n GROUP_CONCAT(DISTINCT cpc.fid_parent SEPARATOR ',') AS fid_parent " .
      "\n FROM #__os_cck_entity_instance AS jei " .
      "\n LEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
      "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
      "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid " .
      "\n LEFT JOIN #__os_cck_child_parent_connect AS cpc ON jei.eiid=cpc.fid_child ";

      if($search || protectInjectionWithoutQuote('sort','')){
        $fieldNames = $session->get('field_names');
        foreach ($fieldNames as $value) {
          foreach ($value['fields'] as $name) {
            if($value['field_type'] == 'categoryfield' && $name == protectInjectionWithoutQuote('sort','')){
              $sort_string = 'cc.title'. " " . $sort_arr['sorting_direction'];
              continue;
            }
            array_push($where2, '#__os_cck_content_entity_'.$value['ent_name'].'.'.$name." LIKE '%$search%' ");
          }
          $selectstring .= "\n LEFT JOIN #__os_cck_content_entity_".$value['ent_name'].
            " ON #__os_cck_content_entity_".$value['ent_name'].".fk_eiid = jei.eiid ";
        }
        array_push($where2, "jei.eiid LIKE '%$search%' ");
      }

    $selectstring .= "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
      "\n LEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
      "\n LEFT JOIN #__users AS u ON u.id = jei.checked_out " .
      (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

    if($search){
      $selectstring .=  (count($where2) ? "\n AND (" . implode(' OR ', $where2).')' : "");
    }
    
    $selectstring .= "\n GROUP BY jei.eiid " .
      "\n ORDER BY jei.notreaded desc,$sort_string " .
      "\n LIMIT $pageNav->limitstart,$pageNav->limit;";
    $db->setQuery($selectstring);
    try {
        $rows = $db->loadObjectList();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
        return false;
    }
//    if ($db->getErrorNum()) {
//      echo $db->stderr();
//      return false;
//    }

    //prepere for show fields: selected for show in RequestManager
    $show_fields = $entityEaaray = $layoutArray = $fieldNames = array();
    if(count($rows)>0){
      $date = strtotime(JFactory::getDate()->toSql());
      foreach ($rows as $row) {
        $check = strtotime($row->checked_out_time);
        $remain = 7200 - ($date - $check);
        if (($remain <= 0) && ($row->checked_out != 0)) {
            $db->setQuery("UPDATE #__os_cck_entity_instance SET checked_out=0,checked_out_time=0");
            $db->execute();
            $row->checked_out = 0;
            $row->checked_out_time = 0;
        }
        // $lay_params = unserialize($row->lay_params);
        $entityEaaray[] = $row->fk_eid;
        $layoutArray[] = $row->fk_lid;
      }

      $entityEaaray = array_unique($entityEaaray);
      $layoutArray = array_unique($layoutArray);
      $uniqFieldsArray = array(); //need for add fields only 1 time
      foreach( $entityEaaray as $key => $value){
        foreach( $layoutArray as $key2 => $value2){

          $layout = new os_cckLayout($db->_db);
          $layout->load($layoutArray[$key2]);
          $bootstrap_version = $session->get( 'bootstrap','2');
          $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
          // $layout_params = unserialize($layout->params);
          $extra_fields_list = $entityFieldLists[$value];
          foreach($extra_fields_list as $Fieldvalue){
            $params = new JRegistry;
            $params->loadString($Fieldvalue->params);
            if($params->get('show_in_requests', '') == 'yes' && strpos($layout_html,"{|f-".$Fieldvalue->fid."|}")){
              if( isset($uniqFieldsArray[$Fieldvalue->fid] ) ) continue; //need for add fields only 1 time
              $uniqFieldsArray[$Fieldvalue->fid] = $Fieldvalue->fid ;
              $fieldNames[$key]['ent_name'] = $Fieldvalue->fk_eid;
              $fieldNames[$key]['field_type'] = $Fieldvalue->field_type;
              $fieldNames[$key]['fields'][] = $Fieldvalue->db_field_name;//need for use in search // [][table_name][column_mname]
              $show_fields[$value][]= $Fieldvalue;
            }
          }
        }
      }
      ksort($show_fields);
    }
    // $show_fields = array_unique($show_fields);
    $session->set('field_names', $fieldNames);

    //************* begin add for sub category   *************
    $categories[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_CATEGORIES'),'value','text');
    $options = $categories;
    $id = 0;
    $fromSearch=0;
    $list = CCK_CAT_Utils::categoryArray('com_os_cck',$fromSearch);
    $cat = new os_cckCategory($db->_db);
    $cat->load($id);

    $this_treename = '';
    foreach ($list as $item) {
      if ($this_treename) {
          if ($item->cid != $cat->cid && strpos($item->title, $this_treename) === false) {
              $options[] = JHTML::_('select.option',$item->cid, $item->title,'value','text');
          }
      } else {
          if ($item->cid != $cat->cid) {
              $options[] = JHTML::_('select.option',$item->cid, $item->title,'value','text');
          } else {
              $this_treename = "$item->title/";
          }
      }
    }
    $clist = JHTML::_('select.genericlist',$options, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid); 

    $pubmenu[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'),'value','text');
    $pubmenu[] = JHTML::_('select.option','not_pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_NOT_PUBLIC'),'value','text');
    $pubmenu[] = JHTML::_('select.option','pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_PUBLIC'),'value','text');
    $publist = JHTML::_('select.genericlist',$pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);

    AdminViewRequest :: showRequests($option, $rows, $clist, $publist, $search, $pageNav, $sort_arr, $show_fields,$entity_list);
  }

  static function removeRequestItem($bid, $option){
    global $db,$app;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if (!is_array($bid) || count($bid) < 1) {
      echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
      exit;
    }
    if (count($bid)) {
      foreach ($bid as $id) {
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($id);
        $instance->delete();
      }
    }
    $app->redirect("index.php?option=$option&task=show_requests");
  }

  static function showRequestItem($option, $bid, $recurse = 0){
    global $db, $my,$app, $entityFieldLists;
    $db = new os_cckDb();
    $entityInstance = new os_cckEntityInstance($db->_db);
    $entityInstance->load(intval($bid));
    if(!$entityInstance->eiid){
      return;
    }
    
    if(intval($bid)){
      $query="UPDATE #__os_cck_entity_instance SET notreaded=0 WHERE eiid=".intval($bid);
      $db->setQuery($query);
      $db->execute();
    }
    
    $extra_fields_list = $entityFieldLists[$entityInstance->fk_eid];
    $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child = $entityInstance->eiid AND media_type='instance'";
    $db->setQuery($query);
    $parent_instance = $db->loadObjectList();
    
    $instance_layout = new os_cckLayout($db->_db);
    $instance_layout->load(intval($entityInstance->fk_lid));
    
    if(empty($parent_instance)){
        if($recurse == 1){
            if($instance_layout->getDefaultLayout($entityInstance->fk_eid, 'instance')){
                $instance_layout->load(intval($instance_layout->getDefaultLayout($entityInstance->fk_eid, 'instance')));
            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
            }
        }else{
            $parent_instance = new os_cckLayout($db->_db);
            if($parent_instance->getDefaultLayout($entityInstance->fk_eid, 'instance')){

                $parent_instance->load(intval($instance_layout->getDefaultLayout($entityInstance->fk_eid, 'instance')));

            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_CREATE_ENTITY_LAYOUT"), 'warning');
            }
        }
    }else{
      $instance_layout->load(intval($entityInstance->fk_lid));
    }
    
    $layout_params = unserialize($instance_layout->params);

    $str_list = array();
    $str_list['layout_params'] = $layout_params;
    $str_list['layout'] = $instance_layout;
    $str_list['extra_fields_list'] = $extra_fields_list;
    $str_list['parent_instance'] = $parent_instance;
    
    //print_r($entityInstance);exit;
    AdminViewRequest :: showRequestItem($option, $entityInstance, $str_list, $recurse);
  }
  
}
