<?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 AdminBuy_request{
  static function showBuyRequestInstances($option){
    global $db, $app, $jConf, $entityFieldLists;
    $db = new os_cckDb();
    //JHtml::_('behavior.framework', true);
    // SORTING parameters start
      if(!JFactory::getUser()->authorise('access_to_buy_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 = 'buy_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 == "1") {
      array_push($where, "jei.published = 1");
   } else if ($pub == "2") {
     array_push($where, "jei.published = 0");
   }
    if ($catid > 0) {
      array_push($where, "c.fk_cid='$catid'");
    }
    array_push($where, "cl.type = 'buy_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');
      // var_dump($fieldNames);
      if(is_array($fieldNames) && !empty($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).')' : "");
    }
    $db->setQuery($selectstring);

    
    try {
        $total = $db->loadResult();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
    }
    //echo $db->getErrorMsg();
    $limit = intval($limit);
    $language = JFactory::getApplication()->getLanguage();
    $language->load('os_lib',JPATH_ROOT);
    $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) && !empty($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);

    

    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;
      }
      
//      var_dump($entityEaaray);
        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 = $entityFieldLists[$value];
//        var_dump($extsra_fields_list);
        foreach($extra_fields_list as $Fieldvalue){
          $params = new JRegistry;
          $params->loadString($Fieldvalue->params);
          if($params->get('show_in_buy_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','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();
    $request_instansies_array = array();
    foreach($rows as $request){
        $query = "SELECT op.fk_eiid, op.сart_item 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." GROUP BY op.сart_item";
        $db->setQuery($query);
        $eiids = $db->loadAssocList('сart_item', 'fk_eiid');
      
        $request_instansies_array[$request->eiid] = $eiids;

        $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;
        
    }

    AdminViewBuy_request :: showBuyRequestInstances($option, $rows, $clist, $publist, $search, $pageNav, $sort_arr, $show_fields, $entity_list, $request_instansies_array, $request_prices);
  }

  static function editBuyRequestInstance($option, $eiid, $parent_price_fields = '', $recursive = 1){
    global $db, $my,$app, $os_cck_state, $entityFieldLists;
    $db = new os_cckDb();
    //JHtml::_('behavior.framework', true);
    $entityInstance = new os_cckEntityInstance($db->_db);
    $entityInstance->load(intval($eiid));
    if(!$entityInstance->eiid){
      return;
    }
    if(intval($eiid)){
      $query="UPDATE #__os_cck_entity_instance SET notreaded=0 WHERE eiid=".intval($eiid);
      $db->setQuery($query);
      $db->execute();
    }
    $extra_fields_list = $entityFieldLists[$entityInstance->fk_eid];
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $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=$eiid";
    $db->setQuery($query);
    $cart_items = $db->loadObjectList();
    //var_dump($cart_items); exit;
    $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();
        
        $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();
        
    }


    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $instance_layout = new os_cckLayout($db->_db);
    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{
      $instance_layout->load(intval($entityInstance->fk_lid));
    }
    //var_dump($parent_instance);
    $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;
    //print_r($entityInstance);exit;
    AdminViewBuy_request :: editBuyRequestInstance($option, $entityInstance, $str_list, $price_fields, $parent_price_fields, $recursive);
  }
  
  static function remove_buy_request_item($eiid, $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($eiid) || count($eiid) < 1) {
      echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
      exit;
    }
    if (count($eiid)) {
      foreach ($eiid as $id) {
        $instance = new os_cckEntityInstance($db->_db);
        $instance->load($id);
        $instance->delete();
      }
    }
    $app->redirect("index.php?option=$option&task=show_buy_request_instances");
  }
  
  static function accept_buying_requests($option, $bids, $redirect = 1){
    global $db,$app, $os_cck_state;
    if(!cck_checkReferer()){
        $app->enqueueMessage(JText::_("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. JText::_("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
//    var_dump($bids); exit;
    foreach ($bids as $bid) {
      
      $instance = new os_cckEntityInstance($db->_db);
      $instance->load($bid);
      $instance->publishInstance(0);
//      $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child=$bid";
//      $db->setQuery($query);
//      $parent_id = $db->loadResult();
//      
//      
//
//      $query = "UPDATE `#__os_cck_entity_instance` SET `published` = '0' WHERE `eiid` = $bid";
//      $db->setQuery($query);
//      $db->execute();
      
//      $buying_request = new os_cckEntityInstance($db);
//      $buying_request->load($parent_id);
//      $buying_request->child_id = $bid;

//      var_dump($buying_request); exit;
//      $entity = new os_cckEntity($db);
//      $entity->load($buying_request->fk_eid);
//      $buying_request->entity_name = $entity->name;
//      $tmp = $buying_request->accept();



      // $datas[] = array('name' => $buying_request->customer_name,
      //   'email' => $buying_request->customer_email,
      //   'id' => $buying_request->fk_houseid
      // );


//      $buying_request->published();



//      if ($tmp != null) {
//        echo "<script> alert('" . addslashes($tmp) . "'); window.history.go(-1); </script>\n";
//        exit ();
//      }
    }
    if($redirect == 1){
        $app->enqueueMessage('ok');
        $app->redirect("index.php?option=$option&task=show_buy_request_instances");
    }
  }

  static function decline_buying_requests($option, $bids){
      global $db,$app;
      $db = new os_cckDb();
      foreach ($bids as $bid) {
          $buy_request = new os_cckEntityInstance($db->_db);
          $buy_request->load($bid);
          $tmp = $buy_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_buy_request_instances");
  }

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