<?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 AdminRent_request{
  static function showRentRequestInstances($option){
    global $db, $app, $jConf, $entityFieldLists;
    $db = new os_cckDb();
//    echo '11111111111111'; exit;
    //JHtml::_('behavior.framework', true);
    // SORTING parameters start
//      var_dump(JFactory::getUser()->authorise('access_to_rent_requests', 'com_os_cck'));
      if(!JFactory::getUser()->authorise('access_to_rent_requests', 'com_os_cck')){
          $app->enqueueMessage("Access denied", 'error');
          return;
      }
    $item_session = JFactory::getSession();
    $item_sort_param = mosGetParam($_GET, 'sort', 'jei.eiid');
    if (is_array($sort_arr = $item_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($item_session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $item_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($item_session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $item_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;
    }
    $item_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', '1');
    $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 ent.eid AS value, ent.name AS text FROM #__os_cck_entity as ent"
    //           ."\n LEFT JOIN #__os_cck_layout as lay ON lay.fk_eid = ent.eid WHERE lay.type = 'rent_request_instance'";
    $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity  ORDER BY name";
    $db->setQuery($query);
    $ent = $db->loadObjectList("value");
    $entities = (count($ent) > 1) ? array_merge($entities, (array)$ent) : $entities;
    $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 ($pub == "1") {
      array_push($where, "jei.published = 1");
    } elseif ($pub == "2") {
      array_push($where, "jei.published = 0");
    }
    if ($catid > 0) {
      array_push($where, "c.fk_cid='$catid'");
    }
    array_push($where, "cl.type = 'rent_request_instance'");
    //pagination?*
    $selectstring = "SELECT count(jei.eiid) " .
      "\nFROM #__os_cck_entity_instance AS jei" .
      "\nLEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
      "\nLEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
      "\nLEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid ";
    if($search && protectInjectionWithoutQuote('sort','')){
      $fieldNames = $item_session->get('field_names');
      foreach ($fieldNames as $value) {
        if($value['field_type'] == 'categoryfield' && $name == protectInjectionWithoutQuote('sort','')){
          $sort_string = 'cc.title'. " " . $sort_arr['sorting_direction'];
          continue;
        }
        foreach ($value['fields'] as $name) {
          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 .=  "\nLEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
      "\nLEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
      "\nLEFT JOIN #__users AS u ON u.id = jei.checked_out " .
      (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

    if($search){
      $selectstring .=  (count($where2) ? "\nAND (" . implode(' OR ', $where2).')' : "");
    }
    $db->setQuery($selectstring);

    
    try {
        $total = $db->loadResult();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
    }
    //echo $db->getErrorMsg();
    $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, GROUP_CONCAT(DISTINCT cc.title SEPARATOR ', ') AS category, ce.name AS entity, " .
      "\nl.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, cpc.fid_parent " .
      "\nFROM #__os_cck_entity_instance AS jei" .
      "\nLEFT JOIN #__os_cck_categories_connect AS c ON jei.eiid=c.fk_eiid " .
      "\nLEFT JOIN #__os_cck_categories AS cc ON cc.cid = c.fk_cid " .
      "\nLEFT JOIN #__os_cck_entity AS ce ON ce.eid = jei.fk_eid " .
      "\nLEFT JOIN #__os_cck_child_parent_connect AS cpc ON jei.eiid=cpc.fid_child ";

      if($search || protectInjectionWithoutQuote('sort','')){
        $fieldNames = $item_session->get('field_names');
        if(is_array($fieldNames)){
            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 .= "\nLEFT JOIN #__os_cck_layout AS cl ON cl.lid = jei.fk_lid ".
      "\nLEFT JOIN #__os_cck_rent AS l ON l.fk_eiid = jei.eiid  and l.rent_return is null " .
      "\nLEFT JOIN #__users AS u ON u.id = jei.checked_out " .
      (count($where) ? "\nWHERE " . implode(' AND ', $where) : "");

    if($search){
      $selectstring .=  (count($where2) ? "\nAND (" . implode(' OR ', $where2).')' : "");
    }
    
    $selectstring .= "\n GROUP BY jei.eiid " .
      "\nORDER BY jei.notreaded desc,$sort_string " .
      "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
    $db->setQuery($selectstring);
// echo $selectstring;
    
    try {
        $rows = $db->loadObjectList();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
        return false;
    }
//    if ($db->getErrorNum()) {
//      echo $db->stderr();
//      return false;
//    }
    $show_fields = $fieldNames = $entityEaaray = 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;
      }
        foreach(array_unique($entityEaaray) as $key => $value){

        $layout = new os_cckLayout($db->_db);
        $layout->load($layoutArray[$key]);
        $bootstrap_version = $item_session->get( 'bootstrap','2');
        $layout_html = urldecode($layout->getLayoutHtml($bootstrap_version));
        $layout_params = unserialize($layout->params);
        // $extra_fields_list = $entity->getFieldList();
        $extra_fields_list = $entityFieldLists[$value];
        foreach($extra_fields_list as $Fieldvalue){
          $params = new JRegistry;
          $params->loadString($Fieldvalue->params);
          if($params->get('show_in_rent_requests', '') == 'yes' && strpos($layout_html,"{|f-".$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);
    }

    $item_session->set('field_names', $fieldNames);
    $categories[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_CATEGORIES'),'value','text');
    //************* begin add for sub category in select in manager houses  *************
    $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/";
          }
      }
    }
    // print_r($list);exit;
    $clist = JHTML::_('select.genericlist',$options, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid); //new nik edit
    // $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);
    $pubmenu[] = JHTML::_('select.option','1', cck_lang_text('COM_OS_CCK_LABEL_SELECT_NOT_ACCEPTED_REQUESTS'),'value','text');
    $pubmenu[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_ALL_REQUESTS'),'value','text');
    $pubmenu[] = JHTML::_('select.option','2', cck_lang_text('COM_OS_CCK_LABEL_SELECT_ACCEPTED_REQUESTS'),'value','text');
    $publist = JHTML::_('select.genericlist',$pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);
    
    $request_prices = array();
    foreach($rows as $request){
        $query = "SELECT op.*, o.fk_request_id FROM #__os_cck_orders_price as op "
                . "LEFT JOIN #__os_cck_orders as o ON o.id=op.fk_order_id "
                . " WHERE o.fk_request_id = ".$request->eiid." ";
        $db->setQuery($query);
        $request_price = $db->loadObjectList();
        
        $request_prices[$request->eiid] = $request_price;
        
    }
//     var_dump($request_prices);

    AdminViewRent_request :: showRentRequestInstances($option, $rows, $clist, $publist, $search, $pageNav, $sort_arr, $show_fields,$entity_list, $request_prices);
  }

    static function editRentRequestInstance($option, $bid, $recursive = 1){
        global $db, $user, $app, $os_cck_state, $entityFieldLists;
        $db = new os_cckDb();
        //JHtml::_('behavior.framework', true);

        $select_type = protectInjectionWithoutQuote('lay_type','');
        $entityInstance = new os_cckEntityInstance($db->_db);
        $entityInstance->load(intval($bid));
        if(!$entityInstance->eiid){
            return;
        }
        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        if(intval($bid)){
            $entityInstance->notreaded = 0;
            $entityInstance->store();
        }
        $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->loadResult();
        

        $instance_layout = new os_cckLayout($db->_db);
        $eiid = $bid;
        $query = "SELECT DISTINCT opr.сart_item FROM #__os_cck_orders_price as opr "
            . "LEFT JOIN #__os_cck_orders as ord ON ord.id = opr.fk_order_id "
            . "WHERE ord.fk_request_id=$entityInstance->eiid";
        $db->setQuery($query);
        $cart_items = $db->loadObjectList();
        // var_dump($cart_items);
        $price_fields = array();
        // $parent_instance = array();
        foreach ($cart_items as $item){
            
            $query = "SELECT DISTINCT opr.* FROM #__os_cck_orders_price as opr "
                . "LEFT JOIN #__os_cck_orders as ord ON ord.id = opr.fk_order_id "
                . "WHERE ord.fk_request_id=$eiid AND opr.сart_item=$item->сart_item";

            $db->setQuery($query);
            $price_fields[] = $db->loadObjectList();
//            var_dump($price_fields);
            // $query = "SELECT opr.fk_eiid FROM #__os_cck_orders_price as opr "
            //     . "LEFT JOIN #__os_cck_orders as ord ON ord.id = opr.fk_order_id "
            //     . "WHERE ord.fk_request_id=$eiid AND opr.сart_item=$item->сart_item "
            //     . "GROUP BY opr.сart_item";
            // $db->setQuery($query);
            // $parent_instance[] = $db->loadObjectList();

        }
        // var_dump($price_fields);

        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        if(empty($parent_instance)){

            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');
                return;

            }

        }else{

//        $query = "SELECT fk_coup_id FROM #__os_cck_orders WHERE fk_request_id = $entityInstance->eiid";
//
//        $db->setQuery($query);
//        $coupon = $db->loadObjectList();
//        if(!empty($coupon)){
//            $coupon = $coupon[0];
//        }
//
//        $entityInstance->_coupon = $coupon;
            $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['parent_instance'] = $parent_instance;
        $str_list['extra_fields_list'] = $extra_fields_list;

        AdminViewRent_request :: editRentRequestInstance($option, $entityInstance, $str_list, $recursive, $price_fields);
    }
  
  static function remove_rent_request_item($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_rent_request_instances");
  }
    
  static function accept_rent_requests($option, $bids, $redirect = 1){
    global $db,$app, $os_cck_state;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    
    foreach ($bids as $bid) {
      $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child=$bid";
      $db->setQuery($query);
      $parent_id = $db->loadResult();

      $rent_request = new os_cckEntityInstance($db->_db);
      $rent_request->load($parent_id);
      $rent_request->child_id = $bid;


      $entity = new os_cckEntity($db->_db);
      $entity->load($rent_request->fk_eid);
      $rent_request->entity_name = $entity->name;

      $tmp = $rent_request->accept();



      if ($tmp != null) {
        echo "<script> alert('" . addslashes($tmp) . "'); window.window.location.href = '".JURI::base()."/index.php?option=com_os_cck&task=orders'; </script>\n";
        exit ();
      }
    }
    if($redirect = 1){
        $app->enqueueMessage('ok');
        $app->redirect("index.php?option=$option&task=show_rent_request_instances");
    }
  }


    

  static function decline_rent_requests($option, $bids){
    global $db,$app;
    $db = new os_cckDb();
    foreach ($bids as $bid) {
      $rent_request = new os_cckEntityInstance($db->_db);
      $rent_request->load($bid);
      $tmp = $rent_request->decline();
      if ($tmp != null) {
        echo "<script> alert('" . addslashes($tmp) . "'); window.history.go(-1); </script>\n";
        exit ();
      }
    }
    $app->enqueueMessage('ok');
    $app->redirect("index.php?option=$option&task=show_rent_request_instances");
  }

}
