<?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 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 == "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) " .
      "\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 = $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 .= "\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) ? "\nAND (" . implode(' OR ', $where2).')' : "");
    }
    $db->setQuery($selectstring);
    try {
        $total = $db->loadResult();
    } catch (RuntimeException $e) {
        echo $e->getMessage();
    }



    $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, " . 
      "\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 = $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 .= "\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) ? "\n WHERE " . 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 BuyRequestManager
    $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 = $item_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_buy_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);
    $item_session->set('field_names', $fieldNames);

    
    //************* begin add for sub category in select  *************
    $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/";
          }
      }
    }
    // print_r($list);exit;
    $clist = JHTML::_('select.genericlist',$options, 'catid', 
      'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $catid); 

    $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(":1111111111111111111:");
// // print_r($entityInstance);
// print_r(":11111111111111111112:");
// // print_r($str_list);
// print_r(":11111111111111111113:");
// print_r($price_fields);
// print_r(":11111111111111111114:");
// print_r($parent_price_fields);


    // andrew code start
    // $price_fields_assoc = array();
    // $parentIdsArr = array();
    // $orderId = 0;
    // $order_status = "";
    // $order_price = "";
    // $order_currency = "";
    // $order_quantity = "";
    // $coupon_id = "" ;



//     if( $orderId == 0 && intval($eiid) > 0 ){
//       $query = "SELECT * FROM #__os_cck_orders WHERE fk_request_id = ".$eiid."";
//       $db->setQuery($query);
//       $order = $db->loadObjectList();
//       if( count($order) > 0 ) {
//         $orderId = $order[0]->id ;
//         $order_status = $order[0]->status ;
//         $order_price = $order[0]->order_price ;
//         $order_currency = $order[0]->order_currency ;
//         $order_quantity = $order[0]->quantity ;
//       }
//     }

 
//     if( $orderId > 0 && count($price_fields_assoc) == 0 ){
//       $query = "SELECT * FROM #__os_cck_orders_price WHERE fk_order_id=$orderId";
//       $db->setQuery($query);
//       $price_fields = $db->loadObjectList();

//       $temp_price_count = 0;
//       foreach($price_fields as $price){

//         if($price && property_exists($price, 'fk_fid') && $price->fk_fid != 0) {
//           //in price_fields - can be coupon item, by pass it
//           $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid] = $price;
//           $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->value = $price->fk_price_id;
//           $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->fid = $price->fk_fid;
//           $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->calculated = 1;
//           $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->quantity = $price->quantity;
//           $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->fid = $price->fk_fid;

//           $entityInstance = new os_cckEntityInstance($db->_db);
//           $entityInstance->load( $price->fk_eiid );
//           $price_fields_assoc[$temp_price_count][$price->fk_eiid][$price->fk_fid]->lid = $entityInstance->fk_lid;
//           $temp_price_count++;
//         } else {
//           //coupon
//           $coupon_id = $price->fk_price_id;
//         }
//       }
//     }

//     if( isset($coupon_id) && $coupon_id != ''){
//       if( !isset($coupon) ){
//         $coupon = new os_cckCoupons($db->_db);
//         $coupon->load($coupon_id);
//       } 
//     } 

//     if( $orderId > 0 ){
//       $query = "SELECT сart_item, fk_eiid as eiid FROM #__os_cck_orders_price WHERE fk_order_id=$orderId GROUP BY сart_item";
//       $db->setQuery($query);
//       $parentIdsArrTmp = $db->loadAssocList("eiid");
//     }

//     if( isset($parentIdsArrTmp) && count($parentIdsArrTmp) > 0 && isset($parentIdsArr) && count($parentIdsArr) > 0 ) {
//         $parentIdsArr = array_merge($parentIdsArr, $parentIdsArrTmp) ;  
//     }elseif(isset($parentIdsArrTmp) && count($parentIdsArrTmp) > 0 && isset($parentIdsArr) && count($parentIdsArr) == 0 ){
//         $parentIdsArr = $parentIdsArrTmp ;  
//     }

//     $cart_item = 0 ; //if $parentIdsArr input param for this function, so $parent['сart_item'] - not defined
//     $fields_for_parent = array();
//     foreach($parentIdsArr as $parent){
//       $parent_eiid = $parent['eiid'];
//       if( isset($parent['сart_item']) ) $cart_item = $parent['сart_item'];

//       if( isset($price_fields_assoc)  && count($price_fields_assoc) > 0 ){
//         $field_tmp = $price_fields_assoc[$cart_item][$parent_eiid];
//         $calculated_price = getCalculatedPrice($field_tmp, $parent_eiid, 51, $coupon_id);
       
//         $parentIdsArr[$parent_eiid]['price_without_coupon'] = $calculated_price['price_without_coupon'];
//         $parentIdsArr[$parent_eiid]['coupon_discount'] = $calculated_price['coupon_discount'];
//         $parentIdsArr[$parent_eiid]['result_price'] =  $calculated_price['calculated_price'];
//       }
//       $parent_instance = new os_cckEntityInstance($db->_db);
//       $parent_instance->load($parent_eiid);

//         foreach($entityFieldLists[$parent_instance->fk_eid] as $field){

//           $field_val = $parent_instance->getFieldValue($field);

//           if(stripos($field->field_type, 'pricefield') !== false) {
//             if (isset($price_fields_assoc[$cart_item][$parent_eiid][$field->fid])) {
//                foreach ($field_val as $val) {

//                    if ($val->price_id == $price_fields_assoc[$cart_item][$parent_eiid][$field->fid]->value) {

//                        if($val->price_value == $val->price_name) {
//                            $fields_for_parent[$cart_item][$parent_eiid][$field->db_field_name] = 
//                             calculatedCurrency($parent_instance, $val->price_value)[0];

//                            if($price_fields_assoc[$cart_item][$parent_eiid][$field->fid]->quantity > 1){
//                                $fields_for_parent[$cart_item][$parent_eiid][$field->db_field_name] .= ' x ' . $price_fields_assoc[$cart_item][$parent_eiid][$field->fid]->quantity;
//                            }
//                        }else{

//                            $fields_for_parent[$cart_item][$parent_eiid][$field->db_field_name] = $val->price_name . ' ' . calculatedCurrency($parent_instance, $val->price_value)[0];
//                        }
//                    }
//                }

//             }else{
//                if(isset($field_val[0])){
//                    $fields_for_parent[$cart_item][$parent_eiid][$field->db_field_name] = calculatedCurrency($parent_instance, $field_val[0]->price_value)[0];
//                }
//             }
//           }
//         }
//       }

// $show_price_body = "{instance_title}, price: {price_without_coupon}, coupon:{coupon}, order_status:{order_status}, order_id: {order_id}";

//                   //first: set Parents fields()
//                   foreach($fields_for_parent as $cart_item)
//                   {
//                     foreach($cart_item as $cart_item_key=>$instance_field){
//                       //there may be only 1 element in array (if 1 order in cart or if this some request for 1 item)
//                       //$cart_item_key === eiid
//                       $parentIdsArr[$cart_item_key]['show_price_body'] = $show_price_body;
//                     }
//                   }
// print_r(":11111111111111111110:");
// print_r($parentIdsArr);


//                   //second: set Request fields
//                   //send to some instance which haven't parent => create $parentIdsArr
//                   if(count($parentIdsArr) == 0 ) $parentIdsArr[0]['show_price_body'] = $show_price_body;


                    
//                   foreach($parentIdsArr as $key1=>$field1){
//                     $parentIdsArr[$key1]['show_price_body'] 
//                         = str_replace("{price_without_coupon}", 
//                             $parentIdsArr[$key1]['price_without_coupon'] . " ". $order_currency, $parentIdsArr[$key1]['show_price_body'] );
//                   }
//                   if(isset($coupon_id) && $coupon_id != '' && isset($coupon) ){
//                     foreach($parentIdsArr as $key1=>$field1){
//                       $parent_instance = new os_cckEntityInstance($db->_db);
//                       $parent_instance->load($key1);

//                       $coupon_text = $coupon->name . ' - ' . $coupon->value ;
//                       if($coupon->type == 'percent'){
//                           $coupon_text .= '%';
//                       }else{
//                           $coupon_text .= calculatedCurrency($parent_instance, $mail_data['coupon']->value)[0];
//                       }

//                       $coupon_text .= ', '. 
//                         cck_lang_text("COM_OS_CCK_COUPON_DISCOUNT").':'. $parentIdsArr[$key1]['coupon_discount'] . " ". $order_currency . ', '. 
//                         cck_lang_text("COM_OS_CCK_RESULT_PRICE").':'. $parentIdsArr[$key1]['result_price'] . " ". $order_currency;
                      
//                       if($parentIdsArr[$key1]['coupon_discount'] == 0 ){ 
//                           $parentIdsArr[$key1]['show_price_body'] 
//                               = str_replace("{coupon}", '', $parentIdsArr[$key1]['show_price_body'] );
//                       } else{
//                           $parentIdsArr[$key1]['show_price_body'] 
//                               = str_replace("{coupon}", $coupon_text, $parentIdsArr[$key1]['show_price_body'] );
//                       }
//                     }
//                   }else{
//                     foreach($parentIdsArr as $key1=>$field1){
//                         $parentIdsArr[$key1]['show_price_body']  
//                             = str_replace("{coupon}", '', $parentIdsArr[$key1]['show_price_body'] );
//                     }
//                   }

//                   foreach($parentIdsArr as $key1=>$field1){
//                     $parentIdsArr[$key1]['show_price_body'] 
//                         = str_replace("{order_id}", $orderId, $parentIdsArr[$key1]['show_price_body']);
//                   }
//                   foreach($parentIdsArr as $key1=>$field1){
//                     $parentIdsArr[$key1]['show_price_body'] 
//                       = str_replace("{order_status}", $order_status, $parentIdsArr[$key1]['show_price_body']);
//                   }
// // andrew code end



// print_r(":11111111111111111112:");
// print_r($parentIdsArr);
// print_r(":11111111111111111113:");
// print_r($fields_for_parent);
// print_r(":11111111111111111114:");
// print_r($parent_price_fields);
    // exit;
    
    AdminViewBuy_request :: editBuyRequestInstance($option, $entityInstance, $str_list, $price_fields, $parent_price_fields, $recursive);
  }
  

  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);
      //here also send email for buy/rent request  
      $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 delete_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");
  }
    
}
