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

  static function showUsersRentHistory($option, & $rows_item, & $return_item, &$history_item, & $userlist, $type, $show_fields,$usermenu, $sort_arr, $entity_list,$request_prices){
    global $user, $db, $entityFieldLists, $my, $entities_type;
    
//    var_dump($rows_item);
    // Load mooTools
    //JHtml::_('behavior.framework', true);
    $doc = JFactory::getDocument();
    $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_RENT_HISTORY_SHOW') . "</div>";
    $app = JFactory::getApplication();
    $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");
    
    //timepicker
    includeJavaScriptCCK("components/com_os_cck/assets/js/jquery.cck_timepicker.js");
    includeStylesCCK('components/com_os_cck/assets/css/jquery.cck_timepicker.css');

    $table = new os_cckViewTable('adminForm', 'adminForm', '', 'index.php?option=com_os_cck&task=users_rent_history', 'users_rent_history');
   
    $table->create_filters('<div>'.$userlist.'</div>');
    $table->create_filters('<div>'.$entity_list.'</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 rent_history manager
    os_cck_site_controller::create_first_row_collumns_titles($table,$show_fields,$sort_arr);
    // foreach($show_fields as $value){
    //     foreach($value as $field){
    //       if( $field->field_type=='datetime_popup'  || $field->field_type=='text_textfield'  ){
    //         $table->create_first_row_collumn(
    //           cck_sort_head($field->field_name, $field->db_field_name, $sort_arr,protectInjectionWithoutQuote('task')),
    //            '', 'admin-order-title-email');   
    //       }else{
    //         $table->create_first_row_collumn($field->field_name, $field->db_field_name, 'admin-order-title-email');   
    //       }
    //     }
    // }

    $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_LABEL_RENT_FROM'), 'rent_from', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-date'); 
    $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_LABEL_RENT_UNTIL'), 'rent_until', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-date'); 
    $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_LABEL_RENT_RETURN'), 'rent_return', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-date'); 
    $table->create_first_row_collumn(cck_lang_text('COM_OS_CCK_LABEL_SHOW_REQUEST'), '', 'admin-order-title-date'); 
    $table->create_first_row_collumn(cck_sort_head(cck_lang_text('COM_OS_CCK_LABEL_ENTITY'), 'inst_entity', $sort_arr,protectInjectionWithoutQuote('task')), '', 'admin-order-title-date'); 

    // for($i = 0; $i < count($rows_item); $i++) { 
    //     // var_dump($rows_item[$i]);
    //     $parentInstance = new os_cckEntityInstance($db->_db);
    //     $parentInstance->load($rows_item[$i]->eiid);
        
    //     $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_rent_requests', '') == 'yes'){
    //             $show_in_orders_fields[] = $field;
    //         }
    //     }

    //     $table->create_second_row_collumn('Title');
    //     $table->create_second_row_collumn('Price');
        
    //     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();
        $row = $rows_item[$i];

        $request_data[] = JHTML::_('grid.id',$i, $rows_item[$i]->eiid, ($rows_item[$i]->checked_out && $rows_item[$i]->checked_out != $my->id), 'eiid');
        $request_data[] = $rows_item[$i]->eiid;

        //add aditional fields data to rent_history 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]->rent_from;
        $request_data[] = $rows_item[$i]->rent_until;
        $request_data[] = ($rows_item[$i]->rent_return)?$rows_item[$i]->rent_return : '<b>In Rent</b>';
        $request_data[] = ($rows_item[$i]->request_id) ? '<a href="index.php?option=com_os_cck&task=show_rent_request_from_history&eiid=' . $rows_item[$i]->request_id . '">'.cck_lang_text("COM_OS_CCK_ORDERS_DETAILS").'</a>' : '';
        $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);

        $rent_requests = array();
        if( isset( $rows_item[$i]->request_id ) || !empty( $rows_item[$i]->request_id ) ) {
          //if we in rent history, and have "rent request"

            $rent_requests[] = $rows_item[$i]->request_id ; 
            $rows_item[$i]->instance_type = "Rent";

        }                    

        //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_rent', $rent_requests );

    }

    echo $table->viewTable();
    
  }


    static function showRentRequestFromHistory($option, & $entityInstance, & $str_list, $recursive, $price_fields){
        global $os_cck_configuration,$my, $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_REQUEST_RENT') . "</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/jquerOs-ui.min.js");
        // $doc->addScript(JUri::root() . 'components/com_os_cck/assets/js/jquery.raty.js');

        // $doc->addScript('//maps.googleapis.com/maps/api/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');
        
        //timepicker
        includeJavaScriptCCK("components/com_os_cck/assets/js/jquery.cck_timepicker.js");
        includeStylesCCK('components/com_os_cck/assets/css/jquery.cck_timepicker.css');

        
        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=users_rent_history', '');
            $table->create_button('Back', 'users_rent_history', '', 'fa-chevron-left');
            $table_html = '';
        
            ob_start();
        }
        if(empty($str_list['parent_instance'])){
            $div_id = 'parent_instance';

        }else{

            ?>
            <script>
                function submitbutton(pressbutton) {
                    form = document.adminForm;
                    form.task.value = pressbutton;
                    form.submit()
                }
            </script>
            <form id="adminForm" action="index.php?option=com_os_cck" method="post" name="adminForm">
                <input name="eiid[]" value="<?php echo $entityInstance->eiid;?>" type="hidden">
                <input name="option" value="com_os_cck" type="hidden">
                <!--<input name="task" value="users_rent_history" type="hidden">-->
                <input name="task" value="" type="hidden">
                <input name="boxchecked" value="1" type="hidden">
            </form>
            <?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 == ''){
                      
                      // $layout = new os_cckLayout($db->_db); commnt 15.11.2025
                      // $lid = $layout->getDefaultLayout($instance->fk_eid, 'instance');

                      // $sql = "SELECT params FROM #__os_cck_layout
                      //              \nWHERE lid =".intval($lid);

                      // $db->setQuery($sql);
                      // $params = $db->loadResult();
                      // $params = unserialize($params);

                      // //get all fields
                      // $sql =  "SHOW columns FROM #__os_cck_content_entity_" . $instance->fk_eid;
                      // //var_dump($sql); exit;
                      // $db->setQuery($sql);
                      // $cols = $db->loadColumn();

        //              foreach ($params['fields'] as $key => $field){
        //                  var_dump($key);
        //                  var_dump($field);
        //              }

                      // //search Title field if exists
                      // for($k=0;$k<count($cols);$k++){  commnt 15.11.2025
                      //   if(isset($params['fields'][$cols[$k].'_title_field']) && $params['fields'][$cols[$k].'_title_field'] == 1){
                      //       $title_field = $cols[$k];
                      //   }
                      // }
                      
                      // if(!empty($title_field)){

                      //   $sql = "SELECT fk_eiid AS id, ".$title_field." AS title_field FROM #__os_cck_content_entity_".$instance->fk_eid.
                      //     "\n WHERE fk_eiid=".intval($instance->eiid);
                      //   $db->setQuery($sql);
                      //   $row = $db->loadObject();

                      //   if(isset($row) && $row) {
                      //     $instance->meta_title = $row->title_field;
                      //   }
                      // }
                      $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>';



              //     $price_detail_html = '<div class="price_detail">';
              //     $calculated_price = 0;
              //     $quantity = 1;
              //     $not_calc_price = '';
              //     $coupon = false;
              //     foreach ($price_field as $key => $single_field){
              //         if($single_field->price_ordering == -1){
              //             $field = new os_cckEntityField($db->_db);
              //             $field->load($single_field->fk_fid);

              //             if($single_field->price_name == $single_field->price_value) {
              //                 $price_name = $field->field_name;
              //             }else{
              //                 $price_name = $field->field_name . ': ' . $single_field->price_name;
              //             }
              //             $calculated_currency = calculatedCurrency($instance, $single_field->price_value);
              //             $not_calc_price .= '<div class="not_calculated_price">' . $price_name . ' ' . $calculated_currency[0] . '</div>';
              //             unset($price_field[$key]);
              //         }elseif($single_field->price_type == 'coupon'){
              //           $coupon = $single_field;
              //         }
              //     }
              //     if($coupon){
              //           $coup_id = $coupon->fk_price_id;
              //           $coupon = new os_cckCoupons($db->_db);
              //           $coupon->load($coup_id);
              //       }
              //     if($not_calc_price != ''){
              //         echo '<div class="not_calculated_field_label">Not Calculated Fields</div>';
              //         echo '<div class="not_calculated_fields">' . $not_calc_price . '</div>';
              //         echo '<div class="calculated_field_label">Calculated Fields</div>';
              //     }

              //     foreach ($price_field as $single_field){
              //         $field = new os_cckEntityField($db->_db);
              //         $field->load($single_field->fk_fid); 
              //         if($single_field->price_value == $single_field->price_name){
              //             $name = '';
              //         }else{
              //             $name = $single_field->price_name;
              //         }
              //         if($single_field->price_type == 'base_price'){
              //               if($single_field->quantity == 0) $single_field->quantity =1;
              //               $calculated_currency = calculatedCurrency($instance, ($single_field->price_value * $single_field->quantity));
              //               $not_quantity_calculated_currency = calculatedCurrency($instance, $single_field->price_value);
              //               $tmp_price_quant = ($single_field->quantity>1) ? '(' . $not_quantity_calculated_currency[1] . ' x ' . $single_field->quantity . ')' : '';
              //               if($single_field->quantity>1) {$quantity = $single_field->quantity;}
              //               $price_detail_html .= '<div class="base_price">' . $field->field_name .  ' ' . $name. ' '  . $calculated_currency[0] . ' ' . $tmp_price_quant . '</div>';
              //               $calculated_price = $calculated_price + ($single_field->price_value * $single_field->quantity);
              //         }elseif($single_field->price_type == 'val+' && $single_field->price_value != '0.00'){
              //               $calculated_currency = calculatedCurrency($instance, ($single_field->price_value * $quantity));
              //               $not_quantity_calculated_currency = calculatedCurrency($instance, $single_field->price_value);
              //               $price_name = $field->field_name . ': ' . $single_field->price_name;
              //               $tmp_price_quant = ($quantity>1) ? '(' . $not_quantity_calculated_currency[1] . ' x ' . $quantity . ')' : '';
              //               $price_detail_html .= '<div class="val+">'.$price_name.' ' . $name.' +' . $calculated_currency[0] . ' ' . $tmp_price_quant . '</div>';
              //               $calculated_price = $calculated_price + ($single_field->price_value * $quantity);
              //           }else if($single_field->price_type == 'val-' && $single_field->price_value != '0.00'){
              //               $calculated_currency = calculatedCurrency($instance, ($single_field->price_value * $quantity));
              //               $price_name = $field->field_name . ': ' . $single_field->price_name;
              //               $not_quantity_calculated_currency = calculatedCurrency($entityInstance, $field->value);
              //               $tmp_price_quant = ($quantity>1) ? '(' . $not_quantity_calculated_currency[1] . ' x ' . $quantity . ')' : '';
              //               $price_detail_html .= '<div class="val-">'.$price_name.' ' . $name.' -' . $calculated_currency[0] . ' ' . $tmp_price_quant . ' </div>';
              //               $calculated_price = $calculated_price - ($single_field->price_value * $quantity);
              //           }else if($single_field->price_type == 'percent+' && $single_field->price_value != '0.00'){
              //               $calculated_currency = calculatedCurrency($instance, ($single_field->price_value * $quantity));
              //               $calculate_value = calculatedCurrency($instance, round($calculated_price/100 * $single_field->price_value, 2));
              //               $price_name = $field->field_name . ': ' . $single_field->price_name;
              //               $price_detail_html .= '<div class="percent+">' . $price_name . ' +' . $calculate_value[0] . ' ('. $single_field->price_value . ' %) </div>';
              //               $calculated_price = $calculated_price + (round($calculated_price/100 * $single_field->price_value, 2));
              //           }else if($single_field->price_type == 'percent-' && $single_field->price_value != '0.00'){
              //               $price_name = $field->field_name . ': ' . $single_field->price_name;
              //               $calculated_currency = calculatedCurrency($instance, ($single_field->price_value * $quantity));
              //               $calculate_value = calculatedCurrency($instance, round($calculated_price/100 * $single_field->price_value, 2));
              //               $price_detail_html .= '<div class="percent-">' . $price_name . ' -' . $calculate_value[0] . ' ('. $single_field->price_value . ' %)</div>';
              //               $calculated_price = $calculated_price - (round($calculated_price/100 * $single_field->price_value, 2));
              //           }
                      
                      
              //         //var_dump($single_field);
              //     }
              //     echo $price_detail_html . '</div>';
              //     echo '<div>Total cost of goods: ' . calculatedCurrency($instance, $calculated_price)[0] . '</div></div><br>';
              //     if($coupon){
              //           echo '<div>Coupon: ' . $coupon->name . ' ';
              //           if($coupon->type == 'percent'){
              //               echo '-'.$coupon->value.'%</div>';
              //           }else{
              //               echo '-'.calculatedCurrency($instance, $coupon->value)[0].'</div>';
              //           }
              //       }
              }
              if( count($price_fields) > 0 ) {
                  echo '<hr><div><span class="rent_from">Rent From: '.$entityInstance->rent_from;
                  echo '</span>';
                  echo '<span class="rent_to" style="margin: 0 0 0 45px;">Rent To: '.$entityInstance->rent_to;
                  echo '</span></div>';
                  echo '<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'];

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

            //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'] : '';
            //      for ($i = 0, $nnn = count($str_list['extra_fields_list']); $i < $nnn; $i++) {
            $layout_html = $layout->getLayoutViews($entityInstance, $fields_list, $layout_html, $layout_params, $hover_animated, $option, $child_entities, $moduleId, $Itemid, 10, $recursive);


      echo $layout_html;
      ?>
    </div>
    <?php
    ?><hr>
    <?php
    if(!empty($str_list['parent_instance'])){
        AdminRent_history::showRentRequestFromHistory($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
  }


}
