<?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 AdminViewRequest{

  static function showRequests($option, & $rows_item, & $clist,
      & $publist, & $search, & $pageNav, & $sort_arr, $show_fields,$entity_list)
  {
      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_SUBMISSIONS') . "</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_requests', 'show_requests');
      $what_check = 'instance' ;
      $table->create_button(cck_lang_text("COM_OS_CCK_LABEL_DELETE"), 'remove_request_item', 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>'.$publist.'</div>');
      $table->create_filters('<div>'.$clist.'</div>');
      $table->create_filters('<div>'.$entity_list.'</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');   
      foreach($show_fields as $value){
        foreach($value as $field){
          
          $table->create_first_row_collumn(cck_sort_head($field->field_name, $field->db_field_name, $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-email');   
                    
        }
      }
      $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_REQUEST_DATE'), 'created', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-email');   
      $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');

      $table->create_second_row_collumn('Title');

      for($i = 0; $i < count($rows_item); $i++) { 
        // var_dump($rows_item[$i]);
        $parentInstance = new os_cckEntityInstance($db->_db);
        $parentInstance->load($rows_item[$i]->fid_parent);
        
        $show_in_orders_fields = array();
                
        if(isset($entityFieldLists[$parentInstance->fk_eid])){
          $fields = $entityFieldLists[$parentInstance->fk_eid];
        }else{
          $fields = array();
        }
        foreach($fields as $field){
            $params = new JRegistry;
            $params->loadString($field->params);
            if($params->get('show_in_requests', '') == 'yes'){
                $show_in_orders_fields[] = $field;
            }
        }

        $table->create_second_row_collumn('Title');
        
        foreach($show_in_orders_fields as $order_fields){
            $table->create_second_row_collumn($order_fields->field_name);
        }
      }

      for($i = 0; $i < count($rows_item); $i++) { 
        $request_data = array();
        $data_second_row = 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.'\',\'show_request_item\',\''.$form_name.'\')">'.$row->eiid.'</a>';

        foreach($show_fields as $key => $value){
          foreach($value as $field){
            $html = '';
            if($rows_item[$i]->fk_eid != $key){
              $request_data[] = '<div class="admin-order-standart-fields-email"></div>';
              continue;
            }
            if($field->field_type == 'categoryfield'){
              $request_data[] = "<div class='admin-order-standart-fields-email'>$rows_item[$i]->category</div>";
              continue;
            }
            ?>
            
              <?php
              $entityInstance = new os_cckEntityInstance($db->_db);
              $entityInstance->load($rows_item[$i]->eiid);
              $value = $entityInstance->getFieldValue($field);
              

              $html .= '<div><span class="col_box" style="display:block;'.($field->field_type=='imagefield'  && isset($field->options['width']) && isset($field->options['height']))? 'width:'.$field->options['width'].'px; height:'.$field->options['height'].'px;':''.'">';
                  
              ob_start();
                require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
                $html .= ob_get_contents();
              ob_end_clean();
              $html .= '</span></div>';
              $request_data[] = $html;
                     
          }
        }
        $request_data[] = $rows_item[$i]->created;
        $request_data[] = $rows_item[$i]->entity;
        $class = 'row' . ($i % 2) . ' '; 
        if($rows_item[$i]->notreaded === 1){
            $class .= ' admin-order-not-readed';
        }
//        var_dump($rows_item[$i]->notreaded);
        
        $table->create_first_row_data($request_data, $class);

        
        $parentInstance = new os_cckEntityInstance($db->_db);
        $parentInstance->load($rows_item[$i]->fid_parent);
        
        $show_in_orders_fields = array();
                
        if(isset($entityFieldLists[$parentInstance->fk_eid])){
          $fields = $entityFieldLists[$parentInstance->fk_eid];
        }else{
          $fields = array();
        }
        foreach($fields as $field){
            $params = new JRegistry;
            $params->loadString($field->params);
            if($params->get('show_in_requests', '') == 'yes'){
                $show_in_orders_fields[] = $field;
            }
        }

        
        $data_second_row[] = $parentInstance->title;
        // var_dump($show_in_orders_fields);
        foreach ($show_in_orders_fields as $field){
          // var_dump($field);
            $value = $parentInstance->getFieldValue($field);
            if(isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data') && $value[0]->data == ''){
                continue;
            }elseif($field->field_type == 'datetime_popup' && isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data') && $value[0]->data == '0000-00-00 00:00:00'){
                continue;
            }elseif($field->field_name == 'Title' && isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data') && $value[0]->data == $parentInstance->title ){ //andrew added for remove duplicate title
              continue;
            }
            $print_value = '';
            if($field->field_type == 'text_select_list'){
                $value = (isset($value[0]->data))?$value[0]->data : '';
                $value = json_decode($value);
                $params = new JRegistry;
                $params->loadString($field->params);
                $allowed_values = $params->get("allowed_value");
                $allowed_values = explode('\sprt', $allowed_values);
                $tmp_val = array();

                if(is_array($value)){

                    foreach($value as $val){

                        if(isset($allowed_values[$val])){
                            $tmp_val[] = cck_lang_text($allowed_values[$val]);
                        }
                    }
                }

                $print_value = implode(', ', $tmp_val);
                
//                                $temp_val = json_decode($value[0]->data);
//                                if(is_array($temp_val)){
//                                    $temp_val = implode(', ', $temp_val);
//                                    $print_value = $temp_val;
//                                }
//                                var_dump(json_decode($value[0]->data));
            }elseif(stripos($field->field_type, 'pricepfield') !== false){
                
                continue;
            }elseif(isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data')){
                $print_value = $value[0]->data;
            }

            
            // $data_second_row[] = $print_value;
            // var_dump(array($data_second_row));
            
//                            var_dump($value);
        }
        $table->create_second_row_data(array($data_second_row));
        

         }

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

        // $buttons = new adminHeaderButton();
        
        echo $table->viewTable();

  }

  static function showRequestItem($option, & $entityInstance, & $str_list, $recurse){
    global $os_cck_configuration,$user, $app, $session, $doc, $entities_type;

    $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_SUBMISSIONS') . "</div>";
    // $app->JComponentTitle = $html;
    // $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/jquerOs-ui.min.js");
    
    // $doc->addScript(JUri::root().'components/com_os_cck/assets/js/jquery.raty.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');
    // $doc->addScript('//maps.googleapis.com/maps/api/js');
    
    $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_requests', '');
    $table->create_button('Back', 'show_requests', '', 'fa-chevron-left');
    

    if($recurse == 1){
      $div_id = 'instance';
    }else{
      $div_id = 'psubmission';
    }  
    $html = '';
    ob_start();
    ?>
    <div id="<?php echo $div_id; ?>">
      <?php
      
      $layout_params = $str_list['layout_params'];
      $layout = $str_list['layout'];
      $bootstrap_version = $session->get( 'bootstrap','2');
//      var_dump($layout);
//      echo '11111111111'; exit;
      $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);
      $child_entities = (isset($layout_params['child_entities'])) ? $layout_params['child_entities'] : '';

      $layout_html = preg_replace("/{\|l-[0-9]*?\|}/", '', $layout_html); //remove child layouts - like add review
      $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 = $layout->getLayoutViews($entityInstance, $fields_list, $layout_html, $layout_params, $hover_animated, $option, $child_entities, $moduleId, $Itemid, 10);


      echo $layout_html;
      
      ?>
    </div>
    <?php
    
    //echo '1111111111'; exit;
    if(!empty($str_list['parent_instance']) && is_array($str_list['parent_instance'])){
        foreach($str_list['parent_instance'] as $parent_instance){
            AdminRequest::showRequestItem($option, $parent_instance->fid_parent, 1);
        }
    }
    $html = ob_get_contents();
    ob_end_clean();
    $table->set_custom_html($html);
    echo $table->viewTable();
    
  }

}
