<?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 AdminViewBuy_request{
  static function showBuyRequestInstances($option, & $rows_item, & $clist,
                                & $publist, & $search, & $pageNav, & $sort_arr, $show_fields,$entity_list,$request_instansies_array, $request_prices)
  {
      global $doc, $user, $app, $session,$db, $entityFieldLists, $entities_type;

      $db = new os_cckDb();
      $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />" . cck_lang_text('COM_OS_CCK_ADMIN_LABLE_ORDER') . "</div>";
      $app = JFactory::getApplication();
      $app->JComponentTitle = $html;
      $onclick = "Joomla.checkAll(this);";


      $form_name = 'adminForm';
      $form_id = 'adminForm' ;
      $table = new os_cckViewTable($form_name, $form_id, '', 
        'index.php?option=com_os_cck&task=show_buy_request_instances', 'show_buy_request_instances');

      $what_check = 'instance' ;
      $table->create_button(cck_lang_text("COM_OS_CCK_TOOLBAR_ADMIN_ACCEPT"), 'accept_buying_requests', 
        JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-check','',$what_check);
      $table->create_button( cck_lang_text("COM_OS_CCK_TOOLBAR_ADMIN_DECLINE") , 'decline_buying_requests', 
        JURI::root() . 'components/com_os_cck/images/published.png', 'fa-close','',$what_check);
      $table->create_button( cck_lang_text("COM_OS_CCK_LABEL_DELETE"), 'delete_buying_requests', 
        JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-close','',$what_check);
      $table->create_button(cck_lang_text("COM_OS_CCK_LABEL_BUTTON_MARK_AS_VIEWED"), 'is_readed', 
        JURI::root() . 'components/com_os_cck/images/published.png', 'fa-check','',$what_check);
      
      $table->create_filters('<div class="search_block"><input type="text" placeholder="'.cck_lang_text('COM_OS_CCK_SHOW_SEARCH').'" name="search" value="'.$search.'" class="inputbox" onChange="document.adminForm.submit();"/><button type="submit" class="cck_search_button" title="" data-original-title="Search"><span class="icon-search"></span></button></div>');
      $table->create_filters('<div>'.$clist.'</div>');
      $table->create_filters('<div>'.$entity_list.'</div>');
      $table->create_filters('<div>'.$publist.'</div>');
      
      
      $table->title_class = 'admin-request-title';
      $table->first_row_custom_class = 'admin-request-standart-fields';
      $table->limitbox = '<div class="btn-group pull-right hidden-phone">
      <label for="limit" class="element-invisible">'. cck_lang_text('OS_LIB_SEARCH_SEARCHLIMIT_DESC') .'</label>'. $pageNav->getLimitBox() .'</div>';


      $table->create_first_row_collumn(JHtml::_('grid.checkall'), '', 'admin-order-title-checkbox');  
      $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_ID'), 'inst_id', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-id');   

      //add aditional fields to Buy_requesta Manager
      os_cck_site_controller::create_first_row_collumns_titles($table,$show_fields,$sort_arr);

      $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_BUY_DATE'), 'created', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-email');   
      $table->create_first_row_collumn(cck_lang_text("COM_OS_CCK_ORDERS_PRICE"), '', 'admin-order-standart-fields-price');
      $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_REQUEST_ENTITY'), 'entity', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-date');


      for($i = 0; $i < count($rows_item); $i++) { 
        $request_data = array();
        
        $row = $rows_item[$i];

        if ($row->checked_out && $row->checked_out != $user->id) {
          $request_data[] = '';
        
        } else {
          $request_data[] = JHTML::_('grid.id',$i, $rows_item[$i]->eiid, ($rows_item[$i]->checked_out && $rows_item[$i]->checked_out != $user->id), 'eiid');
        }
        $request_data[] = '<a href="#show_request_item" onClick="return cckSendForm(\'cb'.$i
          .'\',\'edit_buy_request_instance\',\''.$form_name.'\')">'.$row->eiid.'</a>';

        //add aditional fields data to Buy_request Manager
        $request_data = array_merge($request_data, os_cck_site_controller::create_first_row_collumns_data($table,$rows_item[$i],$show_fields) );  

        $request_data[] = $rows_item[$i]->created;
        $request_data[] = $rows_item[$i]->instance_price." ". $rows_item[$i]->instance_currency;
        $request_data[] = $rows_item[$i]->entity;

        $style = ''; 
        $class = 'row' . ($i % 2) . ' '; 
        if($rows_item[$i]->notreaded == 1){
            $class .= ' admin-order-not-readed';
        }
        $table->create_first_row_data($request_data, $style, $class);

        //second row add always(also with empty data), count the second rows Must Be === count first row !!!!!!
        os_cck_site_controller::second_row_prepere($table,$rows_item[$i],'show_in_buy_requests');

      }

//         $table->paginator = $pageNav->getListFooter();
         $table->pageNav = $pageNav;

        echo $table->viewTable();

  }

  static function editBuyRequestInstance($option, & $entityInstance, & $str_list, $price_fields, $parent_price_fields, $recursive){
    global $os_cck_configuration,$user, $app, $session, $db, $entities_type;

    $db = new os_cckDb();
    $html = "<div class='os_cck_caption' ><img src='./components/com_os_cck/images/os_cck_logo.png' alt ='Config' />" . cck_lang_text('COM_OS_CCK_ADMIN_LABLE_ORDER') . "</div>";
    $app = JFactory::getApplication();
    $app->JComponentTitle = $html;
    // $doc = JFactory::getDocument();
    // $doc->addStyleSheet(JURI::root()."components/com_os_cck/assets/css/jquerOs-ui.min.css");
    // $doc->addStyleSheet(JURI::root()."components/com_os_cck/assets/css/admin_style.css");
    
    // $doc->addScript(JUri::root().'components/com_os_cck/assets/js/jquery.raty.js');
    
    // $doc->addScript(JURI::root()."components/com_os_cck/assets/js/jquerOs-ui.min.js");
    
    // $doc->addStyleSheet( JUri::root().'/components/com_os_cck/assets/lightbox/css/lightbox.css');
    // $doc->addScriptDeclaration('jQuerOs=jQuerOs.noConflict();');
    // $doc->addScript(JURI::root() . '/components/com_os_cck/assets/lightbox/js/lightbox-2.6.min.js');
//    $key = 'key='.$os_cck_configuration->get("google_map_key",'');
//    $doc->addScript('//maps.googlea pis.com/maps/api/js?'.$key);

    if($recursive == 1){
        $form_name = 'adminForm';
        $form_id = 'adminForm' ;
        $table = new os_cckViewTable($form_name, $form_id, 'add_entity_form wrapper_add_entity', 
          'index.php?option=com_os_cck&task=show_buy_request_instances', '');
        $table->create_button(cck_lang_text('COM_OS_CCK_TOOLBAR_ADMIN_ACCEPT'), 'accept_buying_requests', '', 'fa-check');
        $table->create_button(cck_lang_text('COM_OS_CCK_TOOLBAR_ADMIN_DECLINE'), 'decline_buying_requests', '', 'fa-close');
        $table->create_button('Back', 'show_buy_request_instances', '', 'fa-chevron-left');
        $table_html = '';

        ob_start();
    }
    if(empty($str_list['parent_instance'])){
      $div_id = 'parent_instance';
    }else{
    ?>
      <input name="eiid[]" value="<?php echo $entityInstance->eiid;?>" type="hidden">
      <input name="option" value="com_os_cck" type="hidden">
      <input name="task" value="" type="hidden">
      <input name="boxchecked" value="1" type="hidden">

    <?php
      $div_id = 'child_instance';

      //do coupon search
      $coup_id = -1 ;
      foreach ($price_fields as $price_field_inst){
        foreach ($price_field_inst as $price_field){
          if( isset($price_field->price_type) && $price_field->price_type == 'coupon'){
            $coup_id = $price_field->fk_price_id;
            break 2 ;
          }
        }
      }

      foreach ($price_fields as $price_field){

          $instance = new os_cckEntityInstance($db->_db);
          if( isset($price_field[0]) && $price_field[0]->price_type != 'coupon' )
          {
            $instance->load($price_field[0]->fk_eiid); 
          }elseif( isset($price_field[1]) && $price_field[1]->price_type != 'coupon' )
          {
            $instance->load($price_field[1]->fk_eiid); 
          }

          if($instance->meta_title == ''){
              
              $instance->meta_title = getInstanceTitle($instance);

          }
          
          echo '<div class="single_product" style="margin: 15px 0 15px 0;"><div class="product_title">'.$instance->meta_title.'</div>';
          $price_details = get_price_details($price_field , -1, $coup_id ) ;
          print_r(  $price_details['html'] ) ;

          echo '<div class="single_product_total">';
          $calculated_price = getCalculatedPrice($price_field, -1, 51, $coup_id);
          print_r(  "<span class='single_product_total_titla' >Total: </span><span class='single_product_value' >".
            $calculated_price['calculated_price'] .' '.$entityInstance->instance_currency . "</span>" ) ;
          echo '</div>';

          echo '</div>';

      }
      if( count($price_fields) > 0 ) {
          echo '<hr><div><span class="buy-total-price">';
          echo 'Total Price: '.$entityInstance->instance_price.' '.$entityInstance->instance_currency;
          echo '</span></div>';
      }

    }

    ?>
    <div id="<?php echo $div_id; ?>">
      <?php
      $layout_params = $str_list['layout_params'];
      $layout = $str_list['layout'];
      $bootstrap_version = $session->get( 'bootstrap','2');
      $layout->layout_html = $layout->getLayoutHtml($bootstrap_version);
      $layout_html = urldecode($layout->layout_html);
      $field_from_params = $layout_params["fields"];
      $fields_list = $str_list['extra_fields_list'];

      //add child selects to layout
      $addChildSelectToLayout = addChildSelectToLayout($fields_list, $entityInstance, $layout_params, $layout_html, $layout);
      $layout_html = $addChildSelectToLayout['layout_html'];
      $layout_params = $addChildSelectToLayout['layout_params'];
      $parent = $addChildSelectToLayout['select_parent'];
      $layout->params = serialize($layout_params);
      //add child selects to layout
      $hover_animated = array();
      $moduleId = 0;
      $Itemid = 0;
      $layout_params['custom_fields'] = unserialize($layout->custom_fields);
      
      // $layout_html = str_replace("{|l-".$layout->lid."|}", '', $layout_html);
      $layout_html = preg_replace("/{\|l-[0-9]*?\|}/", '', $layout_html); //remove child layouts - like add review
      $layout_html = preg_replace("/{\|f-cck_mail_[0-9]*?\|}/", '', $layout_html); //remove mail fields
      $layout_html = str_replace(array("{|f-cck_send_button|}","Button Send"), '', $layout_html);//button remove
      $layout_html = str_replace(array("{|f-cck_add_to_cart_button|}","Add to cart button"), '', $layout_html); //cart remove
      $layout_html = str_replace(array("{|f-cck_action_button_1|}",
          "{|f-cck_action_button_2|}","{|f-cck_action_button_3|}","Action button"), '', $layout_html); //actions buttons remove
      $layout_html = str_replace("{|f-total_price|}", $entityInstance->instance_price.' '.$entityInstance->instance_currency, $layout_html);
      if(strpos($layout_html,"{|f-coupon|}")){
          if(property_exists($entityInstance, '_coupons') && !empty($entityInstance->_coupons)){
              // ob_start();
              $layout_html_part1 = '<div>'.$entityInstance->_coupons->name.'</div>';
              if($entityInstance->_coupons->type == 'percent'){
                  $layout_html_part1 .= '<div>-'.$entityInstance->_coupons->value.'%</div>';
              }else{
                  $layout_html_part1 .= '<div>-'.calculatedCurrency($entityInstance, $entityInstance->_coupons->value).'%</div>';
              }
              $layout_html = str_replace("{|f-coupon|}", $layout_html_part1, $layout_html);
              // ob_end_clean();
          }else{
            $layout_html = str_replace("{|f-coupon|}", '', $layout_html);
          }
      }

      $child_entities = (isset($layout_params['child_entities'])) ? $layout_params['child_entities'] : '';
      $layout_html = $layout->getLayoutViews($entityInstance, $fields_list, $layout_html, $layout_params, $hover_animated, $option, $child_entities, $moduleId, $Itemid, 10);
      echo $layout_html;
      ?>
    </div>

    <?php
    ?><hr><?php
    if(!empty($str_list['parent_instance'])){
        if(is_array($str_list['parent_instance'])){
            foreach($str_list['parent_instance'] as $key => $parente_instance){
                AdminBuy_request::editBuyRequestInstance($option, $parente_instance[0]->fk_eiid, $price_fields[$key], 2);
            }
        }else{
            AdminBuy_request::editBuyRequestInstance($option, $str_list['parent_instance'], '', 2);
        }
    }
    
    if($recursive == 1){
        
        $table_html = ob_get_contents();
        ob_end_clean();
        $table->set_custom_html($table_html);
        echo $table->viewTable();
    }
    ?>
    <script type="text/javascript">
  jQuerOs("*[class*='hide-field-name-'] , .delete-field, .delete-row, .delete-layout").remove();
  
  jQuerOs("div[class *='cck-row-'], div[id *='cck_col-']").each(function(index, el) {
    jQuerOs(el).attr("style",jQuerOs(el).data("block-styling"));
  });

// jQuerOs("span.cck-help-string").remove()

jQuerOs(function () {
  jQuerOs('[data-toggle="tooltip"]').tooltip()
})

</script><?php
  }

}
