<?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
*/

class AdminRent_history{

  static function users_rent_history($option, $eiid){
    global $db, $user,$app, $entityFieldLists;
    $db = new os_cckDb();
      if(!JFactory::getUser()->authorise('access_to_user_rent_history', 'com_os_cck')){
          $app->enqueueMessage("Access denied", 'error');
          return;
      }
    $session = JFactory::getSession();

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

    $item_sort_param = mosGetParam($_GET, 'sort', 'l.fk_eiid');
    if (is_array($sort_arr = $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($session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $session->get('sorting_direction');
      }else{
        $sort_arr['sorting_direction']="ASC";
      }
      if ($item_sort_param == $sort_arr['field']) {
      } else {
        $sort_arr['field'] = $item_sort_param;
      }

      if($item_sort_param == 'inst_entity'){
        $sort_string = 'ce.name' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_id'){
        $sort_string = 'l.fk_eiid' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'rent_from'){
        $sort_string = 'l.rent_from' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'rent_until'){
        $sort_string = 'l.rent_until' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'rent_return'){
        $sort_string = 'l.rent_return' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == "l.fk_eiid"){
        $sort_string = $item_sort_param . " " . $sort_arr['sorting_direction'];
      }
    } else { 
      $sort_arr = array();
      if(protectInjectionWithoutQuote('sorting_direction','')){
        $sort_arr['sorting_direction'] = protectInjectionWithoutQuote('sorting_direction');
      }elseif($session->get('sorting_direction','')){ 
        $sort_arr['sorting_direction'] = $session->get('sorting_direction');
      }else{
        $sort_arr['sorting_direction']="ASC";
      }

      if($item_sort_param == 'inst_entity'){
        $sort_string = 'ce.name'. " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'inst_id'. " " . $sort_arr['sorting_direction']){
        $sort_string = 'l.fk_eiid'. " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'rent_from'){
        $sort_string = 'l.rent_from' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'rent_until'){
        $sort_string = 'l.rent_until' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == 'rent_return'){
        $sort_string = 'l.rent_return' . " " . $sort_arr['sorting_direction'];
      }else if($item_sort_param == "l.fk_eiid"){
        $sort_string = $item_sort_param. " " . $sort_arr['sorting_direction'];
      }
      $sort_arr['field'] = $item_sort_param;
    }
    
    $where = array();
    
    if ($entity_id != '' && isset($ent[$entity_id])) {
        $where[] = " a.fk_eid ='{$entity_id}'";
    }

    $session->set('eq_itemsort', $sort_arr);

    $owner = $app->getUserStateFromRequest("owner_id", 'owner_id', '');

    $rows = array();
    if( $owner !=-1 && $owner != "" ) 
      $where[] = " ( l.fk_userid=".$db->Quote($owner) ." OR l.user_name=".$db->Quote($owner). " ) " ;

      $select="SELECT a.*, cc.name AS category, l.id as rent_id, cl.params as lay_params,ce.name AS entity, l.rent_from as rent_from, " .
          "\n l.rent_return as rent_return, l.rent_until as rent_until, " .
          "\n l.user_name as user_name, l.user_email as user_email, " .
          "\n cc.rent_request AS for_rent, l.request_id as request_id" .
          "\n FROM #__os_cck_entity_instance AS a" .
          "\n LEFT JOIN #__os_cck_categories_connect AS CC_rel ON CC_rel.fk_eiid = a.eiid" .
          "\n LEFT JOIN #__os_cck_categories AS cc ON cc.cid = CC_rel.fk_cid" .
          "\n LEFT JOIN #__os_cck_layout AS cl ON cl.lid = a.fk_lid ".
          "\n LEFT JOIN #__os_cck_entity AS ce ON ce.eid = a.fk_eid ".
          "\n inner JOIN #__os_cck_rent AS l ON l.fk_eiid = a.eiid " .
          (count($where) ? " WHERE " . implode(' AND ', $where) : "") .
          "\n ORDER BY $sort_string";
      $db->setQuery($select);
      try {
        $rows = $db->loadObjectList();  
      } catch (RuntimeException $e) {
          echo "<script> alert('" . addslashes($e->getMessage()) . "'); window.history.go(-1); </script>\n";
          exit ();
      }
      //id = l.fk_eiid

      //prepere for show fields: selected for show in RentHistoryManager
      $show_fields = $entityEaaray = $layoutArray = $fieldNames = array();
      if(count($rows)>0){
        foreach ($rows as $row) {
          // $lay_params = unserialize($row->lay_params);

          //if request_id - not exist : not add fields in first row table
          if( !isset( $row->request_id ) ) continue ;

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


    $userlist[] = JHTML::_('select.option','-1', cck_lang_text('COM_OS_CCK_OPTION_ALL_USERS'));
    $db->setQuery("SELECT DISTINCT fk_userid AS value, user_name AS text from #__os_cck_rent ORDER BY user_name");
    $users = $db->loadObjectList();
    $userlist = array_merge($userlist, $users);

    foreach ($userlist as $value) {
        if(!$value->value)
            $value->value = $value->text;
        if(!$value->text){
          $value->text = '';
        }
    }
    $usermenu = JHTML::_('select.genericlist',$userlist, 'owner_id', 'class="inputbox input-medium" size="1" 
        onchange="document.adminForm.submit();"', 'value', 'text', $owner);

    $request_prices = array() ;
    foreach($rows as $request){
      $request_price = array() ;
      if( isset($request->request_id) ) {
        $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->request_id." ";
        $db->setQuery($query);
        $request_price = $db->loadObjectList();
      }
      
      $request_prices[$request->eiid] = $request_price;
    }
    
    AdminViewRentHistory:: showUsersRentHistory($option, $rows,$return_item,$history_item, $usermenu, "rent",$show_fields,$usermenu, $sort_arr, $entity_list, $request_prices);
  }

    static function showRentRequestFromHistory($option, $bid, $recursive = 1){
        global $db, $user, $app, $os_cck_state, $entityFieldLists;
        $db = new os_cckDb();

        $select_type = protectInjectionWithoutQuote('lay_type','');
        $entityInstance = new os_cckEntityInstance($db->_db);
        $entityInstance->load(intval($bid));
        if(!$entityInstance->eiid){
            return;
        }


        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        if(intval($bid)){
            $entityInstance->notreaded = 0;
            $entityInstance->store();
        }
        $extra_fields_list = $entityFieldLists[$entityInstance->fk_eid];
        $query = "SELECT fid_parent FROM #__os_cck_child_parent_connect WHERE fid_child = $entityInstance->eiid AND media_type='instance'";
        $db->setQuery($query);
        $parent_instance = $db->loadResult();
        

        $instance_layout = new os_cckLayout($db->_db);
        $eiid = $bid;
        $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=$entityInstance->eiid";
        $db->setQuery($query);
        $cart_items = $db->loadObjectList();
        // var_dump($cart_items);
        $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();
//            var_dump($price_fields);
            // $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();

        }
        // var_dump($price_fields);

        if(!isset($os_cck_state->data) ){
            echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
            return ;
        }
        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{

//        $query = "SELECT fk_coup_id FROM #__os_cck_orders WHERE fk_request_id = $entityInstance->eiid";
//
//        $db->setQuery($query);
//        $coupon = $db->loadObjectList();
//        if(!empty($coupon)){
//            $coupon = $coupon[0];
//        }
//
//        $entityInstance->_coupon = $coupon;
            $instance_layout->load(intval($entityInstance->fk_lid));
        }

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

        if(!empty($parent_instance)){
          //run only for rent request
          //not run for connected instances
          foreach ($extra_fields_list as $value) {

            if($value->field_type == 'datetime_popup'){
                if($layout_params['fields'][$value->db_field_name."_field_type"] == "rent_from"){
                    $rent_from = $entityInstance->getFieldValue($value);
                }

                if($layout_params['fields'][$value->db_field_name."_field_type"] == "rent_to"){
                    $rent_to = $entityInstance->getFieldValue($value);
                }
            }
          }

          $entityInstance->rent_from = $rent_from[0]->data ;
          $entityInstance->rent_to = $rent_to[0]->data ;
        }        

        AdminViewRentHistory :: showRentRequestFromHistory($option, $entityInstance, $str_list, $recursive, $price_fields);
    }

}
