<?php
/**
* @package OrdaSoft 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 Joomla CCK - Content Construction Kit
*/

defined('_JEXEC') or die;


class os_cckInstanceManagerView
{
   
    static function getViewIM($rows_item, $clist, $publist, $search, $pageNav, $sort_arr, $show_fields,$entity_list, $approvedlist, $userslist, $lang_list){
        global $doc, $user, $app, $session, $db, $Itemid;

        if( isset($_REQUEST['Itemid'] ) )  $Itemid = ($Itemid == 0 || empty($Itemid)) ? intval($_REQUEST['Itemid']) : $Itemid;
      
        $db = new os_cckDb();
        //The function checks whether we are in the admin area or on the frontend.
        $is_site = cck_is_site();
      
        $form_name = 'adminForm';
        $form_id = 'adminForm' ;
        if( $Itemid == 0 || empty($Itemid) ) $table = new os_cckViewTable($form_name, $form_id, 'cck-orders-main cck-instanceis-main', 
            'index.php?option=com_os_cck', 'instance_manager');
        else $table = new os_cckViewTable($form_name, $form_id, 'cck-orders-main cck-instanceis-main', 
            'index.php?option=com_os_cck&Itemid='.$Itemid, 'instance_manager');

        if(!$is_site){
          $what_check = 'instance' ;
          $table->create_button('Edit', 'edit_instance', 
            JURI::root() . 'components/com_os_cck/images/btn_edit.png', 'fa-pencil-square-o','',$what_check);
          if( checkOsCckVersionProFree() == "pro" ) $table->create_button('Copy', 'copy_instance', 
            JURI::root() . 'components/com_os_cck/images/btn_copy.png', 'fa-files-o','',$what_check);
          $table->create_button('Publish', 'publish_instances', 
            JURI::root() . 'components/com_os_cck/images/published.png', 'fa-check','',$what_check);
          $table->create_button('Unpublish', 'unpublish_instances', 
            JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-close','',$what_check);
          $table->create_button('Add', 'new_instance', 
            JURI::root() . 'components/com_os_cck/images/btn_add.png', 'fa-plus', '', 'false');
          $table->create_button('Delete', 'remove_instances', 
            JURI::root() . 'components/com_os_cck/images/btn_d.png', 'fa-close','',$what_check);
          $table->create_button('Rent return', 'rent_return', 
            JURI::root() . 'components/com_os_cck/images/btn_edit.png', 'fa-pencil-square-o','',$what_check);
          $table->create_button('Edit rent', 'edit_rent', 
            JURI::root() . 'components/com_os_cck/images/btn_edit.png', 'fa-pencil-square-o','',$what_check);
          $table->create_button('Rent', 'add_rent', 
            JURI::root() . 'components/com_os_cck/images/btn_edit.png', 'fa-pencil-square-o','',$what_check);
          $table->create_button('Mark as viewed', 'is_readed', 
            JURI::root() . 'components/com_os_cck/images/btn_s.png', 'fa-check','',$what_check);

          if( checkOsCckVersionProFree() == "pro" ) {
            $avaibleUpdate = false;
            $xml = @simplexml_load_file(JPATH_BASE . "/components/com_os_cck/os_cck.xml");
            if($xml){
              $version = (string)$xml->version;
              $creationDate = (string)$xml->creationDate;
              unset($xml);

              //check update
              $url="http://ordasoft.com/xml_update/os_cck.xml";
              $ch = curl_init();
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0); 
              curl_setopt($ch, CURLOPT_TIMEOUT, 1);

              $data = curl_exec($ch);

              $data = curl_exec($ch);
              $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

              if( !curl_errno($ch) && $code == 200 ){

                $xml = simplexml_load_string($data);
                $updateArticleUrl = '#';
                $versionArr = explode(".", $version);
                if($xml && isset($xml->version)){
                    $ordasoft_version = (string)$xml->version;
                    $ordasoft_versionArr = explode(".", $ordasoft_version);
                    $ordasoftCreationDate = (string)$xml->creationDate;
                    $updateArticleUrl = (string)$xml->updateArticleUrl;
                    unset($xml);
                    foreach ($versionArr as $k => $ordasoftSubV) {
                        if(isset($ordasoft_versionArr[$k])){
                            if((int)$ordasoft_versionArr[$k] < (int)$ordasoftSubV){
                                break;
                            }
                            if((int)$ordasoft_versionArr[$k] > (int)$ordasoftSubV){
                                $avaibleUpdate = true;
                                break;
                            }
                        }
                    }
                }

              }
              curl_close($ch);

            }

            $update = 'unavaible';
            if( $avaibleUpdate ||  checkOsCckActivationNeed()  ) $update = 'avaible';
            if($update == 'avaible'){
              $about_version_icon = JURI::root() . 'components/com_os_cck/images/yes-update.png';
            }else{
              $about_version_icon = JURI::root() . 'components/com_os_cck/images/no-update.png';
            }
            $button_class = 'update-'.$update;
            $table->create_button('', 'about_version', '', 'fa-bell icon-'. $button_class, 'right-button cck-about', 'false', 'false');
          }
          $table->create_button('Help', '', '', 'fa-question', 'right-button cck-help-button', 'false', 'false');
        }
        if (version_compare(JVERSION, "4.0.0", "ge")) {
            $bs_delimiter = '-bs';
        } else {
            $bs_delimiter = '';
        }


        $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>'.$approvedlist.'</div>');
        $table->create_filters('<div>'.$userslist.'</div>');
        $table->create_filters('<div>'.$clist.'</div>');
        $table->create_filters('<div>'.$entity_list.'</div>');
        if(JLanguageMultilang::isEnabled()){
          $table->create_filters('<div>'.$lang_list.'</div>');
        }

        $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'), 'width:3%;', '');
        $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_ID'), 'inst_id', $sort_arr), 'width:5%;', '');

        //add aditional field to InstancesManager
        os_cck_site_controller::create_first_row_collumns_titles($table,$show_fields,$sort_arr);
        // 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), 'width:10%;', '');

        //   }
        // }

        $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_LABEL_ENTITY'), 'inst_entity', $sort_arr), 'width:7%;', '');
        if(JLanguageMultilang::isEnabled()){
          $table->create_first_row_collumn(cck_lang_text('COM_OS_CCK_LABEL_INSTANCE_LANGUAGE'), 'width:5%;', '');
        }
        if (JFactory::getUser()->authorise('access_to_rent_requests', 'com_os_cck')){
          $table->create_first_row_collumn(cck_lang_text('COM_OS_CCK_LABEL_RENT'), 'width:5%;', '');
        }
        $table->create_first_row_collumn(cck_lang_text('COM_OS_CCK_LABEL_PUBLIC') .' / '. cck_lang_text('COM_OS_CCK_LABEL_APPROVED'), 'width:8%;', '');
        $table->create_first_row_collumn(cck_lang_text('COM_OS_CCK_LABEL_CONTROL'), 'width:5%;', '');

        $session->set('sorting_direction', $sort_arr['sorting_direction']);

        $n = count($rows_item) ;
        for ($i = 0; $i < $n; $i++) {
          $first_row_data = array();
          $row = & $rows_item[$i];
          // var_dump($row->notreaded);
          if ($row->checked_out && $row->checked_out != $user->id) { 
            $first_row_data[] = '';
            $first_row_data[] = $row->eiid;
        } else {
            $first_row_data[] = JHTML::_('grid.id',$i, $row->eiid, ($row->checked_out && $row->checked_out != $user->id), 'eiid');
            $first_row_data[] = '<a href="?option=com_os_cck&Itemid='.$Itemid.'&task=edit_instance&eiid[]='.$row->eiid.'">'.$row->eiid.'</a>';
          }

          //add additional field data to InstanceManager
          $first_row_data = array_merge($first_row_data, os_cck_site_controller::create_first_row_collumns_data($table,$row,$show_fields) );  
          // foreach($show_fields as $key => $value_temp){
          //   foreach($value_temp as $field){

          //     if($row->fk_eid != $key){
          //       $first_row_data[] = '';
          //       continue;
          //     }
          //     if($field->field_type == 'categoryfield'){
          //       $first_row_data[] = $row->category;
          //       continue;
          //     }

          //       $entityInstance = new os_cckEntityInstance($db->_db);
          //       $entityInstance->load($row->eiid);
          //       $value = $entityInstance->getFieldValue($field);
          //       $layout_params = array();
          //       if(isset($value[0]) && $value[0]->data && strlen($value[0]->data) > 40)
          //       {
          //           $layout_params['fields']['description_'.$field->db_field_name] = 'on';
          //           $layout_params['fields'][$field->db_field_name.'_tooltip'] = htmlspecialchars(strip_tags($value[0]->data));
          //           $value[0]->data = strip_tags(substr($value[0]->data,0,40) . '..');
          //       }
          //       // var_dump($value);
          //       $temp_row_data = '';
          //       $temp_row_data .= '<div style="margin-right:15px";>';
          //       $temp_row_data .= '<span class="col_box" style="display:block;';
          //       $temp_row_data .= ($field->field_type=='imagefield' && isset($field->options['width']) && isset($field->options['height']))? 'width:'.$field->options['width'].'px; height:'.$field->options['height'].'px;':'';
          //       $temp_row_data .= '">';
          //       $temp_row_data_html = '';
          //       ob_start();
          //         require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
          //         $temp_row_data_html .= ob_get_contents();
          //       ob_end_clean();
          //       $temp_row_data .= '<a href="?option=com_os_cck&Itemid='.$Itemid.'&task=edit_instance&eiid[]='.$row->eiid.'">'.$temp_row_data_html.'</a>';
          //       $temp_row_data .= '</span></div>';
          //       $first_row_data[] = $temp_row_data;
          //   }
          // } 

          $first_row_data[] = $row->entity;
          if(JLanguageMultilang::isEnabled()){
            $first_row_data[] = $row->lang;
          }
          if (JFactory::getUser()->authorise('access_to_rent_requests', 'com_os_cck')){
            $temp_row_data = '';
            if ($row->rent_from == null) {

              $temp_row_data .= '<img src=\''.
               JUri::root() .'components/com_os_cck/images/lend_f2.png\' align=\'middle\' width=\'15\' height=\'15\' border=\'0\' alt=\'Rent out\'/><br/>';

            } else {

              $temp_row_data .= '<img src=\''.
               JUri::root().'components/com_os_cck/images/lend_return_f2.png\' align=\'middle\' width=\'15\' height=\'15\' border=\'0\' alt=\'Return item\'/><br/></a>';

            }

            $first_row_data[] = $temp_row_data;
          }

          $task = $row->published ? 'unpublish_instances' : 'publish_instances';
          $alt = $row->published ? 'Unpublish' : 'Publish';
          $img = $row->published ? 'tick.png' : 'publish_x.png';
          $task1 = $row->approved ? 'unapprove_instances' : 'approve_instances';
          $alt1 = $row->approved ? 'Unapproved' : 'Approved';
          $img1 = $row->approved ? 'tick.png' : 'publish_x.png';
          $img = JUri::root()."components/com_os_cck/images/{$img}";
          $img1 = JUri::root()."components/com_os_cck/images/{$img1}";

          $temp_row_data = '';

          if (JFactory::getUser()->authorise('publish_instances', 'com_os_cck')){
            $temp_row_data .= '<a href="javascript: void(0);" onClick="return listItemTask(\'cb'.$i.
              '\',\''.$task.'\',\''.$form_name.'\')">';
          }

          $temp_row_data .= '<img src="'.$img.'" width="12" height="12" border="0" alt="'.$alt.'"/>';
          if (JFactory::getUser()->authorise('publish_instances', 'com_os_cck')){
            $temp_row_data .= '</a>';
          }
          $temp_row_data .= ' / ';
          if (JFactory::getUser()->authorise('publish_instances', 'com_os_cck')){
            $temp_row_data .= '<a href="javascript: void(0);" onClick="return listItemTask(\'cb'.$i.
              '\',\''.$task1.'\',\''.$form_name.'\')">';
          }

          $temp_row_data .= '<img src="'.$img1.'" width="12" height="12" border="0" alt="'.$alt1.'"/>';
          if (JFactory::getUser()->authorise('publish_instances', 'com_os_cck')){
            $temp_row_data .= '</a>';
          }
          $first_row_data[] = $temp_row_data;

          if ($row->checked_out) {
            $first_row_data[] = $row->editor;
          }else{
            $first_row_data[] = '';
          }


          $first_row_data_class = 'row' . ($i % 2) . ' '; 

          $not_readed = ($row->notreaded != 0)?'not-readed':'';
          // var_dump($not_readed);
          $first_row_data_class .= ' ' . $not_readed;
          // var_dump($first_row_data_class);
          $table->create_first_row_data($first_row_data, $first_row_data_class);

      }
        $table->pageNav = $pageNav;
//        $table->paginator = $pageNav->getListFooter();
//        var_dump($pageNav->getListFooter());
        $im_html = $table->viewTable();
//        var_dump($im_html); exit;
        return $im_html;

        
        
//        return $im_html;
    }

}


