<?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 os_cck_site_controller{
  //os cck controller class

static function prepere_field_for_show($field, $value,$row=0)
{
    global $moduleId ;
    $field->options['strlen'] = 100;
    $field->options['width'] = 100;
    $field->options['height'] = 100;
    if ($field->published != "1") return "";
    $ftype = $field->field_type;
    $global_settings = unserialize($field->global_settings);
    $db_columns = unserialize($field->db_columns);
    $sufix = '';
    if ($ftype == 'text_textfield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = (strlen($value) > $field->options['strlen']) ? substr($value, 0, $field->options['strlen']) . "..." : $value;
        return $return;
    }elseif ($ftype == 'categoryfield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = $value;
        return $return;
    }elseif ($ftype == 'decimal_textfield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = $value;
        return $return;
    }elseif ($ftype == 'rating_field') {
        return '<img src="'.JURI::root().'/components/com_os_cck/images/rating-'.($value->data*2).'.png"
                alt="'.$value->data.'" border="0"/>&nbsp;';
    } else if ($ftype == 'datetime_popup') {
        $value = (isset($value->data) && $value->data != '0000-00-00 00:00:00') ? $value->data : '';
        $format=($global_settings['output_format']!="") ? ($global_settings['output_format']) : ($global_settings['input_format']);
        $value = date(str_replace('%','',$format), strtotime($value));
        return $value;
    } else if ($ftype == 'filefield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '') $return = '<a href="' . JURI::root() . $value . '" > download </a>';
        return $return;
    } else if ($ftype == 'imagefield') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        $width_heigth = (isset($field->options['width'])) ? ' width="' . $field->options['width'] . 'px" ' : '';
        $width_heigth .= (isset($field->options['height'])) ? ' height="' . $field->options['height'] . 'px" ' : '';
        if ($value != '') {
            $image = show_image_cck($value, $field->options['width'], $field->options['height']);
            $return = '<img src="' . JURI::root() . $image . '"  /><br />';
        }
        return $return;
    } else if ($ftype == 'locationfield') {
        $layout_params = array();
        $layout_params['map_field_name'] = $field->field_name;
        $width = (isset($field->options['width'])) ? $field->options['width'] : '';
        $heigth = (isset($field->options['height'])) ? $field->options['height'] : '';
        $field->settings = unserialize($field->global_settings);
        if($row){
            $fieldName=str_replace(' ','_',($row->title.'_'.$field->field_name));
        }else{
            $fieldName=str_replace(' ','_',$field->field_name);
        }
        ob_start();
        showLocationMap($layout_params,false, $fieldName
            , $value->{$field->field_name . "_vlat"}
            , $value->{$field->field_name . "_vlong"}
            , $value->{$field->field_name . "_zoom"}
            , $value->{$field->field_name . "_adress"}
            , $field->settings['maptype']
            , $width
            , $heigth

        );
    
        $return = ob_get_contents();
        ob_end_clean();

        return $return;
    } 
//    else if ($ftype == 'galleryfield') {
//        
//        $width_heigth = (isset($field->options['width'])) ? 'width:' . $field->options['width'] . 'px;' : '';
//        $width_heigth .= (isset($field->options['height'])) ? ' height:' . $field->options['height'] . 'px;' : '';
//        $return = '';
//
//        if(!empty($value) && $images = json_decode(base64_decode($value->data))){
//            $return .= "<div class='gallery_".$field->field_name."' id='gallery_".$field->field_name."'>";
//            $images = json_decode(base64_decode($value->data));
//
//            foreach ($images as $image) {
//                if (!isset($_REQUEST['view']) || $_REQUEST['view'] != 'category')
//                    $return .= '<a href="' . JURI::root() . 'images/com_os_cck' . $field->fid . '/original/' . $image->file . '" data-lightbox="roadtrip_'.$field->field_name.$moduleId.'" title="' . $image->alt . '">';
//                $return .= '<img style="' . $width_heigth . '" src="' . JURI::root() . 'images/com_os_cck' . $field->fid . '/thumbnail/' . $image->file . '"  />';
//                if (!isset($_REQUEST['view']) || $_REQUEST['view'] != 'category') $return .= '</a>';
//                if (isset($_REQUEST['view']) && $_REQUEST['view'] == 'category') break;
//            }
//            return $return . "</div>";
//        }
//    } 
    else if ($ftype == 'text_radio_buttons') {
        $value = (isset($value->data)) ? $value->data : '';
      $return = '';
      $arr = array();
      $allowed_values = urlencode($global_settings['allowed_values']);
      if (strpos($allowed_values, '%0D%0A') !== false) $allowed_values = explode('%0D%0A', $allowed_values);
      else if (strpos($allowed_values, '%0D') !== false) $allowed_values = explode('%0D', $allowed_values);
      else if (strpos($allowed_values, '%0A') !== false) $allowed_values = explode('%0A', $allowed_values);
      else return "Bad set 'allow value' for this field!";
      foreach ($allowed_values as $item) {
          $key_value = explode('%7C', $item);
          if ($key_value[0] == $value) $return = (isset($key_value[1]))?urldecode($key_value[1]):urldecode($key_value[0]);
      }
      return $return;
    } else if ($ftype == 'text_select_list') {
        $value = (isset($value->data)) ? $value->data : '';
          $return = '';
          $arr = array();
          $allowed_values = $global_settings['allowed_values'];
          $allowed_values = urlencode($allowed_values);
          if (strpos($allowed_values, '%0D%0A') !== false) $allowed_values = explode('%0D%0A', $allowed_values);
          else if (strpos($allowed_values, '%0D') !== false) $allowed_values = explode('%0D', $allowed_values);
          else if (strpos($allowed_values, '%0A') !== false) $allowed_values = explode('%0A', $allowed_values);
          else return "Bad set 'allow value' for this field!";
          foreach ($allowed_values as $key => $allow_value) {
            $allow_value = str_replace("+", ' ', $allow_value);
            $allowed_values[$key] = trim(urldecode($allow_value));
          }
          foreach ($allowed_values as $item) {
              //echo ":1111111111:".$item.":1111111111:".$value.":1111111111:";
              $key_value = explode('|', $item);
              if(!isset($key_value[0]) && isset($key_value[1])){
                $key_value[0] = str_replace(' ', '', $key_value[1]);
              }
              //print_r($key_value);
              if($key_value[0] !== 0){
                if ($key_value[0] == $value and count($key_value) > 1) $return = $key_value[1];
                else if ($key_value[0] == $value) $return = $key_value[0];
              }
          }
          return $return;
    } else if ($ftype == 'text_single_checkbox_onoff') {
        $value = (isset($value->data)) ? $value->data : '';
      $return = '';
      $arr = array();
      $allowed_values = str_replace(' ', '', $global_settings['allowed_values']);
      $allowed_values = urlencode($allowed_values);
      if (strpos($allowed_values, '%0D%0A') !== false) $allowed_values = explode('%0D%0A', $allowed_values);
      else if (strpos($allowed_values, '%0D') !== false) $allowed_values = explode('%0D', $allowed_values);
      else if (strpos($allowed_values, '%0A') !== false) $allowed_values = explode('%0A', $allowed_values);

      foreach ($allowed_values as $key => $item) {
        $key_value = explode('%7C', $item);
        if (isset($key_value[0]) && isset($key_value[1]) && $key_value[0] == $value) $return = urldecode($key_value[1]);
        else if (isset($key_value[0]) && !isset($key_value[1]) && $key_value[0] == $value) $return = urldecode($key_value[0]);
        else if (!isset($key_value[0]) && isset($key_value[1]) && $key_value[1] == $value) $return = urldecode($key_value[1]);
        else if (count($allowed_values) == 2 && empty($value) && $key == 0){
          if (isset($key_value[0]) && isset($key_value[1])) 
            $return = urldecode($key_value[1]);
          else
            $return = urldecode($key_value[0]);
        }
      }
      return $return;

    } else if ($ftype == 'text_textarea') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
//       if($value!=''){
//         $return = '<textarea class="text_area" type="text"  rows="'.$field->options['rows'].'" cols="'.$field->options['cols'].'" readonly="true" > '.$value.'</textarea>' ;
//       }
        if ($value != '') $return = (strlen($value) > $field->options['strlen']) ? substr($value, 0, $field->options['strlen']) . "..." : $value;

        return $return;

    } else if ($ftype == 'text_url') {
        $value = (isset($value->data)) ? $value->data : '';
        $return = '';
        if ($value != '' && $value != 'http://') {
            $return = '<a href="' . $value . '">' . $value . '</a>';
        }
        return $return;
    } else {
        return 'Canity test. Error - Bad type sellected!';
    }
}

  static function checkFile() {
      $path = protectInjectionWithoutQuote("path");
      $filename = basename(protectInjectionWithoutQuote("file"));
      $file = $path . $filename;
      if (file_exists($file)) {
          echo "The file with such name already is!";
      } else {
          echo "";
      }
  }


  static function paypal(){
    global $db, $os_cck_configuration;
    $db = new os_cckDb();
    $operation=protectInjectionWithoutQuote('operation');
    
    if(isset($operation) && $operation == 'success') {
//        $dispatcher = JDispatcher::getInstance();
        $plugin_name = $os_cck_configuration->get('use_paypal', 0);
        $plugin = JPluginHelper::importPlugin( 'payment',$plugin_name);
        $plugin2 = JPluginHelper::getPlugin('payment',$plugin_name);
        $plugin_params = new JRegistry($plugin2->params);
        //$plugin_params = $plugin->get('params');
        $a = '';
        $userName = '';
        $userEmail = '';
        $html = JFactory::getApplication()->triggerEvent('onValidateIPN');
        
        if($plugin_params->get('paypal_acc_type') == '1' && $html){ //PayPal PRO
            $userId  = intval(protectInjectionWithoutQuote('userId','','INT'));
            
            if($userId){
                $sql = "SELECT  name,username,email FROM  `#__users` WHERE id= '".$userId."'";
                $db->setQuery($sql);
                $result = $db->loadObjectList();
                $result = $result['0'];
                $userName = $result->name;
                $userEmail = $result->email;
            }
            if(!$userName)$userName = protectInjectionWithoutQuote('first_name');
            if(!$userEmail)$userEmail = protectInjectionWithoutQuote('payer_email');
            $instId = intval(protectInjectionWithoutQuote('instId'));
            
            if($instId){

                $status = protectInjectionWithoutQuote('RESPMSG');
                if($status == 'Approved'){
                    $status = 'Completed';
                }
                $payer_id = intval(protectInjectionWithoutQuote('userId'));
                $txn_id = protectInjectionWithoutQuote('PNREF');
                $txn_type = protectInjectionWithoutQuote('METHOD');
                $payer_status = protectInjectionWithoutQuote('RESPMSG');
                
                $mc_gross = protectInjectionWithoutQuote('AMT');
                //$order_currency_code = protectInjectionWithoutQuote('mc_currency');
                $orderId = intval(protectInjectionWithoutQuote('orderId'));
                $order_currency_code = protectInjectionWithoutQuote('currency_code');
                $raw_data = urlencode( serialize($_REQUEST) );
                $itemName = protectInjectionWithoutQuote("item_name",'');

                $params_array = array();
                $params_array['payer_id']  = $payer_id;
                $params_array['txn_id']  = $txn_id;
                $params_array['txn_type']  = $txn_type;
                $params_array['mc_gross']  = $mc_gross;
                $params_array['order_currency_code']  = order_currency_code;
                $params_array['raw_data']  = $raw_data;
                $params_array['itemName']  = $itemName;
                $params_array['userId']  = $userId;
                $params_array['instId']  = $instId;
                $params_array['userEmail']  = $userEmail;
                $params_array['userName']  = $userName;
                $params_array['payer_status']  = $payer_status;
                $params_array['order_currency_code']  = $order_currency_code;

                cckUpdateOrderStatus($orderId, $status, '', 'com_os_cck', $params_array);
                
                // $sql = "UPDATE #__os_cck_orders SET order_date = now(), status='" . $status . "',
                //         payer_id='".$payer_id."',
                //         order_price='".$mc_gross."',
                //         order_currency='".$order_currency_code."',
                //         txn_id='".$txn_id."',
                //         txn_type='".$txn_type."',
                //         paid_price='".$mc_gross."',
                //         notreaded=1,
                //         paid_currency='".$order_currency_code."',
                //         payer_status='".$payer_status."' WHERE id = '".$orderId."'";
                // $db->setQuery($sql);
                // $db->execute();
                //
                // $sql = "INSERT INTO #__os_cck_orders_details( fk_order_id, fk_user_id, fk_instance_id,
                //                                               instance_title, user_email, user_name, status,
                //                                               order_date,txn_type, txn_id, payer_id, payer_status,
                //                                               order_price, order_currency, payment_details)
                //         VALUES ('".$orderId."','".$userId."','". $instId ."',
                //                 '".$itemName."','".$userEmail."','".$userName."','".$status."',
                //                 now(),'".$txn_type."','".$txn_id."',  '".$payer_id."',
                //                 '".$payer_status."',  '".$mc_gross."', '".$order_currency_code."',
                //                 ".$db->Quote($raw_data).")";
                // $db->setQuery($sql);
                // $db->execute();
            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_PAYPAL_ERROR"), 'warning');
                return;
            }
            echo cck_lang_text("COM_OS_CCK_PAYPAL_SUCCESS_PAYMENT");
        }else{
            if(isset($html[0]))$html = $html[0];
            if(protectInjectionWithoutQuote('payer_email','') || (is_array($html) && count($html)>2) ){
                $userId  = intval(protectInjectionWithoutQuote('userId','','INT'));
                if($userId){
                    $sql = "SELECT  name,username,email FROM  `#__users` WHERE id= '".$userId."'";
                    $db->setQuery($sql);
                    $result = $db->loadObjectList();
                    $result = $result['0'];
                    $userName = $result->name;
                    $userEmail = $result->email;
                }
                if(!$userName)$userName = protectInjectionWithoutQuote('first_name');
                if(!$userEmail)$userEmail = protectInjectionWithoutQuote('payer_email');
                $instId = intval(protectInjectionWithoutQuote('instId'));
                if($instId){

                    $status = protectInjectionWithoutQuote('payment_status');
                    $payer_id = intval(protectInjectionWithoutQuote('payer_id'));
                    $txn_id = intval(protectInjectionWithoutQuote('txn_id'));
                    $txn_type = protectInjectionWithoutQuote('txn_type');
                    $payer_status = protectInjectionWithoutQuote('payer_status');
                    $mc_gross = protectInjectionWithoutQuote('mc_gross');
                    $order_currency_code = protectInjectionWithoutQuote('mc_currency');
                    $orderId = intval(protectInjectionWithoutQuote('orderId'));
                    $raw_data = urlencode( serialize($_REQUEST) );

                    $query = "SELECT * FROM #__os_cck_orders WHERE id = ".$orderId."";
                    $db->setQuery($query);
                    $old_order = $db->loadObjectList();
                    $old_status = $old_order[0]->status;

                    $itemName = protectInjectionWithoutQuote("item_name",'');

                    $params_array = array();
                    $params_array['payer_id']  = $payer_id;
                    $params_array['txn_id']  = $txn_id;
                    $params_array['txn_type']  = $txn_type;
                    $params_array['mc_gross']  = $mc_gross;
                    $params_array['order_currency_code']  = $order_currency_code;
                    $params_array['raw_data']  = $raw_data;
                    $params_array['itemName']  = $itemName;
                    $params_array['userId']  = $userId;
                    $params_array['instId']  = $instId;
                    $params_array['userEmail']  = $userEmail;
                    $params_array['userName']  = $userName;
                    $params_array['payer_status']  = $payer_status;
                    $params_array['order_currency_code']  = $order_currency_code;

                    cckUpdateOrderStatus($orderId, $status, '', 'com_os_cck', $params_array);
            
//                     if($status == 'Completed'){
//                         if($old_order[0]->instance_type == 'Rent'){
//                             $request = new os_cckEntityInstance($db->_db);
//                             $request->load($old_order[0]->fk_request_id);
//                             if($request->eiid){
//                                 Instance::accept_rent_requests('com_os_cck', array($old_order[0]->fk_request_id), 0);
//                             }
//
//                         }elseif($old_order[0]->instance_type == 'Buy'){
//                             $request = new os_cckEntityInstance($db->_db);
//                             $request->load($old_order[0]->fk_request_id);
//                             if($request->eiid){
//                                 Instance::accept_buy_requests('com_os_cck', array($old_order[0]->fk_request_id), 0);
//                             }
//                         }
//
//                     }
//                     $sql = "UPDATE #__os_cck_orders SET order_date = now(), status='" . $status . "',
//                             payer_id='".$payer_id."',
//                             order_price='".$mc_gross."',
//                             order_currency='".$order_currency_code."',
//                             txn_id='".$txn_id."',
//                             txn_type='".$txn_type."',
//                             paid_price='".$mc_gross."',
//                             notreaded=1,
//                             paid_currency='".$order_currency_code."',
//                             payer_status='".$payer_status."' WHERE id = '".$orderId."'";
//                     $db->setQuery($sql);
//                     $db->execute();
//                     $itemName = protectInjectionWithoutQuote("item_name",'');
//                     $sql = "INSERT INTO #__os_cck_orders_details( fk_order_id, fk_user_id, fk_instance_id,
//                                                                   instance_title, user_email, user_name, status,
//                                                                   order_date,txn_type, txn_id, payer_id, payer_status,
//                                                                   order_price, order_currency, payment_details)
//                             VALUES ('".$orderId."','".$userId."','". $instId ."',
//                                     '".$itemName."','".$userEmail."','".$userName."','".$status."',
//                                     now(),'".$txn_type."','".$txn_id."',  '".$payer_id."',
//                                     '".$payer_status."',  '".$mc_gross."', '".$order_currency_code."',
//                                     ".$db->Quote($raw_data).")";
//                     $db->setQuery($sql);
//                     $db->execute();
//
//                     $sql = "SELECT * FROM #__os_cck_orders_price WHERE fk_order_id=".$orderId;
//                     $db->setQuery($sql);
//                     $order_prices = $db->loadObjectList();
//
//                     foreach($order_prices as $order_price){
//                         if($order_price->quantity > 0){
//                             $sql = "SELECT quantity FROM #__os_cck_content_instances_price WHERE price_id=" . $order_price->fk_price_id;
//                             $db->setQuery($sql);
//                             $old_quantity = $db->loadResult();
//                             if($old_quantity > -1) {
//                                 if ($status == 'Completed') {
//                                     $quantity = $old_quantity - $order_price->quantity;
//                                 } elseif ($old_status != 'Completed') {
//                                     $quantity = $old_quantity;
//                                 } else {
//                                     $quantity = $old_quantity + $order_price->quantity;
//                                 }
//
//                                 $sql = "UPDATE #__os_cck_content_instances_price SET quantity = '$quantity' WHERE price_id=" . $order_price->fk_price_id;
//                                 $db->setQuery($sql);
//                                 $db->execute();
//                             }
//                         }
//                     }
                }else{
                    $app->enqueueMessage(cck_lang_text("COM_OS_CCK_PAYPAL_ERROR"), 'warning');
                    return;
                }
                echo cck_lang_text("COM_OS_CCK_PAYPAL_SUCCESS_PAYMENT");
            }
        }
    } elseif(isset($_GET['operation']) && protectInjectionWithoutQuote('operation') == 'cancel') {
        echo cck_lang_text("COM_OS_CCK_PAYPAL_UNSUCCESS_PAYMENT");
    }
  }

  static function twocheckout(){
    global $db, $os_cck_configuration;
    $db = new os_cckDb();
			$orders_det_id = protectInjectionWithoutQuote('orders_det_id');
            
            $option = $_REQUEST['option'];
            $orderid = protectInjectionWithoutQuote('merchant_order_id');
            $total = protectInjectionWithoutQuote('total');
            $currency_code = protectInjectionWithoutQuote('currency_code');
            $id = protectInjectionWithoutQuote('id');
            $groupName = protectInjectionWithoutQuote('li_0_name');
            
            if (version_compare(JVERSION, "4.0.0", "lt")) $dispatcher = JDispatcher::getInstance();
            $plugin_name = '2checkout';
            $plugin = JPluginHelper::importPlugin( 'payment', $plugin_name);

            if (version_compare(JVERSION, "4.0.0", "lt")) $html = $dispatcher->trigger('onValidateIPN', $option);
            else $html = JFactory::getApplication()->triggerEvent('onValidateIPN', $option);

      if ($html[0] == 'Success') { //потом дописать не тестовый демо!!!!!!
            
            $status = 'Completed';

            $payment_details = urlencode( serialize($_REQUEST) );
            $query = $db->getQuery(TRUE);

            $fields = array(
                $db->quoteName('status') . ' = ' . $db->quote('Completed'),
                $db->quoteName('order_price') . ' = ' . $db->quote($total),
                $db->quoteName('order_currency') . ' = ' . $db->quote($currency_code)
                );

            $query->update($db->quoteName('#__os_cck_orders'));
            $query->set($fields);
            $query->where($db->quoteName('id') . ' = '. $db->quote($orderid));

            $db->setQuery($query);
            $result = $db->execute();

            $query = $db->getQuery(TRUE);

            $fields = array(
                $db->quoteName('status') . ' = ' . $db->quote('Completed'),
                $db->quoteName('payment_details') . ' = ' . $db->quote($payment_details)
            );

            $query->update($db->quoteName('#__os_cck_orders_details'));
            $query->set($fields);
            $query->where($db->quoteName('id') . ' = '. $db->quote($orders_det_id));

            $db->setQuery($query);
            $result2 = $db->execute();
           
            
            echo '<span class="btn-large">';
            echo cck_lang_text("COM_OS_CCK_PAYPAL_SUCCESS_PAYMENT");
            echo '</span>';
            
      } else {
                    
                JFactory::getApplication()->enqueueMessage(cck_lang_text("COM_OS_CCK_PAYPAL_ERROR"), 'warning');
                return;
        }       
  }

  static function ajax_rent_calcualete($eiids,$ceid,$rent_from,$rent_until){
      
    $resulArr = calculatePriceCCK($eiids,$ceid,$rent_from,$rent_until);

    echo json_encode(array("success"=>true,"price"=>$resulArr["price"],"not_currency_value"=>$resulArr["price"], "print_value"=>$resulArr["calculatedCurrency"][0],"currency"=>$resulArr["currency"],"calculated_currency"=>$resulArr["calculatedCurrency"]));
    exit;
  }

  static function saveInstance($option){
    global $db, $user,$task, $Itemid, $app, $os_cck_state, $entityFieldLists, $input;
    $db = new os_cckDb();
    $instance = new os_cckEntityInstance($db->_db);
    //A call to the general save function.
    $instance->saveInstance();

    $lay_type = $input->get('lay_type');
//     // var_dump($_REQUEST);
//     // var_dump($lay_type);
//     //              exit;
    $query = "SELECT c.title,c.lid,c.params,c.fk_eid ,c.mail, ch.layout_html, c.type FROM #__os_cck_layout AS c"
            ."\n LEFT JOIN #__os_cck_entity_instance AS ei ON c.lid = ei.fk_lid"
            ."\n LEFT JOIN #__os_cck_layout_html AS ch ON c.lid = ch.fk_lid"
            ."\n WHERE c.lid = ".$lay_type. " limit 1 ";

    try {
        $db->setQuery($query);
        $layout = $db->loadObjectList();
    }catch (Exception $e){
        echo $query;
        exit;
    }
    
    $Itemid  = intval(protectInjectionWithoutQuote('Itemid'));
    $id = intval(protectInjectionWithoutQuote('eiid'));
    $catid = intval(protectInjectionWithoutQuote('catid',''));



    if($catid)
      $catid = '&catid='.$catid;
    // var_dump($input->get('task', ''));
    //   var_dump($_SERVER['HTTP_REFERER']);
    //   var_dump($post['redirect']); exit;
    if(!empty($id) && $id > 0 && (!isset($post['redirect']) || $post['redirect'] == '') && $input->get('task', '') != 'apply_instance'){
    //    print_r($_SERVER['HTTP_REFERER']);
    // exit;
      //JRoute::_("index.php?option=$option&view=instance&id=$id"."$catid&Itemid=$Itemid")
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
      $app->redirect('index.php?option=' . $_REQUEST['option'] . '&task=instance_manager&Itemid='.$Itemid);
    }elseif($post['redirect'] == 'instance_manager'){
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
      $app->redirect('index.php?option=' . $_REQUEST['option'] . '&task=instance_manager&Itemid='.$Itemid);
    }elseif($post['redirect'] != ''){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
        $app->redirect($post['redirect']);
    }else{
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
      $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
    }

  }

  static function send_buy_request($option){
    global $db, $user,$task, $app, $os_cck_state, $entityFieldLists, $session, $input;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    $post = $_POST;
    $data = $post;
    if(isset($data['g-recaptcha-response']) || isset($data['plg_captcha_recaptcha_os_action'])){
          $config = JFactory::getConfig();
          $captha_type = $config->get('captcha', '');
          $captcha = JCaptcha::getInstance($captha_type, array('namespace' => $data['recaptcha_namespace']));
          if($captcha){
              $get_answer = protectInjectionWithoutQuote('g-recaptcha-response', "");
              if($get_answer == ''){
                $get_answer = protectInjectionWithoutQuote('plg_captcha_recaptcha_os_action', "");
              }
              
              if(!$get_answer ) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }

              $answer = $captcha->checkAnswer($get_answer);
              //$answer = $captcha->checkAnswer('captcha_keystring_rent_request');
              if(!$answer) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }
          }

      }
    

    $instance = new os_cckEntityInstance($db->_db);


    $input = JFactory::getApplication()->input;
    
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $requireLogin = $input->get('requireLogin', '', 'STRING');
    if($requireLogin == '1'){
        $user = JFactory::getUser();
        if($user->id == 0){
            $login_url = $input->get('login_url', '', 'STRING');
            $fields_val = array();
            $fields_val[$post['fk_eiid']] = array();
            foreach($post as $key => $val){
                if(stripos($key, 'fi_') === 0){
                    $fields_val[$post['fk_eiid']][$key] = $val;
                }
            }
            
            $session->set('price_fields', $input->get('price_fields', '', 'STRING'));
            $session->set('fields_val', $fields_val);
            if($login_url != ''){
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_LOGIN_PLEASE"), 'warning');
                $app->redirect($login_url);
            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_LOGIN_PLEASE"), 'warning');
                return;
            }
        }
    }
    
    
    
    
    $coupon_id = $input->get('coupon_id', '', 'STRING');
    if($coupon_id == ''){
        $coupon_val = $input->get('coupon', '', 'STRING');
        if($coupon_val != ''){
            $coup = self::ajaxCheckCoupon(1);
            
            if($coup['success']){
                $coupon_id = $coup['coup_id'];
            }else{
                echo '<script>alert("'.$coup['error_text'].'");</script>';
            }
        }
    }
    
    //var_dump($coupon_id); exit;
    if($coupon_id != ''){
        $coupon = new os_cckCoupons($db->_db);
        $coupon->load($coupon_id);
        $coupon->used_number += 1;
    }

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

    $price_fields = $input->get('price_fields', '', 'STRING');
    $price_fields = json_decode($price_fields);


    $total_price = 0;
    $сart_item = 0;
    // $used_coupon = false;
    $parentIdsArr = array();
    $parent_instance_id_first_from_cart = 0 ;
    foreach ($price_fields as $key1 => $fields){
        foreach($fields as $key2 => $field){
            if($parent_instance_id_first_from_cart == 0 ) $parent_instance_id_first_from_cart = $key2 ;
            $parentIdsArr[$key2]['eiid'] = $key2;
            $parentIdsArr[$key2]['сart_item'] = $сart_item;
            //$parentIdsArr[$key2]['price_field'] = $field[0];

            $calculated_price = getCalculatedPrice($field, $key2, 51, $coupon_id);
           
            $parentIdsArr[$key2]['price_without_coupon'] = $calculated_price['price_without_coupon'];
            $parentIdsArr[$key2]['coupon_discount'] = $calculated_price['coupon_discount'];
            $parentIdsArr[$key2]['result_price'] =  $calculated_price['calculated_price'];
            
            $total_price += $calculated_price['calculated_price'];
            $сart_item++;
        }
    }

    $parent_instance_id = intval(protectInjectionWithoutQuote('fk_eiid'));
    if( $parent_instance_id != 0 ){
        //we not in cart, Parent 1
        $parentIns = new os_cckEntityInstance($db->_db);
        $parentIns->load($parent_instance_id);
    } else {
        //we in cart with many Parents items
        $parentIns = new os_cckEntityInstance($db->_db);
        $parentIns->load($parent_instance_id_first_from_cart);
    }    

    $temp_price_count = 0;
    foreach($price_fields as $instance_price){
        foreach($instance_price as $key => $prices){
            foreach($prices as $price){
                if($price && property_exists($price, 'fid')) {
                    $price_fields_assoc[$temp_price_count][$key][$price->fid] = $price;
                }
            }
        }
        $temp_price_count++;
    }


    $coupon_for_rowData = new stdClass();
    if($coupon_id != ''){
        $coupon_for_rowData->coup_id = $coupon->coup_id;
        $coupon_for_rowData->name = $coupon->name;
        $coupon_for_rowData->type = $coupon->type;
        $coupon_for_rowData->value = $coupon->value;
        $coupon_for_rowData->entities = $coupon->entities;
        $coupon_for_rowData->user_group_ids = $coupon->user_group_ids;
        $coupon_for_rowData->category_ids = $coupon->category_ids;
    }
    
    
    $calculated_price = $total_price;
    $data = $post;
    
    
    $quantity = 0;
    foreach ($price_fields as $fields){
        
        foreach($fields as $key => $field){
            if(isset($field->quantity)){
                $quantity = $field->quantity;
                continue;
            }
            foreach ($field as $price_field){
                if(isset($price_field->quantity)){
                    $quantity = $price_field->quantity;
                }
            }
        }
    }
    //var_dump($quantity); exit;
    if($quantity == 0){
        echo "<script> alert('The quantity of goods ordered cannot be zero'); window.history.go(-1); </script>\n";
        exit ();
    }
  
    
    
    
    //select add clild firlds for sale
    $select_list = array();
    foreach ($data as $key => $value) {
       if(stripos($key,'fi_text_select_list_') !== false){
        $select_id = str_ireplace('fi_text_select_list_', '', $key);
          $select_list[] = $instance->getField($select_id);
       }
    }
    //select add clild firlds for sale

    $data['fields_data'] = array();
    foreach ($post as $key => $var) {
      if (strpos($key, 'fi_') === 0) $data['fields_data'][str_replace('fi_', '', $key)] = $var;
    }
    //   print_r($data['fields_data']);
    // exit;
    $query = "SELECT c.fk_eid FROM #__os_cck_layout as c WHERE c.lid=".protectInjectionWithoutQuote('lay_type');
    $db->setQuery($query);
    $data['fk_eid'] = $db->loadResult();
    $data['created'] = get_curent_site_time();

    $data['title'] = protectInjectionWithoutQuote('title','');
    $data['asset_id'] = 0;
    if(!isset($post['categories'])){
      $data['categories'] = array();
    }
    $data['fk_userid'] = $user->id;
    $data['fk_lid'] = protectInjectionWithoutQuote('lay_type','');
    $data['published'] = 1;
    $data['approved'] = 1;
    $data['checked_out'] = 0;
    $data['checked_out_time'] = '0000-00-00 00:00:00';
    $data['changed'] = '0000-00-00 00:00:00';
    $data['teid'] = 0;
    
    
    $instance->fields_data = '';
    $instance->categories = '';
    if (!$instance->bind($data)) {
//      var_dump($instance->getError()); exit;  
      echo "<script> alert('$instance->getError()'); window.history.go(-1); </script>\n";
      exit ();
    }
    
    //entity_name, entity_tbale_name
    $entitty = new os_cckEntity($db->_db);
    $entitty->load($instance->fk_eid);
    $instance->_entity_name = $entitty->name;
    $instance->_entity_table_name = "#__os_cck_entity_" . $entitty->name;
    $query = "SELECT c.title,c.lid,c.params,c.fk_eid ,c.mail, ch.layout_html FROM #__os_cck_layout AS c"
            ."\n LEFT JOIN #__os_cck_entity_instance AS ei ON c.lid = ei.fk_lid"
            ."\n LEFT JOIN #__os_cck_layout_html AS ch ON c.lid = ch.fk_lid"
            ."\n WHERE c.lid = ".protectInjectionWithoutQuote('lay_type') . " limit 1 ";
    $db->setQuery($query);
    $layout = $db->loadObjectList();
    $instance->_field_list = $entitty->getFieldList($layout[0]->layout_html);
    $instance->_field_list = array_merge($instance->_field_list, $select_list);
    $layout_params = unserialize($layout[0]->params);
    $instance->_layout_params = $layout_params['fields'];
    $instance->_layout_html = $layout[0]->layout_html;
    //$instance->instance_price = $parentIns->instance_price; 
    $instance->instance_price = $calculated_price;
    $instance->instance_currency = $parentIns->instance_currency;

    $user = JFactory::getUser();
    $instance->fk_userid = $user->id;
    if (!$instance->require_check()) {
      echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
      exit ();
    }
    
    $instance->store();

    if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
        && isset($parent_instance_id) && $parent_instance_id != 0 ){

        $query = "INSERT INTO #__os_cck_child_parent_connect (media_type,fid_parent,fid_child)"
             ."\n VALUES ('instance',$parent_instance_id,$instance->eiid)";
        $db->setQuery($query);
        $db->execute();
    }else{
        foreach($parentIdsArr as $key => $value){
            //$key ===  parent_instance_id
            $query = "INSERT INTO #__os_cck_child_parent_connect (media_type,fid_parent,fid_child)"
                 ."\n VALUES ('instance',$key,$instance->eiid)";
            $db->setQuery($query);
            $db->execute();
        }
    } 

    $instance_for_rowData = new stdClass();
    $instance_for_rowData->eiid = $instance->eiid;
    $instance_for_rowData->_field_list = $instance->_field_list;



    $Itemid  = intval(protectInjectionWithoutQuote('Itemid'));
    $id = intval(protectInjectionWithoutQuote('fk_eiid'));
    $catid = intval(protectInjectionWithoutQuote('catid',''));
    if($catid)
      $catid = '&catid='.$catid;

    //JRoute::_("index.php?option=$option&view=instance&id=$id"."$catid&Itemid=$Itemid")
    $backLink = JRoute::_($_SERVER['HTTP_REFERER']);

    $selected_payment_systems = array();
    $os_cck_configuration = JComponentHelper::getParams('com_os_cck');
    
    $payment_systems = $os_cck_configuration->get("payment_systems",array());
    if(!empty($payment_systems)){
        foreach ($payment_systems as $system){
            $query = "SELECT enabled FROM #__extensions WHERE element='$system' AND folder='payment'";
            $db->setQuery($query);
            $status = $db->loadResult();
            if($status){
                $selected_payment_systems[] = $system;
            }
        }
    }else{
    
        if($os_cck_configuration->get("use_paypal",'0') != '0'){
          $paypal_plugin = $os_cck_configuration->get("use_paypal");

          $query = "SELECT enabled FROM #__extensions WHERE element='$paypal_plugin' AND folder='payment'";
          $db->setQuery($query);
          $status = $db->loadResult();

          if($status){
            $selected_payment_systems[] = 'paypal';
          }
        }
        if($os_cck_configuration->get("use_2checkout",'0')){
          $query = "SELECT enabled FROM #__extensions WHERE element='2checkout'";
          $db->setQuery($query);
          $status = $db->loadResult();
          if($status){
            $selected_payment_systems[] = '2checkout';
          }
        }
        if($os_cck_configuration->get("use_stripe",'0')){
          $query = "SELECT enabled FROM #__extensions WHERE element='stripe'";
          $db->setQuery($query);
          $status = $db->loadResult();
          if($status){
            $selected_payment_systems[] = 'stripe';
          }
        }
    }
    

    //insert into orders
    $userId= $user->get("id","");
    $userEmail = $user->get("email","");
    $userName = $user->get("name","");

    $instTitle = protectInjectionWithoutQuote('title','');

    $total_price = $calculated_price;
    
    $rowData = array();
    $rowData['coupon'] = $coupon_for_rowData;
    $rowData['instance'] = $instance_for_rowData;
    
    $sql = "INSERT INTO  #__os_cck_orders(fk_user_id, fk_instance_id, fk_request_id,instance_type, instance_title, user_email , user_name , status,
                                        txn_type, order_date , order_price, order_currency, notreaded, quantity)
            VALUES ('".$userId."', '".$parent_instance_id."','".$instance->eiid."','Buy', '".$instTitle."', '".$userEmail."',
                    '".$userName."', 'Pending', 'Buy request','".get_curent_site_time()."','".$total_price."', '".$parentIns->instance_currency."', 1, '". $quantity . "')";
    $db->setQuery($sql);
//    var_dump($instance); exit;
    $db->execute();
    $orderId = $db->insertid();
    $serialize_str = urlencode( serialize($rowData) );
    $sql = "INSERT INTO #__os_cck_orders_details( fk_order_id, fk_user_id, fk_instance_id,
                    instance_title, user_email, user_name, status,
                    order_date,txn_type,quantity, row_data, payment_details, comment)
            VALUES (".$orderId.",'".$userId."','". $parent_instance_id ."',
                    '".$instTitle."','".$userEmail."','".$userName."','Pending',
                    '".get_curent_site_time()."','Buy request','" . $quantity . "','" . $serialize_str . "', '', '')";
    $db->setQuery($sql);
    $db->execute();
    
    
    $layout_mail = new os_cckLayout($db->_db);
    $layout_mail->load($instance->fk_lid);

//    $layout_html = urldecode($layout_mail->getLayoutHtml('2'));
    $layout_html = urldecode($layout[0]->layout_html);


    //old code - where we can have ONE mail field in layout
    if(!isset($layout_params['mail_fields']) && strpos($layout_html,"{|f-cck_mail|}")){
        $app->enqueueMessage(cck_lang_text("Email send not work. Please create new email fieled in this layout!!!"), 'warning');
    }        

    //new code mail send - where we can have many mails fields in layout
    if( strpos($layout_html,"{|f-cck_mail_") ) {

        $mail_data = array(); 
        $mail_data['mail'] = unserialize($layout_mail->mail);
        $mail_data['request_instance_fields_data'] = $data['fields_data'] ;
        $mail_data['mail_fields'] = $layout_params['mail_fields'] ;
        $mail_data['order_id'] = $orderId ;

        if( isset($coupon_id) && $coupon_id != '') $mail_data['coupon_id'] = $coupon_id ;
        if( isset($coupon) ) $mail_data['coupon'] = $coupon ;
        $mail_data['mail_event'] = "create";
        
        $parent_fields_data = array();
        if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
            && isset($parent_instance_id) && $parent_instance_id != 0 ){

            $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

            //run after correct $parentIdsArr defined
            $parent_fields_data = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc );

        } 
        $mail_data['parent_instances_fields_data'] = $parent_fields_data ;

        cckSendMailEvent($mail_data, $parentIdsArr, $instance );
    }    


    $instTitleArr = array();
    foreach ($price_fields as $cart_item => $fields){
        foreach($fields as $key => $field){
            
            foreach ($field as $price_field){
                if($price_field == null){continue;}
                $query = "SELECT * FROM #__os_cck_content_instances_price WHERE price_id='$price_field->value'";

                $db->setQuery($query);
                $row = $db->loadObjectList();
                if(empty($row)) continue;
                $field = new os_cckEntityField($db->_db);
                  $field->load($price_field->fid);

                  $layout = new os_cckLayout($db->_db);
                  $layout->load($price_field->lid);
                  $layout_params = unserialize($layout->params);

                  $calculate_ordering = (isset($layout_params['fields'][$field->db_field_name . '_calculation_order'])) ? $layout_params['fields'][$field->db_field_name . '_calculation_order'] : 0;
                    if(property_exists($price_field, 'calculated') && $price_field->calculated == 0){
                        $calculate_ordering = -1;
                    }
                  $calculate_type = (isset($layout_params['fields'][$field->db_field_name . '_price_type'])) ? $layout_params['fields'][$field->db_field_name . '_price_type'] : 'base';
                  $field_quantity = (isset($price_field->quantity)) ? $price_field->quantity : 0;

                $sql = "INSERT INTO #__os_cck_orders_price (fk_order_id, fk_price_id, fk_eid, fk_eiid, fk_fid, price_name, price_value, quantity, price_type, price_ordering, сart_item)"
                        . "VALUES ('$orderId', '$price_field->value', '" . $row[0]->fk_eid . "', '" . $row[0]->fk_eiid . "', '" . $row[0]->fk_fid . "' , '" . $row[0]->price_name . "', '" . $row[0]->price_value."' , '" . $field_quantity."', '" . $calculate_type."', '" . $calculate_ordering."', '" . $cart_item."' )";

                $db->setQuery($sql);
                try {
                    $db->execute();
                }catch (Exception $e){
                    echo $sql;
                    exit;
                }

                $temp_inst = new os_cckEntityInstance($db->_db);
                $temp_inst->load($row[0]->fk_eiid);
                // var_dump(getInstanceTitle($temp_inst));
                $instTitleArr[] = getInstanceTitle($temp_inst);

            }
        }
    }
    // var_dump($instTitleArr);
    $instTitle = implode(', ', $instTitleArr);
    if($coupon_id != ''){
        $sql = "INSERT INTO #__os_cck_orders_price (fk_order_id, fk_price_id, fk_eid, fk_eiid, fk_fid, price_name, price_value, quantity, price_type, price_ordering, сart_item)"
                . "VALUES ('$orderId', '$coupon_id', '" . $row[0]->fk_eid . "', '" . $row[0]->fk_eiid . "', '0' , '" . $coupon->name . "', '" . $coupon->value."' , '1', 'coupon', '52', '0' )";
        //var_dump($sql); exit;
        $db->setQuery($sql);
        $db->execute();
        
        $coupon->store();
    }
    
    clear_os_cart();
    
//    $query = "UPDATE #__os_cck_entity_instance SET quantity = '" . $total_quantity . "' WHERE eiid='".$parent_instance_id."'";
//    $db->setQuery($query);
//    $db->execute();
    $_REQUEST['OrderID'] =$orderId;
    $_REQUEST['userId'] = $userId;

    //end
    $instance->title = $instTitle;
    HTML_os_cck::showBuyRequestThanks($backLink, $selected_payment_systems, $instance, $calculated_price);

  }

  static function send_rent_request($option){
    global $db, $user,$task, $app, $input, $os_cck_state, $entityFieldLists, $os_cck_configuration, $session;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if(isset($data['g-recaptcha-response']) || isset($data['plg_captcha_recaptcha_os_action'])){
          $config = JFactory::getConfig();
          $captha_type = $config->get('captcha', '');
          $captcha = JCaptcha::getInstance($captha_type, array('namespace' => $data['recaptcha_namespace']));
          if($captcha){
              $get_answer = protectInjectionWithoutQuote('g-recaptcha-response', "");
              if($get_answer == ''){
                $get_answer = protectInjectionWithoutQuote('plg_captcha_recaptcha_os_action', "");
              }
              
              if(!$get_answer ) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }

              $answer = $captcha->checkAnswer($get_answer);
              //$answer = $captcha->checkAnswer('captcha_keystring_rent_request');
              if(!$answer) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }
          }
          // echo '1111111111111111';
      }
    $input = $app->input;
    $post = $_POST;
    $Itemid  =intval(protectInjectionWithoutQuote('Itemid'));
    $id = intval(protectInjectionWithoutQuote('fk_eiid'));
    $catid = intval(protectInjectionWithoutQuote('catid',''));
    if($catid)
      $catid = '&catid='.$catid;

    // if(JPluginHelper::isEnabled('payment','paypal')){
    //   if(empty($post['calculated_price'])){
    //     $app->redirect(JRoute::_("index.php?option=$option&view=instance&id=$id"."$catid&Itemid=$Itemid"),cck_lang_text("COM_OS_CCK_LABEL_REQUEST_PRICE_ERROR"));
    //   }
    // }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $requireLogin = $input->get('requireLogin', '', 'STRING');
    if($requireLogin == '1'){
        $user = JFactory::getUser();
        if($user->id == 0){
            $login_url = $input->get('login_url', '', 'STRING');
            $fields_val = array();
            $fields_val[$post['fk_eiid']] = array();
            foreach($post as $key => $val){
                if(stripos($key, 'fi_') === 0){
                    $fields_val[$post['fk_eiid']][$key] = $val;
                }
            }
//            var_dump($post); exit;
            
            $session->set('price_fields', $input->get('price_fields', '', 'STRING'));
            $session->set('fields_val', $fields_val);
            if($login_url != ''){
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_LOGIN_PLEASE"), 'warning');
                $app->redirect($login_url);
            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_LOGIN_PLEASE"), 'warning');
                return;
            }
        }
    }
    
    $coupon_id = $input->get('coupon_id', '', 'STRING');
    
    if($coupon_id == ''){
        $coupon_val = $input->get('coupon', '', 'STRING');
        if($coupon_val != ''){
            $coup = self::ajaxCheckCoupon(1);
            
            if($coup['success']){
                $coupon_id = $coup['coup_id'];
            }else{
                echo '<script>alert("'.$coup['error_text'].'");</script>';
            }
            
        }
        
        
    }
    
    
    if($coupon_id != ''){
        
        $coupon = new os_cckCoupons($db->_db);
        $coupon->load($coupon_id);
        $coupon->used_number += 1;
//        var_dump($coupon); exit;
    }

    $parent_instance_id = intval(protectInjectionWithoutQuote('fk_eiid'));
    $instance = new os_cckEntityInstance($db->_db);
    $parentIns = new os_cckEntityInstance($db->_db);
    $parentIns->load($parent_instance_id);
    $data = $post;
    
    $price_fields = $input->get('price_fields', '', 'STRING');
    $price_fields = json_decode($price_fields);

    $price_fields_assoc = array();
//     foreach($price_fields as $price){
//         if($price && property_exists($price, 'fid')) {
//             $price_fields_assoc[$price->fid] = $price;
//         }
//     }

      $temp_price_count = 0;
      $coupon_id = "" ;
      foreach($price_fields as $price){

        if($price && property_exists($price, 'fid') ) {

            if($price && !property_exists($price, 'quantity')) {
                $price->quantity = 1;
            }
            $price_fields_assoc[$temp_price_count][$parent_instance_id][$price->fid] = $price;

            $temp_price_count++;
      }
    }

    $coupon_for_rowData = new stdClass();
    if($coupon_id != ''){
        $coupon_for_rowData->coup_id = $coupon->coup_id;
        $coupon_for_rowData->name = $coupon->name;
        $coupon_for_rowData->type = $coupon->type;
        $coupon_for_rowData->value = $coupon->value;
        $coupon_for_rowData->entities = $coupon->entities;
        $coupon_for_rowData->user_group_ids = $coupon->user_group_ids;
        $coupon_for_rowData->category_ids = $coupon->category_ids;
    }
//    $calculated_price = getCalculatedPrice($price_fields, $parent_instance_id);

    //select add clild firlds for sale
    $select_list = array();
    foreach ($data as $key => $value) {
       if(stripos($key,'fi_text_select_list_') !== false){
        $select_id = str_ireplace('fi_text_select_list_', '', $key);
          $select_list[] = $instance->getField($select_id);
       }
    }
    $query = "SELECT c.title,c.lid,c.params,c.fk_eid ,c.mail, ch.layout_html FROM #__os_cck_layout AS c"
            ."\n LEFT JOIN #__os_cck_entity_instance AS ei ON c.lid = ei.fk_lid"
            ."\n LEFT JOIN #__os_cck_layout_html AS ch ON c.lid = ch.fk_lid"
            ."\n WHERE c.lid = ".protectInjectionWithoutQuote('lay_type') . " limit 1 ";
    $db->setQuery($query);
    $layout = $db->loadObjectList();
    $layout_params = unserialize($layout[0]->params);
    $field_rent_from = false;
    $field_rent_to = false;
//    var_dump($layout_params['fields']);
    foreach ($layout_params['fields'] as $key => $par){
        if(stripos($key, 'datetime_popup') !== false && stripos($key, '_field_type') !== false && $par == 'rent_from'){
            $field_rent_from = substr($key, 0, -11);
        }elseif(stripos($key, 'datetime_popup') !== false && stripos($key, '_field_type') !== false && $par == 'rent_to'){
            $field_rent_to = substr($key, 0, -11);
        }
    }
    $rent_from_format = $layout_params['fields'][$field_rent_from . '_input_format'];
    $rent_to_format = $layout_params['fields'][$field_rent_to . '_input_format'];
    
    $rent_from_time_format = isset($layout_params['fields'][$field_rent_from . '_input_time_format']) ? $layout_params['fields'][$field_rent_from . '_input_time_format'] : 'H:i:s';
    $rent_to_time_format = isset($layout_params['fields'][$field_rent_to . '_input_time_format']) ? $layout_params['fields'][$field_rent_to . '_input_time_format'] : 'H:i:s';
//    input_time_format
//    var_dump($field_rent_from);
    //select add clild firlds for sale
//    var_dump(data_transform_cck($data['rent_from'], $rent_from_format));
    $rent_from = $data['fi_'.$field_rent_from] = data_transform_cck($data['rent_from'].' '.$data['time_from'], $rent_from_format . ' ' . $rent_from_time_format);
    $rent_until = $data['fi_'.$field_rent_to] = data_transform_cck($data['rent_until'].' '.$data['time_until'], $rent_to_format . ' ' . $rent_to_time_format);
    $data['rent_from'] = $rent_from;
    $data['rent_until'] = $rent_until;
   // var_dump($layout_params['fields']);
   // var_dump($rent_from);
   // var_dump($rent_until);
   // var_dump($rent_from_format);
   // var_dump($rent_to_format);
   // exit;
    //var_dump($id); exit;

    //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
    if($os_cck_configuration->get('rent_type') == 0){

      try {
        $rent_from_temp = substr($rent_from,0,10);
        $rent_from_temp =DateTime::createFromFormat($rent_from_format,$rent_from_temp);
        $rent_from_temp = $rent_from_temp->format("Y-m-d");
        $rent_until_temp = substr($rent_until,0,10);
        $rent_until_temp =DateTime::createFromFormat($rent_to_format ,$rent_until_temp);
        $rent_until_temp = $rent_until_temp->format("Y-m-d");

        if($rent_from_temp === $rent_until_temp){
          echo "<script> alert('Sorry, not one night, selected!'); window.history.go(-1); </script>\n";
          exit;
        }
      } catch (Exception $ex) {
          echo "<script> alert('Sorry, not one night, selected!'); window.history.go(-1); </script>\n";
          exit;
      }
                          
    }

    $query = "SELECT * FROM #__os_cck_rent where fk_eiid = " . $id .
          " AND rent_return is NULL ";
        $db->setQuery($query);
        $rentTerm = $db->loadObjectList();
        
        //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
        if(isset($data['start_time']) && isset($data['finish_time']) && $os_cck_configuration->get('rent_type') == 2){
            $rangeDates = getDatesFromRange($rent_from, $rent_until);
            
            foreach($rangeDates as $date){
                $new_start_date = new stdClass();
                $new_finish_date = new stdClass();
                if($data['start_time'] != 0 && $data['start_time'] != '00:00:00'){
                    $new_start_date->rent_from = $date . ' ' . '00:00:00';
                    $new_start_date->rent_until = $date . ' ' . $data['start_time'];
                }
                if($data['finish_time'] != 0 && $data['finish_time'] != '00:00:00'){
                    $new_finish_date->rent_from = $date . ' ' . $data['finish_time'];
                    $new_finish_date->rent_until = $date . ' ' . '23:59:59';
                }
                if(property_exists($new_start_date, 'rent_from')){
                    $rentTerm[] = $new_start_date;
                }
                if(property_exists($new_finish_date, 'rent_from')){
                    $rentTerm[] = $new_finish_date;
                }
            }
        }
//        var_dump($rentTerm); exit;
//        exit;
        foreach ($rentTerm as $oneTerm){
            //rent_type == 1 - by days; rent_type == 0 - by night, rent_type == 2 - by time
            if($os_cck_configuration->get('rent_type') != 2){
                $oneTerm->rent_from = substr($oneTerm->rent_from, 0, 10);
                $oneTerm->rent_until = substr($oneTerm->rent_until, 0, 10);
                $returnMessage = checkRentCCK (($oneTerm->rent_from),($oneTerm->rent_until),
                    substr($rent_from, 0 , 10), substr($rent_until, 0 , 10));
            }else{
                $returnMessage = checkRentCCK (($oneTerm->rent_from),($oneTerm->rent_until),
                    $rent_from, $rent_until);
            }
            
            
            if($returnMessage && strlen($returnMessage) > 0){
//                var_dump($returnMessage && strlen($returnMessage) > 0); exit;
              echo "<script> alert('$returnMessage'); window.history.go(-1); </script>\n";
              exit;
            }
          }
    
    $data['fields_data'] = array();
    foreach ($data as $key => $var) {
      if (strpos($key, 'fi_') === 0) $data['fields_data'][str_replace('fi_', '', $key)] = $var;
    }
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $query = "SELECT c.fk_eid FROM #__os_cck_layout as c WHERE c.lid=".protectInjectionWithoutQuote('lay_type');
    $db->setQuery($query);
    $data['fk_eid'] = $db->loadResult();
    $data['created'] = get_curent_site_time();
    $data['title'] = protectInjectionWithoutQuote('title','');
    $data['asset_id'] = 0;
    if(!isset($post['categories'])){
      $data['categories'] = array();
    }
    $data['fk_userid'] = $user->id;
    $data['fk_lid'] = protectInjectionWithoutQuote('lay_type','');
    $data['published'] = 1;
    $data['approved'] = 1;
    $data['checked_out'] = 0;
    $data['checked_out_time'] = '0000-00-00 00:00:00';
    $data['changed'] = '0000-00-00 00:00:00';
    $data['teid'] = 0;
    $entitty = new os_cckEntity($db->_db);
    $entitty->load($data['fk_eid']);
    $instance->_entity_name = $entitty->name;
    $instance->_entity_table_name = "#__os_cck_entity_" . $entitty->name;

    $instance->instance_currency = $parentIns->instance_currency;

    //entity_name, entity_tbale_name
    
    $instance->_layout_params = $layout_params['fields'];
    $instance->_layout_html = $layout[0]->layout_html;
    $instance->_field_list = $entitty->getFieldList($instance->_layout_html);
    $instance->_field_list = array_merge($instance->_field_list, $select_list);

    $user = JFactory::getUser();
    $instance->fk_userid = $user->id;

    $calculate_price = array();

    foreach ($instance->_field_list as $field) {

      if($field->field_type == 'datetime_popup'){
        if($instance->_layout_params[$field->db_field_name.'_field_type'] == 'rent_from'){
          if($input->get('fi_'.$field->db_field_name, "")){
//            $rentFrom = $input->get('fi_'.$field->db_field_name, "");
            $rentFrom = $data['fi_'.$field->db_field_name];
          }
        }
        if($instance->_layout_params[$field->db_field_name.'_field_type'] == 'rent_to'){
          if($input->get('fi_'.$field->db_field_name, "")){
            $rentTo = $data['fi_'.$field->db_field_name];
          }
        }
      }

      if($field->field_type == 'decimal_textfield'){
        if(isset($instance->_layout_params[$field->db_field_name.'_field_type']) && $instance->_layout_params[$field->db_field_name.'_field_type'] == 'price'){
          $data['fields_data'][$field->db_field_name] = protectInjectionWithoutQuote('calculated_price','0');
        }
      }
    }
//    var_dump($rentFrom);
//    var_dump($rentTo);
//    exit;
    if(isset($rentFrom) && isset($rentTo)){
      $calculate_price = calculatePriceCCK($parent_instance_id,$data['fk_eid'],$rentFrom,$rentTo, $layout[0]->lid, $price_fields);
    }else{
      $calculate_price["price"] = 0;
    }
//    var_dump($calculate_price); exit;
    $instance->instance_price = $calculate_price["price"];
    $instance->fields_data = '';
    $instance->categories = '';
    if (!$instance->bind($data)) {
//      var_dump($instance->getError()); exit;  
      echo "<script> alert('$instance->getError()'); window.history.go(-1); </script>\n";
      exit ();
    }
//    var_dump($instance);
    if (!$instance->require_check()) {
      echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
      exit ();
    }

    $instance->store();

    $query = "INSERT INTO #__os_cck_child_parent_connect (media_type,fid_parent,fid_child)"
         ."\n VALUES ('instance',$parent_instance_id,$instance->eiid)";
    $db->setQuery($query);
    $db->execute();    

    $Itemid  = intval(protectInjectionWithoutQuote('Itemid'));
    $id = intval(protectInjectionWithoutQuote('fk_eiid'));
    $catid = intval(protectInjectionWithoutQuote('catid',''));
    if($catid)
      $catid = '&catid='.$catid;
    //JRoute::_("index.php?option=$option&view=instance&id=$id"."$catid&Itemid=$Itemid")
    //mosRedirect(JRoute::_($_SERVER['HTTP_REFERER']),cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"));

    $backLink = JRoute::_($_SERVER['HTTP_REFERER']);

    
    $selected_payment_systems = array();
    $os_cck_configuration = JComponentHelper::getParams('com_os_cck');
    if($os_cck_configuration->get("use_paypal",0)){
      $paypal_plugin = $os_cck_configuration->get("use_paypal");
      $query = "SELECT enabled FROM #__extensions WHERE element='$paypal_plugin'";
      $db->setQuery($query);
      $status = $db->loadResult();
      if($status){
        $selected_payment_systems[] = 'paypal';
      }
    }
    if($os_cck_configuration->get("use_2checkout",0)){
      $query = "SELECT enabled FROM #__extensions WHERE element='2checkout'";
      $db->setQuery($query);
      $status = $db->loadResult();
      if($status){
        $selected_payment_systems[] = '2checkout';
      }
    }
      if($os_cck_configuration->get("use_stripe",'0')){
          $query = "SELECT enabled FROM #__extensions WHERE element='stripe'";
          $db->setQuery($query);
          $status = $db->loadResult();
          if($status){
              $selected_payment_systems[] = 'stripe';
          }
      }
    //insert into orders
    $userId= $user->get("id","");
    $userEmail = $user->get("email","");
    $userName = $user->get("name","");
    $instTitle = protectInjectionWithoutQuote('title','');
    $instance_for_rowData = new stdClass();
    $instance_for_rowData->eiid = $instance->eiid;
    $instance_for_rowData->_field_list = $instance->_field_list;
    $rowData = array();
    $rowData['coupon'] = $coupon_for_rowData;
    $rowData['instance'] = $instance_for_rowData;
    //calculate price for rent
    // $calcPrice = calculatePriceCCK($parent_instance_id,$instance->fk_eid,$rent_from,$rent_until);

    //$calcPrice = $calculate_price;
    //$instance->instance_price = $calcPrice[0];
    //end
    $sql = "INSERT INTO  #__os_cck_orders(fk_user_id, fk_instance_id,fk_request_id,instance_type, instance_title, user_email , user_name , status,
                                        txn_type, order_date , order_price, order_currency, notreaded)
            VALUES ('".$userId."', '".$parent_instance_id."','".$instance->eiid."','Rent', '".$instTitle."', '".$userEmail."',
                    '".$userName."', 'Pending', 'Rent request','".get_curent_site_time()."','".$instance->instance_price."', '".$parentIns->instance_currency."', 1)";
    $db->setQuery($sql);
    $db->execute();
    $orderId = $db->insertid();
    $serialize_str = urlencode( serialize($rowData) );
    $sql = "INSERT INTO #__os_cck_orders_details( fk_order_id, fk_user_id, fk_instance_id,
                    instance_title, user_email, user_name, status,
                    order_date,txn_type, payment_details, comment, row_data)
            VALUES (".$orderId.",'".$userId."','". $parent_instance_id ."',
                    '".$instTitle."','".$userEmail."','".$userName."','Pending',
                    '".get_curent_site_time()."','Rent request', '', '', '". $serialize_str ."')";
    $db->setQuery($sql);
    $db->execute();
    
    

    $layout_mail = new os_cckLayout($db->_db);
    $layout_mail->load($instance->fk_lid);

    $layout_html = urldecode($layout[0]->layout_html);
    
    //old code - where we can have ONE mail field in layout
    if(!isset($layout_params['mail_fields']) && strpos($layout_html,"{|f-cck_mail|}")){
        $app->enqueueMessage(cck_lang_text("Email send not work. Please create new email fieled in this layout!!!"), 'warning');
    }


    //new code mail send - where we can have many mails fields in layout
    if( strpos($layout_html,"{|f-cck_mail_") ) {

        $mail_data = array(); 
        $mail_data['mail'] = unserialize($layout_mail->mail);
        $mail_data['request_instance_fields_data'] = $data['fields_data'] ;
        $mail_data['mail_fields'] = $layout_params['mail_fields'] ;
        $mail_data['order_id'] = $orderId ;
        if( isset($coupon_id) && $coupon_id != '') $mail_data['coupon_id'] = $coupon_id ;
        if( isset($coupon) ) $mail_data['coupon'] = $coupon ;
        $mail_data['mail_event'] = "create";

        $parent_fields_data = array();
        if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
            && isset($parent_instance_id) && $parent_instance_id != 0 ){

            $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

            //run after correct $parentIdsArr defined
            $parent_fields_data = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc );
            
        } 
        $mail_data['parent_instances_fields_data'] = $parent_fields_data ;
        
        cckSendMailEvent($mail_data, $parentIdsArr, $instance );
    }


    $_REQUEST['OrderID'] =$orderId;
    $_REQUEST['userId'] = $userId;

      foreach ($price_fields as  $price_field){
                  if($price_field == null){continue;}
                  $query = "SELECT * FROM #__os_cck_content_instances_price WHERE price_id='$price_field->value'";

                  $db->setQuery($query);
                  $row = $db->loadObjectList();
                  if(empty($row)) continue;

                  $field = new os_cckEntityField($db->_db);
                  $field->load($price_field->fid);

                  $layout = new os_cckLayout($db->_db);
                  $layout->load($price_field->lid);
                  $layout_params = unserialize($layout->params);

                  $calculate_ordering = (isset($layout_params['fields'][$field->db_field_name . '_calculation_order'])) ? $layout_params['fields'][$field->db_field_name . '_calculation_order'] : 0;
                  if(property_exists($price_field, 'calculated') && $price_field->calculated == 0){
                      $calculate_ordering = -1;
                  }
                  $calculate_type = (isset($layout_params['fields'][$field->db_field_name . '_price_type'])) ? $layout_params['fields'][$field->db_field_name . '_price_type'] : 'base';
                  $field_quantity = (isset($price_field->quantity)) ? $price_field->quantity : 0;

                  $sql = "INSERT INTO #__os_cck_orders_price (fk_order_id, fk_price_id, fk_eid, fk_eiid, fk_fid, price_name, price_value, quantity, price_type, price_ordering, сart_item)"
                      . "VALUES ('$orderId', '$price_field->value', '" . $row[0]->fk_eid . "', '" . $row[0]->fk_eiid . "', '" . $row[0]->fk_fid . "' , '" . $row[0]->price_name . "', '" . $row[0]->price_value."' , '" . $field_quantity."', '" . $calculate_type."', '" . $calculate_ordering."', '" . '0'."' )";
                  $db->setQuery($sql);
                  try {
                      $db->execute();
                  } catch (Exception $ex) {
                      var_dump($price_field); exit;
                  }
                  

      }
      if($coupon_id != ''){
        $sql = "INSERT INTO #__os_cck_orders_price (fk_order_id, fk_price_id, fk_eid, fk_eiid, fk_fid, price_name, price_value, quantity, price_type, price_ordering, сart_item)"
                . "VALUES ('$orderId', '$coupon_id', '" . $row[0]->fk_eid . "', '" . $row[0]->fk_eiid . "', '0' , '" . $coupon->name . "', '".$coupon->value."' , '1', 'coupon', '52', '0' )";
        $db->setQuery($sql);
        $db->execute();
        
        $coupon->store();
    }

    clear_os_cart();


    $instance->title = $instTitle;
    HTML_os_cck::showRentRequestThanks($backLink, $selected_payment_systems, $instance);

  }

  static function send_request($option){
    global $db, $user,$task,$app, $os_cck_state, $entityFieldLists;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if(isset($data['g-recaptcha-response']) || isset($data['plg_captcha_recaptcha_os_action'])){
          $config = JFactory::getConfig();
          $captha_type = $config->get('captcha', '');
          $captcha = JCaptcha::getInstance($captha_type, array('namespace' => $data['recaptcha_namespace']));
          if($captcha){
              $get_answer = protectInjectionWithoutQuote('g-recaptcha-response', "");
              if($get_answer == ''){
                $get_answer = protectInjectionWithoutQuote('plg_captcha_recaptcha_os_action', "");
              }
              
              if(!$get_answer ) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }

              $answer = $captcha->checkAnswer($get_answer);
              //$answer = $captcha->checkAnswer('captcha_keystring_rent_request');
              if(!$answer) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }
          }
          // echo '1111111111111111';
      }
    $post = $_POST;
    $parent_instance_array = explode(',', protectInjectionWithoutQuote('fk_eiid'));
    
    $instance = new os_cckEntityInstance($db->_db);
    

    $data = $post;

    //select add clild firlds for sale
    $select_list = array();
    foreach ($data as $key => $value) {
       if(stripos($key,'fi_text_select_list_') !== false){
        $select_id = str_ireplace('fi_text_select_list_', '', $key);
          $select_list[] = $instance->getField($select_id);
       }
    }
    //select add clild firlds for sale
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $data['fields_data'] = array();
    foreach ($post as $key => $var) {
      if (strpos($key, 'fi_') === 0) $data['fields_data'][str_replace('fi_', '', $key)] = $var;
    }
    $query = "SELECT c.fk_eid FROM #__os_cck_layout as c WHERE c.lid=".intval(protectInjectionWithoutQuote('lay_type', 0, 'INT'));
    $db->setQuery($query);
    $data['fk_eid'] = $db->loadResult();
    $data['created'] = get_curent_site_time();

    $data['title'] = protectInjectionWithoutQuote('title','');
    $data['asset_id'] = 0;
    if(!isset($post['categories'])){
      $data['categories'] = array();
    }
    $data['fk_userid'] = $user->id;
    $data['fk_lid'] = protectInjectionWithoutQuote('lay_type','');
    $data['published'] = 1;
    $data['approved'] = 1;
    $data['checked_out'] = 0;
    $data['checked_out_time'] = '0000-00-00 00:00:00';
    $data['changed'] = '0000-00-00 00:00:00';
    $data['teid'] = 0;
    $instance->fields_data = '';
    $instance->categories = '';
    if (!$instance->bind($data)) {
//      var_dump($instance->getError()); exit;  
      echo "<script> alert('$instance->getError()'); window.history.go(-1); </script>\n";
      exit ();
    }
    //entity_name, entity_tbale_name
    $entitty = new os_cckEntity($db->_db);
    $entitty->load($instance->fk_eid);
    $instance->_entity_name = $entitty->name;
    $instance->_entity_table_name = "#__os_cck_entity_" . $entitty->name;
    
    $query = "SELECT c.title,c.lid,c.params,c.fk_eid ,c.mail, ch.layout_html FROM #__os_cck_layout AS c"
            ."\n LEFT JOIN #__os_cck_entity_instance AS ei ON c.lid = ei.fk_lid"
            ."\n LEFT JOIN #__os_cck_layout_html AS ch ON c.lid = ch.fk_lid"
            ."\n WHERE c.lid = ".intval(protectInjectionWithoutQuote('lay_type', 0, 'INT')) . " limit 1 ";
    $db->setQuery($query);
    $layout = $db->loadObjectList();
    $layout_params = unserialize($layout[0]->params);
    $instance->_layout_params = $layout_params['fields'];
    $instance->_layout_html = $layout[0]->layout_html;

    $instance->_field_list = $entitty->getFieldList($instance->_layout_html);
    $instance->_field_list = array_merge($instance->_field_list, $select_list);
    if (!$instance->require_check()) {
      echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
      exit ();
    }
    $instance->store();

   // $parent_fields_data = array();

   foreach($parent_instance_array as $tmp_instance_id){
        if($tmp_instance_id == '') continue;
       
        $parent_instance_id = $tmp_instance_id ;
        $query = "INSERT INTO #__os_cck_child_parent_connect (media_type,fid_parent,fid_child)"
             ."\n VALUES ('instance',$parent_instance_id,$instance->eiid)";
        $db->setQuery($query);
        $db->execute();

        // $parentIns = new os_cckEntityInstance($db->_db);
        // $parentIns->load($parent_instance_id);
       
        // foreach($entityFieldLists[$parentIns->fk_eid] as $field)
        // {

        //     $field_val = $parentIns->getFieldValue($field);

        //     if(isset($field_val[0])) $field_val = $field_val[0];

        //     if(isset($field_val->data))
        //     {
        //         $parent_fields_data[$field->db_field_name] = $field_val->data;
        //     }

        //     if($field->field_type == 'datetime_popup'){
        //         unset($parent_fields_data[$field->db_field_name]);
        //     }
        // }
    }


    $layout_mail = new os_cckLayout($db->_db);
    $layout_mail->load($instance->fk_lid);

    $layout_html = urldecode($layout[0]->layout_html);
    
    //old code - where we can have ONE mail field in layout
    if(!isset($layout_params['mail_fields']) && strpos($layout_html,"{|f-cck_mail|}")){
        $app->enqueueMessage(cck_lang_text("Email send not work. Please create new email fieled in this layout!!!"), 'warning');
    }


    //new code mail send - where we can have many mails fields in layout
    if( strpos($layout_html,"{|f-cck_mail_") ) {

        $mail_data = array(); 
        $parentIdsArr = array(); 
        $mail_data['mail'] = unserialize($layout_mail->mail); ;

        $fields_for_mail = getInstanceFieldsData( $instance->eiid );
        $mail_data['request_instance_fields_data'] = $fields_for_mail ;
        // $mail_data['request_instance_fields_data'] = $data['fields_data'] ;

        $mail_data['mail_fields'] = $layout_params['mail_fields'] ;


        $parent_fields_data = array();
        $parentIdsArr = array();
        $price_fields_assoc = array();
        $coupon_id = "";
        if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
              && (isset($parent_instance_id) && $parent_instance_id != 0) ){
            
            if( isset($parent_instance_id) && $parent_instance_id != 0 ) 
                $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

            //run after correct $parentIdsArr defined
            $parent_fields_data = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc );
        }
        $mail_data['parent_instances_fields_data'] = $parent_fields_data ;
        // $mail_data['parent_instances_fields_data'][][$parent_instance_id] = $parent_fields_data ;  

        if( isset($coupon_id) && $coupon_id != '') $mail_data['coupon_id'] = $coupon_id ;
        if( isset($coupon) ) $mail_data['coupon'] = $coupon ;
        $mail_data['mail_event'] = "create";

        cckSendMailEvent($mail_data, $parentIdsArr, $instance );
    }
    
    clear_os_cart();

    $Itemid  = protectInjectionWithoutQuote('Itemid');
    $id = protectInjectionWithoutQuote('eiid');
    if($id){
      $catid = protectInjectionWithoutQuote('catid','');
      if($catid)
        $catid = '&catid='.$catid;
      //JRoute::_("index.php?option=$option&view=instance&id=$id"."$catid&Itemid=$Itemid")
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
      $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
//      $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']),cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"));
    }else{
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
      $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
//      $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']),cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"));//maybe need add in all request function HTTP_REFERER //no need get request item to set return url
    }

  }

  static function send_review_request($option){
    global $db, $user,$task, $Itemid,$app, $os_cck_state, $entityFieldLists;
    $db = new os_cckDb();
    // Params(cck component menu)
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    if(isset($data['g-recaptcha-response']) || isset($data['plg_captcha_recaptcha_os_action'])){
          $config = JFactory::getConfig();
          $captha_type = $config->get('captcha', '');
          $captcha = JCaptcha::getInstance($captha_type, array('namespace' => $data['recaptcha_namespace']));
          if($captcha){
              $get_answer = protectInjectionWithoutQuote('g-recaptcha-response', "");
              if($get_answer == ''){
                $get_answer = protectInjectionWithoutQuote('plg_captcha_recaptcha_os_action', "");
              }
              
              if(!$get_answer ) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }

              $answer = $captcha->checkAnswer($get_answer);
              //$answer = $captcha->checkAnswer('captcha_keystring_rent_request');
              if(!$answer) {
                  $app->enqueueMessage(cck_lang_text("COM_OS_CCK_INFOTEXT_JS_CAPTCHA"), 'success');
                  $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
                  // mosRedirect($_SERVER['HTTP_REFERER'], _REALESTATE_MANAGER_LABEL_ERROR_CAPTCHA);
                  exit();
              }
          }
          // echo '1111111111111111';
      }
    $menu = new JTableMenu($db->_db);
    $menu->load($Itemid);
    $params = new JRegistry;
    if($menu->params){
      $params->loadString($menu->params);
    }    
    $post = $_POST;

    $parent_instance_id = protectInjectionWithoutQuote('fk_eiid');
    $eiid = protectInjectionWithoutQuote('eiid');
//    var_dump($eiid); exit;
    $instance = new os_cckEntityInstance($db->_db);
    if($eiid > 0){
        $instance->load($eiid);
    }
    $parentIns = new os_cckEntityInstance($db->_db);
    $parentIns->load($parent_instance_id);
    $data = $post;

    //select add clild firlds for sale
    $select_list = array();
    foreach ($data as $key => $value) {
       if(stripos($key,'fi_text_select_list_') !== false){
        $select_id = str_ireplace('fi_text_select_list_', '', $key);
          $select_list[] = $instance->getField($select_id);
       }
    }
    //select add clild firlds for sale
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
    $data['fields_data'] = array();
    foreach ($post as $key => $var) {
      if (strpos($key, 'fi_') === 0) $data['fields_data'][str_replace('fi_', '', $key)] = $var;
    }

    $query = "SELECT c.fk_eid FROM #__os_cck_layout as c WHERE c.lid=".protectInjectionWithoutQuote('lay_type');
    $db->setQuery($query);
    $data['fk_eid'] = $db->loadResult();
    $data['created'] = get_curent_site_time();
    // var_dump($parentIns); exit;
    $parentIns->last_review = $data['created'];
    $parentIns->store();
    // $data['last_review'] = get_curent_site_time();

    $data['title'] = protectInjectionWithoutQuote('title','');
    $data['asset_id'] = 0;
    if(!isset($post['categories'])){
      $data['categories'] = array();
    }
    $data['fk_userid'] = $user->id;
    $data['fk_lid'] = protectInjectionWithoutQuote('lay_type','');
    $data['published'] = 1;
    $data['checked_out'] = 0;
    $data['checked_out_time'] = '0000-00-00 00:00:00';
    $data['changed'] = '0000-00-00 00:00:00';
    $data['teid'] = 0;
    $instance->fields_data = '';
    $instance->categories = '';
    $query = "SELECT c.title,c.lid,c.params,c.fk_eid ,c.mail, ch.layout_html FROM #__os_cck_layout AS c"
            ."\n LEFT JOIN #__os_cck_entity_instance AS ei ON c.lid = ei.fk_lid"
            ."\n LEFT JOIN #__os_cck_layout_html AS ch ON c.lid = ch.fk_lid"
            ."\n WHERE c.lid = ".protectInjectionWithoutQuote('lay_type') . " limit 1 ";
    $db->setQuery($query);
    $layout = $db->loadObjectList();
    $layout_params = unserialize($layout[0]->params);
    if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }

    if( isset($layout_params['views']['access_approved']) 
        && checkAccess_cck($layout_params['views']['access_approved'], $user->groups, $data['fk_eid'], 'fields'))
    {
        if(isset($layout_params['views']['layout_approve_on_add'])){
          $data['approved'] = 1;
        }else{
          $data['approved'] = 0;
        }
  
    }else{
        $data['approved'] = 0;
    }        


    if(isset($layout_params['views']['access_publish']) 
        && checkAccess_cck($layout_params['views']['access_publish'], $user->groups, $data['fk_eid'], 'instances'))
    {
        if(isset($layout_params['views']['layout_publish_on_add'])){
          $data['published'] = 1;
        }else{
          $data['published'] = 0;
        }

    }else{
        $data['published'] = 0;
    }



    if (!$instance->bind($data)) {
//      var_dump($instance->getError()); exit;  
      echo "<script> alert('$instance->getError()'); window.history.go(-1); </script>\n";
      exit ();
    }
    //entity_name, entity_tbale_name
    $entitty = new os_cckEntity($db->_db);
    $entitty->load($instance->fk_eid);
    $instance->_entity_name = $entitty->name;
    $instance->_entity_table_name = "#__os_cck_entity_" . $entitty->name;
    $instance->_layout_params = $layout_params['fields'];
    $instance->_layout_html = $layout[0]->layout_html;
    $instance->_field_list = $entitty->getFieldList($instance->_layout_html);
    $instance->_field_list = array_merge($instance->_field_list, $select_list);
    if (!$instance->require_check()) {
      echo '<script> alert("' . cck_lang_text("COM_OS_CCK_ADMIN_INFOTEXT_JS_EDIT_REQUIRED") .'"); window.history.go(-1); </script>\n';
      exit ();
    }

    $instance->store();

    $query = "INSERT INTO #__os_cck_child_parent_connect (media_type,fid_parent,fid_child)"
         ."\n VALUES ('instance',$parent_instance_id,$instance->eiid)";
    $db->setQuery($query);
    $db->execute();


   // $parent_fields_data = array();
   
   //  foreach($entityFieldLists[$parentIns->fk_eid] as $field)
   //  {

   //      $field_val = $parentIns->getFieldValue($field);

   //      if(isset($field_val[0])) $field_val = $field_val[0];

   //      if(isset($field_val->data))
   //      {
   //          $parent_fields_data[$field->db_field_name] = $field_val->data;
   //      }

   //      if($field->field_type == 'datetime_popup'){
   //          unset($parent_fields_data[$field->db_field_name]);
   //      }
   //  }

    $layout_mail = new os_cckLayout($db->_db);
    $layout_mail->load($instance->fk_lid);

    $layout_html = urldecode($layout[0]->layout_html);

    //old code - where we can have ONE mail field in layout
    if(!isset($layout_params['mail_fields']) && strpos($layout_html,"{|f-cck_mail|}")){
        $app->enqueueMessage(cck_lang_text("Email send not work. Please create new email fieled in this layout!!!"), 'warning');
    }


    //new code mail send - where we can have many mails fields in layout
    if( strpos($layout_html,"{|f-cck_mail_") ){
        $mail_data = array(); 
        $mail_data['mail'] = unserialize($layout_mail->mail) ;

        $fields_for_mail = getInstanceFieldsData( $instance->eiid );
        $mail_data['request_instance_fields_data'] = $fields_for_mail ;
        // $mail_data['request_instance_fields_data'] = $data['fields_data'] ;

        $mail_data['mail_fields'] = $layout_params['mail_fields'] ;


        $parent_fields_data = array();
        $parentIdsArr = array();
        $price_fields_assoc = array();
        $coupon_id = "";
        if( ( !isset($parentIdsArr) || count($parentIdsArr) == 0 ) 
              && (isset($parent_instance_id) && $parent_instance_id != 0) ){
            
            if( isset($parent_instance_id) && $parent_instance_id != 0 ) 
                $parentIdsArr[$parent_instance_id]['eiid'] = $parent_instance_id ;

            //run after correct $parentIdsArr defined
            $parent_fields_data = getParentsFieldsData($coupon_id, $parentIdsArr, $price_fields_assoc );
        }
        $mail_data['parent_instances_fields_data'] = $parent_fields_data ;
        // $mail_data['parent_instances_fields_data'][][$parent_instance_id] = $parent_fields_data ;  

        if( isset($coupon_id) && $coupon_id != '') $mail_data['coupon_id'] = $coupon_id ;
        if( isset($coupon) ) $mail_data['coupon'] = $coupon ;
        $mail_data['mail_event'] = "create";

        cckSendMailEvent($mail_data, $parentIdsArr, $instance );
    }   


    $Itemid  = protectInjectionWithoutQuote('Itemid');
    $id = protectInjectionWithoutQuote('fk_eiid');
    if($id){
      $catid = protectInjectionWithoutQuote('catid','');
      if($catid)
        $catid = '&catid='.$catid;
      //JRoute::_("index.php?option=$option&view=instance&id=$id"."$catid&Itemid=$Itemid")
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
      $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
    }else{
      //JRoute::_("index.php?option=$option&view=add_instance&Itemid=$Itemid")
      $app->enqueueMessage(cck_lang_text("COM_OS_CCK_LABEL_REQUEST_THANKS"), 'success');
      $app->redirect(JRoute::_($_SERVER['HTTP_REFERER']));
    }

  }

  // static function orderitem($option){
  //   global $db, $user,$app;
  //   $db = new os_cckDb();
  //   $id = (int)$_POST['itemid'];
  //   $buy_quantity = (int)$_POST['buy_quantity'];
  //   $priceid = (int)$_POST['priceid'];
  //   $date = date("Y-m-d");
  //   $query = "select * from #__os_cck_items where id='$id'";
  //   $db->setQuery($query);
  //   $item = loadObjectList();
  //   if (array_key_exists(0, $item))
  //     $item = $item[0];
  //   if ($item->quantity < $buy_quantity) {
  //     $app->redirect(JRoute::_('index.php?option=com_os_cck'), 'Order not created: exceed item quantity.');
  //     exit;
  //   }
  //   if ($item->published != 1) {
  //     $app->redirect(JRoute::_('index.php?option=com_os_cck'), 'Order not created: wrong item.');
  //     exit;
  //   }
  //   $query = "insert into #__os_cck_order (itemid, quantity, userid, date_income, status, price_plan) VALUES
  //             ('$id', '$buy_quantity', '$user->id', '$date', 'pending', '$priceid')";
  //   $db->setQuery($query);
  //   $db->execute();
  //   $app->redirect(JRoute::_('index.php?option=com_os_cck'), 'Your order successfuly added');
  // }

  static function checkCaptcha(){
      global $db, $acl,$user;
      $db = new os_cckDb();
  //*********************   begin compare to key   ***************************ч
      $session = JFactory::getSession();
      $type = protectInjectionWithoutQuote('captcha_type','');
      if(isset($_POST['keyguest']) && ($type == 'review_instance'))
        $password = $session->get('captcha_review_instance_keystring', 'default');
      if(isset($_POST['keyguest']) && ($type == 'rent_request_instance'))
        $password = $session->get('captcha_rent_request_instance_keystring', 'default');
      if(isset($_POST['keyguest']) && ($type == 'buy_request_instance'))
        $password = $session->get('captcha_buy_request_instance_keystring', 'default');
      if(isset($_POST['keyguest']) && ($type == 'add_instance'))
        $password = $session->get('captcha_add_instance_keystring', 'default');
      if(isset($_POST['keyguest']) && ($type == 'request_instance'))
        $password = $session->get('captcha_request_instance_keystring', 'default');
  //**********************   end compare to key   *****************************
 
        $session->set('keyguest', $_POST['keyguest']);
        
      if (isset($_POST['keyguest']) && ($_POST['keyguest'] != $password)) {
          print_r( json_encode(array('status'=> false)));
          exit ();
      }else{
          $status =  cck_lang_text("COM_OS_CCK_SUCCESS");
          print_r( json_encode(array("status"=>$status)));
          exit ();
      }
  }
  
  static function SecondCheckCaptcha(){
      global $db, $acl,$user;
      $db = new os_cckDb();
      
      $session = JFactory::getSession();
      $password = $session->get('captcha_add_instance_keystring', 'default');
      $keyguest = $session->get('keyguest');
      
  
  
      if ($keyguest != $password) {
          $session->set('keyguest', '');
          return FALSE;
      }else{
          $session->set('keyguest', '');
          return TRUE;
      }
  }

  //this function check - is exist houses in this folder and folders under this category
  //if( $eid > 0 ) search only category accessible for this entity
  //if $is_edit == true - search all category(and unpublish)
  static function is_exist_curr_and_subcategory_items($catid, $eid=0, $cat_all=array(), $is_edit=true){

    $db = new os_cckDb();

    $where = "" ;
    if( !$is_edit ) $where = " AND ei.published=1 AND ei.approved=1 ";  
    $query = "SELECT COUNT(ei.eiid) FROM #__os_cck_entity_instance as ei "
            . "LEFT JOIN #__os_cck_categories_connect as cc ON cc.fk_eiid = ei.eiid "
            . "LEFT JOIN #__os_cck_categories as cat ON cat.cid = cc.fk_cid "
            . "WHERE cat.cid=$catid ". $where ." ; ";
    $db->setQuery($query);
    $item_count = $db->loadResult();

    if( $item_count > 0) return true;
 
    if( count($cat_all) > 0  ){
        ;
    }else{
        $where = "" ;
        if( $eid > 0 ) $where = " where cc.fk_eid = ". $eid ." || cc.fk_eid = 0 ";
        if( $eid > 0 and !$is_edit ) $where = " where cc.fk_eid = ". $eid ." || cc.fk_eid = 0 and cc.published=1";
        if( $eid == 0 and !$is_edit ) $where = " where cc.published=1";  
        $query = "SELECT *  FROM #__os_cck_categories AS cc ". $where ." ; ";
        $db->setQuery($query);
        $cat_all = $db->loadObjectList();
        if (count($cat_all) == 0) return false;
    }

    $categories = array();
    foreach($cat_all as $cat){
        if($cat->parent_id == $catid){
            $categories[] = $cat;
        }
    }

    if( count($categories) == 0  ) return false;
 
    foreach ($categories as $k) {
      //if return not true , check nect child category
      if( self::is_exist_curr_and_subcategory_items($k->cid, $eid, $cat_all, $is_edit) ) return true;;
    }

    return false;
  }

  
  //*****************************************************************************

  //this function check - is exist folders under this category
  static function is_exist_subcategory_items($catid){
    global $db, $user;
    $db = new os_cckDb();
    $query = "SELECT *, COUNT(a.fk_cid) AS numlinks FROM #__os_cck_categories AS cc" .
      "\n JOIN #__os_cck_categories_connect AS a ON a.fk_cid = cc.cid" .
      "\n WHERE  cc.parent_id='$catid' " .
      "\n GROUP BY cc.cid" .
      "\n ORDER BY cc.ordering";
    $db->setQuery($query);
    $categories = $db->loadObjectList();

    if (count($categories) != 0) return $categories;
    if (count($categories) == 0) return false;

    foreach ($categories as $k) {
      if (is_exist_subcategory_items($k->id)) return $categories;
    }
    return false;
  }

  //end function


  /**
   * This function is used to show a list of all houses
   */


  static function cck_constructPathway($data, $type, $mod_type){
    global $app, $db, $option, $Itemid;
    $db = new os_cckDb();
    switch ($type) {
      case "category":
          //var_dump($data); exit;
        break;
    }
    $jinput = JFactory::getApplication()->input;
    $task = $jinput->getVar('view', '');
    //var_dump($task);
    if($task != '' && $task != 'all_categories' && $mod_type === 0 && $task != 'featured'){
        
        $pid = $data->cid;
        $pathway = array();
        $pathway_name = array();
        
        while ($pid != 0) {
          $query = "SELECT * FROM #__os_cck_categories ";
          $db->setQuery($query);
          $rows = $db->loadObjectlist('cid');
          $cat = $rows[$pid];
          $pathway[] = JRoute::_('index.php?option=' . $option . '&view=category&catid=' . $cat->cid . '&Itemid=' . $Itemid);
          $pathway_name[] = $cat->name;
          $pid = $cat->parent_id;
        }
        

        $breadcrumbs = $app->getPathWay();
        $pathway = array_reverse($pathway);
        $pathway_name = array_reverse($pathway_name);
        $path_way = $app->getPathway();
        $path_way_reverse = array_reverse($path_way->getPathwayNames());

        for ($i = 0, $n = count($pathway); $i < $n; $i++) {
          if(count($pathway) == 1 || (isset($path_way_reverse[0]) && $pathway_name[$i] == $path_way_reverse[0])){

          }else {
              $path_way->addItem($pathway_name[$i], $pathway[$i]);
          }
        }
        //var_dump($path_way);
    }
  }

  static function secretImageCCK($type){
    $session = JFactory::getSession();
    if($type=='review_instance'){
      $pas = $session->get('captcha_review_instance_keystring', 'default');
    }
    if($type=='rent_request_instance'){
      $pas = $session->get('captcha_rent_request_instance_keystring', 'default');
    }
    if($type=='buy_request_instance'){
      $pas = $session->get('captcha_buy_request_instance_keystring', 'default');
    }
    if($type=='request_instance'){
      $pas = $session->get('captcha_request_instance_keystring', 'default');
    }
    if($type=='add_instance'){
      $pas = $session->get('captcha_add_instance_keystring', 'default');
    }
    $new_img = new PWImageCCK();
    $new_img->set_show_string($pas);
    $new_img->get_show_image(2.2, array(mt_rand(0, 50), mt_rand(0, 50), mt_rand(0, 50)), array(mt_rand(200, 255),
        mt_rand(200, 255), mt_rand(200, 255)));
    exit();
  }



  static function userGID($oID){
    global $db, $ueConfig;
    $db = new os_cckDb();
    if ($oID > 0) {
      $query = "SELECT group_id FROM #__user_usergroup_map WHERE user_id = '" . $oID . "'";
      $db->setQuery($query);
      $gid = $db->loadResult();
      return $gid;
    } else return 0;
  }



  // static function listRssCategories(){
  //   global $db;
  //   $db = new os_cckDb();
  //   $Itemid = intval($_GET['Itemid']);
  //   $catid = protectInjectionWithoutQuote('catid');
  //   if ($catid == "") $where_catid = "";
  //   else $where_catid = " AND c.id=" . $catid;
  //   $query = "SELECT c.id as catid, c.title as ctitle, a.id,"
  //            ."\n a.description,a.title,a.image,a.edok_link,a.date,a.price"
  //            ."\n FROM #__categories as c, #__os_cck_items as a"
  //            ."\n LEFT JOIN #__os_cck_adequacy as b ON a.id=b.itemid"
  //            ."\n WHERE b.cat_id=c.id AND a.published='1' AND c.published='1'" . $where_catid;
  //   $db->setQuery($query);
  //   $cat_all = $db->loadObjectList();
  //   HTML_os_cck :: showRssCategories($cat_all, $catid);
  // }
  
  
    static function ajaxCalculatedCurrency(){
      global $os_cck_configuration, $db;
      $db = new os_cckDb();
      $input = JFactory::getApplication()->input;
            
      $selectValue = $input->get('selectValue');
      $fid = $input->get('fid', 0, 'INT');
      $eiid = $input->get('eiid', 0, 'INT');
      $lid = $input->get('lid', 0, 'INT');
      $numberFormat = json_decode($input->get('numberFormat', '', 'STRING'));

      if(is_object($numberFormat)){
          $numberFormat = (array) $numberFormat;
      }
//var_dump($numberFormat); exit;
      $entityInstance = new os_cckEntityInstance($db->_db);
      $entityInstance->load($eiid);
      
      
      $query = "SELECT price_value, quantity FROM #__os_cck_content_instances_price WHERE price_id='$selectValue'";
      $db->setQuery($query);
      $value = $db->loadObjectList();
      
      $val = calculatedCurrency($entityInstance, $value[0]->price_value, '', $numberFormat);
      
      $print_value = '';
      
      
      $print_value .= $val[0];
      
      
      echo json_encode(array("success"=>true, "print_value"=>$print_value, "quantity"=>$value[0]->quantity, "value"=>$val[1]));
      return;

  }
  
  static function ajaxCalculatedPrice(){
      global $db;
      $db = new os_cckDb();
      $input = JFactory::getApplication()->input;
      $index = $input->get('index', 0, 'INT');
      
      $eiid = $input->get('eiid', 0, 'INT');
      
      $coupon = $input->get('coupon', -1, 'INT');
      $numberFormat = json_decode($input->get('number_format', '', 'STRING'));
      if(is_object($numberFormat)){
          $numberFormat = (array) $numberFormat;
      }

      $entityInstance = new os_cckEntityInstance($db->_db);
      $entityInstance->load($eiid);

      $jsonPriceFields = $input->get('jsonPriceFields', '', 'STRING');
      $price_fields = json_decode($jsonPriceFields);
      //var_dump($coupon); exit;
      $orderingCalculateField = $input->get('orderingCalculateField', 0, 'INT');
      
      $calculated_price= getCalculatedPrice($price_fields, $eiid, $orderingCalculateField, $coupon);
      $coupon_discount = $calculated_price['coupon_discount'];
      $calculated_price = $calculated_price['calculated_price'];
      //var_dump($calculated_price);
      $currency_price = calculatedCurrency($entityInstance, $calculated_price, '', $numberFormat);
      $hidden_currency_price = calculatedCurrency($entityInstance, $calculated_price);
      $print_currency_price = '';
      //for($k = 0; $k < count($currency_price); $k++){
        //if(($k + 1) <  count($currency_price)){
        //    $print_currency_price .= $currency_price[0] . ', ';
        //}else{
            $print_currency_price .= $currency_price[0];
        //}
      //}
  	  
      echo json_encode(array("success"=>true, "print_value"=>$print_currency_price, "index"=>$index, "not_currency_value"=>$hidden_currency_price[1], "coupon_discount" => $coupon_discount));
      return;
  }
  
  static function addInstanceToCart(){
      global $session, $input, $os_cck_state;
      
      $price_fields = $input->get('price_fields', '', 'STRING');
      $eiid = $input->get('eiid', 0, 'INT');
      
      $new_product[] = array('eiid' => $eiid, 'price_fields' => $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($session->get('cart', '') != ''){
          $new_price = json_decode($price_fields);
          
          $new_quantity = 1;
          foreach ($new_price as $key => $price){
              if(isset($price->quantity)){
                  $new_quantity = $price->quantity;
                  unset ($new_price[$key]->quantity);
              }
          }
          $cart = $session->get('cart', '');
          $dublicated_item = false;
          
          foreach($cart as $cart_key => $item){
              
              if($item['eiid'] == $eiid){
                  $prices = json_decode($item['price_fields']);
                  
                  $quantity = 0;
                  if(!empty($prices) && isset($prices[0]) && property_exists($prices[0], 'fid')){
                      foreach($prices as $key => $price){


                          if(isset($price->quantity)){
                              $quantity = $price->quantity;
                              unset ($prices[$key]->quantity);
                          }

                          if(count($prices) == count($new_price)){
                              $dublic = true;
                              foreach ($prices as $price_key => $temp_price){

                                  if(!is_object($temp_price)) continue;
                                  if($temp_price->fid != $new_price[$price_key]->fid || $temp_price->value != $new_price[$price_key]->value){
                                      $dublic = false;
                                      //break;
                                  }
                              }
                              //var_dump($dublic);
                              if($dublic){
                                $prices[$key]->quantity = $quantity + $new_quantity;
                                $dublicated_item = true;
                              }
                          }
                      }
                  }else{
                      if($new_product[0]['eiid'] == $item['eiid']){
                          $dublicated_item = true;
                          $prices = json_decode($item['price_fields']);
                          
                          if(!empty($prices)){
                            $prices[0]->quantity += 1;
                          }else{
                              $price = new stdClass();
                              $price->quantity = 2;
                              $prices[] = $price;
//                              var_dump($cart[$cart_key]['price_fields']); exit;
//                              $cart[$cart_key]['price_fields'][] = $field;
                          }
                      }
                  }
                  $json_price = json_encode($prices);
                  $cart[$cart_key]['price_fields'] = $json_price;
              }   
              
          }
          if(!$dublicated_item){
            $cart = array_merge($cart, $new_product);
          }
          $session->set('cart', $cart);
          
      }else{
          $session->set('cart', $new_product);
      }
      if(!isset($os_cck_state->data) ){
        echo '<script>alert("'. cck_lang_text("COM_OS_CCK_YOUR_LICENSE_NEED_ACTIVE").'"); history.back(); </script>';
        return ;
    }
      $count = 0;
      foreach ($session->get('cart', '') as $cart){
          $price_fields = json_decode($cart['price_fields']);
          if(isset($price_fields[0]->quantity)){
              $count += $price_fields[0]->quantity;
          }else{
              $count += 1;
          }
      }
      //var_dump($session->get('cart', ''));
      echo json_encode(array("success"=>true,"cart_count"=>$count));
      return;
      
  }
  
  
  static function removeProductFromCart(){
      global $session, $input;
      
      $product_key = $input->get('keyProduct', 0, 'INT');
      $cart = $session->get('cart', '');
      if(isset($cart[$product_key])){
          unset($cart[$product_key]);
          $session->set('cart', $cart);
          $cart_count = 0;
          foreach($cart as $cart_item){
              $price_fields = json_decode($cart_item['price_fields']);
              $cart_count += $price_fields[0]->quantity;
              
          }
//          var_dump($cart_count);
          echo json_encode(array("success"=>true,"cart_count"=>$cart_count));
          return;
      }
  }
  
  static function getAjaxPriceDetails(){
      global $input;
      
      $price_fields = $input->get('jsonPriceFields', '', 'STRING');
      $price_fields = json_decode($price_fields);
      
      $instance_currency = $input->get('instance_currency', '' , 'STRING');
      $eiid = $input->get('eiid', 0, 'INT');
      
      $coup_id = $input->get('coupon', -1, 'INT');
      $numberFormat = $input->get('numberFormat', '', 'STRING');
      if($numberFormat != ''){
          $numberFormat = json_decode($numberFormat, true);
      }
      
      $price_details = get_price_details($price_fields, $eiid, $coup_id, $numberFormat);
      
      echo json_encode(array('success'=>true,'html'=>$price_details['html']));
  }
  
  static function changeCurrency($ajax = true){
      global $input, $session, $app;
      
      $currency = $input->get('currency');
//      $curent_url = $input->get('curent_url', '', 'STRING');
      
//      if(stripos($curent_url, '?currency=')){
//          $new_url = substr($curent_url, 0, (stripos($curent_url, '?currency='))) . '?currency=' . $currency;
//      }elseif(stripos($curent_url, '&currency=')){
//          $new_url = substr($curent_url, 0, (stripos($curent_url, '&currency='))) . '&currency=' . $currency;
//      }
//      var_dump($new_url);
      $session->set('currency', $currency);
      
//      $app->redirect($new_url);
//      $juri = new JURI();
//      var_dump($curent_url);
      if($ajax){
        echo json_encode(array('success'=>true));
      }
  }
  
  static function ajaxCheckCoupon($self = 0){
      global $db, $input;

      $db = new os_cckDb();
      $coupon_name = protectInjectionWithoutQuote('coupon' , '', 'STRING');
      
      if($coupon_name != ''){
        $query = "SELECT coup_id FROM #__os_cck_coupons WHERE name='$coupon_name'";
        $db->setQuery($query);
        $coup_id = $db->loadResult();
        
        if(!$coup_id){
            if($self == 0){
                echo json_encode(array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_MISSING_COUPON')));
            }
            return array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_MISSING_COUPON'));
            //exit;
        }
        
        $coupon = new os_cckCoupons($db->_db);
        $coupon->load($coup_id);
        
        if($coupon->max_uses > 0 && $coupon->used_number >= $coupon->max_uses){
            if($self == 0){
                echo json_encode(array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_MAX_USED_COUPON')));
            }
            return array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_MAX_USED_COUPON'));
            //exit;
        }
        
        $now = new DateTime();
        $date_start = new DateTime($coupon->date_start);
        $date_finish = new DateTime($coupon->date_finish);
        
        if($date_start > $now){
            if($self == 0){
                echo json_encode(array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_NOT_START_COUPON').$coupon->date_start.'!'));
            }
            return array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_NOT_START_COUPON').$coupon->date_start.'!');
            //exit;
        }
        if($date_finish < $now ){
            if($self == 0){
                echo json_encode(array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_EXPIRED_COUPON')));
            }
            return array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_EXPIRED_COUPON'));
            //exit;
        }
        
        $user = JFactory::getUser();
        
        $coupon_user_groups = explode(',', $coupon->user_group_ids);
        $coupon_user_groups = array_diff($coupon_user_groups, array(''));
        sort($coupon_user_groups);
//        var_dump($coupon_user_groups);
        if(!empty($coupon_user_groups) && !checkAccess_cck($coupon_user_groups, $user->groups)){
            if($self == 0){
                echo json_encode(array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_NOT_USER_GROUP_COUPON')));
            }
            return array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_NOT_USER_GROUP_COUPON'));
            //exit;
        }
        
        if($self == 0){
            echo json_encode(array('success'=>true, 'coup_id'=> $coup_id, 'coupon_type'=> $coupon->type));
        }
        return array('success'=>true, 'coup_id'=> $coup_id, 'coupon_type'=> $coupon->type);
      } else{
        return array('success'=>false, 'error_text'=> cck_lang_text('COM_OS_CCK_ERROR_MESSAGE_MISSING_COUPON'));
      }
  }
  
  static function fileDownload(){
    global $input, $db, $cck_entity_configuration;
    $db = new os_cckDb();
    $fid = $input->get('fid', '');
    $eiid = $input->get('eiid', '');
    
    $file = new os_cckFile($db->_db);
    $file->load($fid);
    
    $params = new JRegistry;
          
    
    $field_id = $input->get('field', '');
    $product = false;
    if($field_id != ''){
        $field = new os_cckEntityField($db->_db);
        $field->load($field_id);
        $params->loadString($field->params);
    }
    
    if($params->get('allowed_value', '') == 'on'){
        $max_download = $cck_entity_configuration[$field->fk_eid]['max_product_download'];
        $days_for_product_download = $cck_entity_configuration[$field->fk_eid]['days_for_product_download'];
        $my = JFactory::getUser();
        
        $query = "SELECT ord.* FROM #__os_cck_orders as ord "
                  . "LEFT JOIN #__os_cck_orders_price as opr ON ord.id = opr.fk_order_id "
                  . "WHERE opr.fk_eiid='$eiid' AND ord.user_email='$my->email' AND ord.status='Completed' ORDER BY ord.id DESC LIMIT 0,1";
        $db->setQuery($query);
        $order = $db->loadObjectList();
        
        
        if(!empty($order)){
            $order_date = new DateTime($order[0]->order_date);
            $now_date = new DateTime();
            $max_date = $order_date->modify($days_for_product_download . 'day');
            
            //var_dump($max_date);
            if(($max_download == 0 || $max_download > $order[0]->number_of_downloads)){
                $product = true;
            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_MAX_PRODUCT_DOWNLOADS"), 'warning');
                return; 
            }
            
            if($days_for_product_download == 0 ||$now_date < $max_date){
                $product = true;
            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_DAYS_PRODUCT_DOWNLOADS"), 'warning');
                return; 
            }
        }
        

    }
    

    
    if($file->fid != null){
        
    

        $new_temp_file = JPATH_SITE . '/' . $file->filename;
        symlink(JPATH_SITE . $file->filepath, $new_temp_file);
          
        if($product){
            $query = "UPDATE #__os_cck_orders SET number_of_downloads = '".($order[0]->number_of_downloads + 1)."' WHERE id = ".$order[0]->id."";
            $db->setQuery($query);
            $db->execute();
        }
        
        file_force_download($new_temp_file, $file->filemime);
        
        

    }elseif(!empty($result)){
//    	unactive_link($result[0]->gid);
    	echo "You are using an invalid link";

    }else{
    	echo "You are using an invalid link";
    }
  }
  
  static function pay_pal_request(){
      define("LOG_FILE", "./ipn3.log");
      
        foreach($_REQUEST as $key => $val){
            error_log(date('[Y-m-d H:i e] '). $key . " - " . $val, 3, LOG_FILE);
        }
  }
  
  static function stripe(){
    global $db, $os_cck_configuration, $app;
    $db = new os_cckDb();
    define("DEBUG", false);
    define("LOG_FILE", "./stripe.log");
//    $payload = @file_get_contents('php://input');
//var_dump(json_decode($payload));
    
    $operation=protectInjectionWithoutQuote('operation');
    $input = JFactory::getApplication()->input;
    if(isset($operation) && $operation == 'success') {
//        $dispatcher = JDispatcher::getInstance();
        $plugin_name = 'stripe';
        $plugin = JPluginHelper::importPlugin( 'payment',$plugin_name);
        $paymentIntent = json_decode($input->get('paymentIntent', '', 'STRING'));
        
        //var_dump($paymentIntent); exit;
        //$plugin_params = $plugin->get('params');
        $a = '';
        $userName = '';
        $userEmail = '';
        $pay_data = JFactory::getApplication()->triggerEvent('onValidateIPN');
//        var_dump($pay_data);
        
        if(isset($pay_data[0]))$pay_data = $pay_data[0];
        // if($pay_data['metadata']['order_id'] != protectInjectionWithoutQuote('orderId')){
        //     error_log(date('[Y-m-d H:i e] '). cck_lang_text("COM_OS_CCK_STRIPE_ERROR") . PHP_EOL, 3, LOG_FILE);
        //     // $app->enqueueMessage(cck_lang_text("COM_OS_CCK_STRIPE_ERROR"), 'warning');
        //     return;
        // }
       
        if(protectInjectionWithoutQuote('payer_email','') || count($pay_data)>2 ){
            $userId  = intval(protectInjectionWithoutQuote('userId','','INT'));
            if($userId){
                $sql = "SELECT  name,username,email FROM  `#__users` WHERE id= '".$userId."'";
                $db->setQuery($sql);
                $result = $db->loadObjectList();
                $result = $result['0'];
                $userName = $result->name;
                $userEmail = $result->email;
            }
            if(!$userName)$userName = protectInjectionWithoutQuote('first_name');
            if(!$userEmail)$userEmail = protectInjectionWithoutQuote('payer_email');
            $instId = intval(protectInjectionWithoutQuote('instId'));
            foreach($pay_data as $key => $data){
                error_log(date('[Y-m-d H:i e]'). ' pay_data - ' . $key . '-'. $data. PHP_EOL, 3, LOG_FILE);    
            }
            
            if($instId || $pay_data['metadata']['order_id']){

                $status = $pay_data['status'];

                if($status == 'succeeded'){
                    $status = 'Completed';
                }
                $payer_id = intval(protectInjectionWithoutQuote('payer_id'));
                $txn_id = $pay_data['id'];
                $txn_type = $pay_data['payment_method'];
                $payer_status = $pay_data['status'];
                $mc_gross = $pay_data['amount'];
                
                $order_currency_code = strtoupper($pay_data['currency']);
                $zero_decimal_currencies = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA',
                    'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
                if(!in_array(strtoupper($order_currency_code), $zero_decimal_currencies)){
                    $mc_gross = $mc_gross / 100;
                }
                $orderId = $pay_data['metadata']['order_id'];
                $raw_data = urlencode( serialize($pay_data) );
                $query = "SELECT * FROM #__os_cck_orders WHERE id = ".$orderId."";
                $db->setQuery($query);
                $old_order = $db->loadObjectList();
                $old_status = $old_order[0]->status;

                if($status == 'Completed'){
                    if($old_order[0]->instance_type == 'Rent'){
                        $request = new os_cckEntityInstance($db->_db);
                        $request->load($old_order[0]->fk_request_id);
                        if($request->eiid){
                            Instance::accept_rent_requests('com_os_cck', array($old_order[0]->fk_request_id), 0);
                        }

                    }elseif($old_order[0]->instance_type == 'Buy'){
                        $request = new os_cckEntityInstance($db->_db);
                        $request->load($old_order[0]->fk_request_id);
                        if($request->eiid){
                            Instance::accept_buy_requests('com_os_cck', array($old_order[0]->fk_request_id), 0);
                        }
                    }

                }
                $itemName = $pay_data['metadata']['title'];

                $params_array = array();
                $params_array['payer_id']  = $payer_id;
                $params_array['txn_id']  = $txn_id;
                $params_array['txn_type']  = $txn_type;
                $params_array['mc_gross']  = $mc_gross;
                $params_array['order_currency_code']  = $order_currency_code;
                $params_array['raw_data']  = $raw_data;
                $params_array['itemName']  = $itemName;
                $params_array['userId']  = $userId;
                $params_array['instId']  = $instId;
                $params_array['userEmail']  = $userEmail;
                $params_array['userName']  = $userName;
                $params_array['payer_status']  = $payer_status;
                $params_array['order_currency_code']  = $order_currency_code;

                cckUpdateOrderStatus($orderId, $status, '', 'com_os_cck', $params_array);

            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_STRIPE_ERROR"), 'warning');
                return;
            }
            echo cck_lang_text("COM_OS_CCK_STRIPE_SUCCESS_PAYMENT");
        }
        
    }elseif(isset($operation) && $operation == 'successV2') { 
        $payload = @file_get_contents('php://input');
        $payload = json_decode($payload);

        $plugin_name = 'stripe';
        $plugin = JPluginHelper::importPlugin( 'payment',$plugin_name);
        $paymentIntent = $payload->data->object->id;
        // $paymentIntent = 'pi_1HNJOUBuAyxWNDQIjNwg1hz0';
        $GLOBALS['paymentIntentId'] = $paymentIntent;
        //var_dump($paymentIntent); exit;
        //$plugin_params = $plugin->get('params');
        $a = '';
        $userName = '';
        $userEmail = '';
        $pay_data = JFactory::getApplication()->triggerEvent('onValidateIPN');
        
        if(isset($pay_data[0]))$pay_data = $pay_data[0];
        if(isset($pay_data['status'])){
            $status = $pay_data['status'];
        }else{
            if($pay_data['type'] == 'payment_intent.processing'){
                $status = 'Pending';
            }else{
                $status = $pay_data['type'];
            }
        }
        if($status == 'succeeded'){
            $status = 'Completed';
        }
        if(DEBUG == true) {
            //foreach($_REQUEST as $key => $val)
            error_log(date('[Y-m-d H:i e] '). " piID - " . $GLOBALS['paymentIntentId'] . PHP_EOL, 3, LOG_FILE);
            error_log(date('[Y-m-d H:i e] '). " status - " . $status . PHP_EOL, 3, LOG_FILE);
            error_log(date('[Y-m-d H:i e] '). " type - " . $payload->type . PHP_EOL, 3, LOG_FILE);

            // foreach($pay_data as $key => $data){
            //     error_log(date('[Y-m-d H:i e]'). ' pay_data - ' . $key . '-'. $data. PHP_EOL, 3, LOG_FILE);
            // }
            //echo "HTTP request of validation request";
        }
               
        if(protectInjectionWithoutQuote('payer_email','') || count($pay_data)>2 ){
            
            if(!$userName)$userName = protectInjectionWithoutQuote('first_name');
            if(!$userEmail)$userEmail = protectInjectionWithoutQuote('payer_email');
            $itemName = $pay_data['metadata']['title'];
            if($itemName){

                
                $query = "SELECT status, fk_instance_id, fk_user_id FROM #__os_cck_orders WHERE id = " . $pay_data['metadata']['order_id'];
                $db->setQuery($query);
                $result = $db->loadObjectList();

                $old_status = (isset($result[0])) ? $result[0]->status : '';
                $instId = (isset($result[0])) ? $result[0]->fk_instance_id : 0;
                $userId = (isset($result[0])) ? $result[0]->fk_user_id : 0;
                if($status == $old_status) return;
                $payer_id = intval(protectInjectionWithoutQuote('payer_id'));
                $txn_id = $pay_data['id'];
                $txn_type = $pay_data['payment_method'];
                $payer_status = $pay_data['status'];
                $mc_gross = $pay_data['amount'] / 100;
                $order_currency_code = strtoupper($pay_data['currency']);
                $zero_decimal_currencies = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA',
                    'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
                if(!in_array(strtoupper($order_currency_code), $zero_decimal_currencies)){
                    $mc_gross = $mc_gross / 100;
                }
                $orderId = $pay_data['metadata']['order_id'];
                $raw_data = urlencode( serialize($pay_data) );

                $params_array = array();
                $params_array['payer_id']  = $payer_id;
                $params_array['txn_id']  = $txn_id;
                $params_array['txn_type']  = $txn_type;
                $params_array['mc_gross']  = $mc_gross;
                $params_array['order_currency_code']  = $order_currency_code;
                $params_array['raw_data']  = $raw_data;
                $params_array['itemName']  = $itemName;
                $params_array['userId']  = $userId;
                $params_array['instId']  = $instId;
                $params_array['userEmail']  = $userEmail;
                $params_array['userName']  = $userName;
                $params_array['payer_status']  = $payer_status;
                $params_array['order_currency_code']  = $order_currency_code;

                cckUpdateOrderStatus($orderId, $status, 'Stripe', 'com_os_cck', $params_array);


            }else{
                $app->enqueueMessage(cck_lang_text("COM_OS_CCK_STRIPE_ERROR"), 'warning');
                return;
            }
            echo cck_lang_text("COM_OS_CCK_STRIPE_SUCCESS_PAYMENT");
        }     
//            var_dump(json_decode($payload));
    }elseif(isset($_GET['operation']) && protectInjectionWithoutQuote('operation') == 'cancel') {
        echo cck_lang_text("COM_OS_CCK_STRIPE_UNSUCCESS_PAYMENT");
    }elseif($operation == 'checkout'){
          $plugin_name = 'stripe';
          $plugin = JPluginHelper::importPlugin( 'payment',$plugin_name);

            if ( version_compare(JVERSION, "4.0.0-alpha10", "ge") ) { 
                JFactory::getApplication()->triggerEvent('onStripCheckout');
            } else {

             $dispatcher = JDispatcher::getInstance();
             $results = $dispatcher->trigger('onStripCheckout');
            }


    }elseif($operation == 'return'){
          echo "Your order status is \"Paid\" Please wait while Stripe check it!";
        //   var_dump($_REQUEST);
          // error_log(date('[Y-m-d H:i e] '). "Change order status, now it ".$status. PHP_EOL, 3, './ipn.log');
          return FALSE;
    }
  }
  
  static function displayCckPdfCategory($category, $instancies, $layout, $layout_params) {
      global $doc, $db, $entityFieldLists, $input, $os_cck_configuration, $entities_type;
      $pdf_structure = json_decode($layout->pdf_structure);
//      var_dump($pdf_structure);
      
  }
  
  static function displayCckPdf($category = '', $instancies = array(), $layout = '', $layout_params = '', $eiid = 0, $width = false, $pdf = false, $subcat_shift = 0) {
      global $doc, $db, $entityFieldLists, $input, $os_cck_configuration, $entities_type;
      $db = new os_cckDb();

      $k = 0;
      $not_stop = false;
      if($layout == ''){
        $lid = $input->get('lid', 0, 'INT');
        $eiid = $input->get('eiid', 0, 'INT');
        $layout = new os_cckLayout($db->_db);
        $layout->load($lid);
        $layout_params = unserialize($layout->params);
      }
      $entity = new os_cckEntity($db->_db);
      $entity->load($layout->fk_eid);
      if($layout->type == 'pdf'){
      
          $instance_layout = $layout;
      }
      if($layout->type == 'parent_child_pdf' && $eiid != 0){
          $entityInstance = new os_cckEntityInstance($db->_db);
          if($entities_type[$layout->fk_eid] == 'os_cck_entity'){
            $entityInstance->load($eiid);
          }elseif($entities_type[$layout->fk_eid] == 'joomla_user'){
              $user_id = $eiid;
              $entityInstance = ConvertEntityInstanceToUser($entity->eid, $user_id);
          }elseif($entities_type[$layout->fk_eid] == 'custom_sql'){
              $entityInstance = ConvertEntityInstanceToCustomSql($entity, $eiid);
          }
//          $entityInstance->load($eiid);
          
      }
//      var_dump($entityInstance); exit;
        $layout_form_params = new JRegistry;
        $layout_form_params = $layout_form_params->loadString($layout_params['form_params']);
//        var_dump($layout_params);
//        var_dump($layout->type);
        if(empty($instancies) && $layout->type != 'all_categories_pdf' && $layout->type != 'parent_child_pdf'){
//        if(empty($instancies) && $layout->type == 'pdf'){
            
            if($entities_type[$layout->fk_eid] == 'os_cck_entity'){
                $entityInstance = new os_cckEntityInstance($db->_db);
                $entityInstance->load($eiid);
            }elseif($entities_type[$layout->fk_eid] == 'joomla_user'){
                $entityInstance = ConvertEntityInstanceToUser($layout->fk_eid, $eiid);
            }elseif($entities_type[$layout->fk_eid] == 'custom_sql'){
                $entityInstance = ConvertEntityInstanceToCustomSql($entity, $eiid);
            }
            $instancies[] = $entityInstance;
        }
//        var_dump($instancies);
        $fields = $entityFieldLists[$layout->fk_eid];
        if($entities_type[$layout->fk_eid] == 'joomla_user' || $entities_type[$layout->fk_eid] == 'custom_sql'){
            $fields = cckConvertFieldList($fields);
        }
//        var_dump($fields);
        
        $text = array();
//        $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df';
//        $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df';
//        $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df'
//                . 'bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df';
//        $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df'
//                . 'bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df'
//                . 'bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df';
        
          $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf';
        $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs';
        $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df';
        $text[] = '<div>bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df'
                . 'bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df bvsfd sdf df vas dfb dfvasc asdf dsv fbdf sdcva ca sf dfs dfb fvAs caSc bdfb df';
        $pdf_structure = json_decode($layout->pdf_structure);
        
        $format_array = array('A0' => array( 2383.937,
3370.394), // = ( 841 x 1189 ) mm = ( 33.11 x 46.81 ) in
'A1' => array( 1683.780,
2383.937), // = ( 594 x 841 ) mm = ( 23.39 x 33.11 ) in
'A2' => array( 1190.551,
1683.780), // = ( 420 x 594 ) mm = ( 16.54 x 23.39 ) in
'A3' => array( 841.890,
1190.551), // = ( 297 x 420 ) mm = ( 11.69 x 16.54 ) in
'A4' => array( 595.276,
841.890), //= ( 210 x 297 ) mm = ( 8.27 x 11.69 ) in 
'A5' => array( 419.528, 595.276), //= ( 148 x 210 ) mm = ( 5.83 x 8.27 ) in 
'A6' => array( 297.638, 419.528), //= ( 105 x 148 ) mm = ( 4.13 x 5.83 ) in 
'A7' => array( 209.764,
297.638), //= ( 74 x 105 ) mm = ( 2.91 x 4.13 ) in 
'A8' => array( 147.402, 209.764), //= ( 52 x 74 ) mm = ( 2.05 x 2.91 ) in 
'A9' => array( 104.882, 147.402), //= ( 37 x 52 ) mm = ( 1.46 x 2.05 ) in 
'A10' => array( 73.701, 104.882), //= ( 26 x 37 ) mm = ( 1.02 x 1.46 ) in 
);
        if($layout_params['views']['pdf_orientation'] == 'L'){
            $total_width = $format_array[$layout_params['views']['pdf_format']][1];
        }else{
            $total_width = $format_array[$layout_params['views']['pdf_format']][0];
        }
//        var_dump($total_width); exit;
        $layout_html = urldecode($layout->getLayoutHtml(3));
        
        $layout_params['custom_fields'] = unserialize($layout->custom_fields);
//        require_once(JPATH_SITE . "/components/com_os_cck/tcpdf/tcpdf.php");
        if(!$pdf){
            $pdf = new myPDF($layout_params['views']['pdf_orientation'], 'px', $layout_params['views']['pdf_format'], true, 'UTF-8', false);
    //        $layout_form_params
            
            $pdf->layout_form_params = $layout_form_params;
            $pdf->total_width = $total_width;
            $pdf->layout = $layout;
            $pdf->layout_params = $layout_params;
            $pdf->eiid = $eiid;
            $pdf->pdf_footer_height = $layout_params['views']['pdf_footer_height'];

            if(isset($category)) $pdf->category = $category;
            $body = [];
            $header = [];
            $footer = [];

            foreach($pdf_structure as $row){
                if($row->pdf_type == 'header'){
                    $header[] = $row;
                }
                if($row->pdf_type == 'body'){
                    $body[] = $row;
                }
                if($row->pdf_type == 'footer'){
                    $footer[] = $row;
                }
            }
            $pdf->header_row = $header;
            $pdf->footer_row = $footer;
    //        var_dump($layout_form_params->get('marginTop'));
            echo '1111111111';
            
            
            
            $pdf->SetAutoPageBreak(true, $layout_params['views']['pdf_footer_height']);
            
//            var_dump($layout_params['views']); exit;
            if(isset($layout_params['views']['show_layout_title']) && $layout_params['views']['show_layout_title'] == '1'){
                $pdf->SetTitle($layout_params['views']['layout_title']);
            }
            
    //        $pdf->SetFont('freesans', 'B', 20);
            
            //$pdf->Write(0, $currentcat->header, '', 0, 'L', true, 0, false, false, 0);
            $pdf->SetFont('freesans', '', $layout_form_params->get('fontSize', 10));
    //        $pdf->setCellPaddings(5, 5, 5, 5);
    //        $pdf->setCellMargins(5, 5, 5, 5);
            $pdf->SetMargins($layout_form_params->get('marginLeft'), 0, $layout_form_params->get('marginRight'), true);
            if(empty($header)){
                $pdf->setTopMargin($layout_form_params->get('marginTop'));
            }
            $height_px = 0;
//            
//            $pdf->setHeaderMargin($layout_form_params->get('marginTop'));
//            var_dump($pdf);
            
            $pdf->AddPage();
            $start_row_y = $pdf->GetY();
//            var_dump($start_row_y); exit;
            $start_cell_y = $pdf->GetY();
            $start_page = $pdf->getPage();
        }else{
            $total_width = $width;
            if(isset($category)) $pdf->category = $category;
            $body = [];
            
            foreach($pdf_structure as $row){
                if($row->pdf_type == 'body'){
                    $body[] = $row;
                }
            
            }
            $start_row_y = $pdf->GetY();
            $start_cell_y = $pdf->GetY();
            $start_page = $pdf->getPage();
            
            $not_stop = true;
        }
        $pdf->instancies = $instancies;
        $child_entities = (isset($layout_params['child_entities'])) ? $layout_params['child_entities'] : '';
//        var_dump($body[1]);
        if($layout->type == 'pdf'){
            foreach ($instancies as $inst){
                self::displayCckPdfInstance($pdf, $inst, $instance_layout, $total_width, $body);
            }
        }else{
            $user = JFactory::getUser();
            $user_profile_form = new stdClass();

            if($entities_type[$layout->fk_eid] == 'joomla_user'){

                $user = JFactory::getUser($entityInstance->eiid);
//                $dispatcher = JDispatcher::getInstance();
              JPluginHelper::importPlugin('user');
              JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');
              $user_profile_form = JForm::getInstance('com_users.user', 'profile');
              $results2 = JFactory::getApplication()->triggerEvent('onContentPrepareData', array('com_users.user', $user));
              $results = JFactory::getApplication()->triggerEvent('onContentPrepareForm', array($user_profile_form, $user));
              $user_profile_form->bind($user);
            }
            
            foreach($body as $row){
                $coll_i = 1;

                $start_cell_x = $subcat_shift;
//                var_dump($start_cell_x);
                $start_row_page = $start_page;
                $start_cell_y = $start_row_y;


                foreach($row as $key => $collumn){
                    if(!is_object($collumn) || $key == 'row_styles'){continue;}

                    $page = $start_row_page;
                    
//                    $new_page = $pdf->getPage();
//                    if($new_page != $page){
//                        $pdf->setPage($page);
//                    }
                    $start_y = $start_cell_y;
                    $temp_y = 0;
                    $start_x = $start_cell_x;

                    $collumn_width = $collumn->width;
//                    var_dump($layout_params);
                    $px_width = (($total_width / 12) * $collumn_width) - 10 - (($layout_form_params->get('marginLeft') + $layout_form_params->get('marginRight')) / count(get_object_vars($row)));

                    $field_i = 1;
                    
                    foreach($collumn->placeholders as $field_cell){
                        if(stripos($field_cell, '{|f-') !== false){
//                            var_dump($entityInstance);
                            
                            if($layout->type != 'parent_child_pdf'){
                                $pdf->getFieldCell($field_cell, $field_i, $layout_params, '', $fields, $layout, $start_cell_y, $row, $px_width, $coll_i, $start_cell_x, '', $layout_html, $child_entities, '', $user_profile_form, $user);
                            }else{
                                $pdf->getFieldCell($field_cell, $field_i, $layout_params, $entityInstance, $fields, $layout, $start_cell_y, $row, $px_width, $coll_i, $start_cell_x, $eiid, $layout_html, $child_entities, '', $user_profile_form, $user);
                            }

                        }
                        if(stripos($field_cell, '{|l-') !== false){
                            $pos1 = stripos($field_cell, '-') + 1;
                            $pos2 = stripos($field_cell, '|}');
                            $lid = substr($field_cell, $pos1, $pos2 - $pos1);
                            if(isset($layout_params['views']['instance_grid_'.$lid]) && $layout_params['views']['instance_grid_'.$lid] == '1'){
                                $grid_collumn_width = $layout_params['views']['count_inst_columns_'.$lid];
                                $px_grid_width = $px_width / $grid_collumn_width;
                            }else{
                                $grid_collumn_width = 1;
                                $px_grid_width = $px_width;
                            }
                            if(!isset($layout_params['views']['show_request_layout'][$lid])) continue;
                              
                              if($layout->type == 'all_categories_pdf'){
                                  $categories = $category;
                                  
                                  if($pdf->cat_y != 0){
                                      $cat_y = $pdf->cat_y;
                                  }else{
                                    $cat_y = $pdf->getY();
                                  }
//                                  var_dump($categories);
                                  foreach($categories as $category){
                                      if($category->parent_id != '0') continue;
//                                      var_dump($cat_y);
//                                      var_dump($pdf->getY());
//                                      var_dump($pdf->cat_y);
//                                      var_dump($pdf->cat_page);
//                                      var_dump($pdf->getPage());
                                      if($cat_y > $pdf->getY() || $pdf->cat_page > $pdf->getPage()){
                                        $pdf->setY($cat_y);
                                      }
                                      if($pdf->cat_page > $pdf->getPage()){
                                          $pdf->setPage($pdf->cat_page);
                                      }
//                                      var_dump($pdf->getY());
//                                      var_dump($pdf->getPage());
//                                      var_dump($category->cid);
                                      $cat_params = Category::showCategory('com_os_cck', $category->cid, $lid,$layout_params, 0, true);
                                      
                                      
                                      $cat_y = self::displayCckPdf($category, $cat_params['instancies'], $cat_params['layout'], $cat_params['layout_params'], 0, $px_grid_width, $pdf);
                                      $cat_y = $pdf->cat_y;
                                      
//                                      echo '333333333333333';
                                  }
                              }
                              $instance_layout = new os_cckLayout($db->_db);
                              $instance_layout->load($lid);
                              $inst_i = 0;
                              $i = 1;
                              $inst_start_page = $page;
                              $temp_page = 0;
                              if($layout->type == 'all_categories_pdf'){
                              
                              
                              }
                              
                              
                              var_dump($pdf->instancies);
                              foreach ($instancies as $inst){
                                  $pdf->setPage($inst_start_page);
//                                    $pdf2 = clone $pdf;
//                                    self::displayCckPdfInstance($pdf2, $inst, $instance_layout, $px_width);
//                                    if($pdf2->getPage() > $pdf->getPage()){
//                                        var_dump($pdf2->getPage());
//                                        
//                                        $pdf->AddPage();
//                                        var_dump($pdf->getPage());
//                                        
//                                    }
                                
                                    self::displayCckPdfInstance($pdf, $inst, $instance_layout, $px_grid_width, '', $start_x, $start_y);
//                                    if(isset($layout_params['views']['instance_grid_'.$lid]) && $layout_params['views']['instance_grid_'.$lid] == '1'){
                                        $start_x = $start_x + $px_grid_width;
                                        
                                        if(($pdf->getY() > $temp_y && $pdf->getPage() == $temp_page) || $pdf->getPage() > $temp_page) $temp_y = $pdf->getY();
                                        if($pdf->getPage() > $temp_page)
                                            $temp_page = $pdf->getPage();
                                        $inst_i ++;
                                        $i ++;
//                                        $temp_inst_y = 
//                                        var_dump($pdf->getY());
//                                        var_dump($temp_page);
//                                        var_dump($grid_collumn_width);
                                        if($inst_i == $grid_collumn_width){
                                            
                                            $start_y = $temp_y;
                                            if($i == count($instancies)){
                                                $pdf->cat_y =  $temp_y;
                                            }
                                            $temp_y = 0;
                                            $inst_i = 0;
                                            $start_x = $start_cell_x;
                                            $inst_start_page = $temp_page;
                                            $page = $temp_page;
                                        }else{
//                                            $start_y = $temp_y;
                                            if(($pdf->getY() > $temp_y && $pdf->getPage() == $temp_page) || $pdf->getPage() > $temp_page) $temp_y = $pdf->getY();
//                                            var_dump($pdf->getY());
//                                            var_dump($temp_y);
//                                            var_dump($pdf->getPage());
//                                            var_dump($temp_page);

                                            $pdf->cat_y =  $temp_y;

//                                            var_dump($pdf->cat_y);
//                                            $inst_start_page = $temp_page;
//                                            $page = $temp_page;
                                            if($pdf->getPage() > $pdf->cat_page){
                                                $pdf->cat_page = $pdf->getPage();
                                            }
                                        }
                                        if($i == count($instancies)){
                                           $pdf->cat_y =  $start_y;
                                        }
//                                    }
//                                    var_dump($pdf->getPageHeight());
//                                    var_dump($pdf->getScaleFactor());
                                }
                                
                        }
//                        if(stripos($field_cell, '{|f-') !== false || stripos($field_cell, '{|e-p-ch-') !== false || stripos($field_cell, "{|f-custom_code_field_") !== false){
//
//                            $pdf->getFieldCell($field_cell, $field_i, $layout_params, $entityInstance, $fields, $layout, $start_cell_y, $row, $px_width, $coll_i, $start_cell_x, $eiid, $layout_html, $child_entities);
//
//                        }

                        if(count(get_object_vars($collumn->placeholders)) == $field_i){
                            if($pdf->GetY() > $start_row_y){
                                if($pdf->getPage() == $start_page){
                                    $start_row_y = $pdf->GetY();
                                }
                            }

                            if($pdf->getPage() > $start_page){
                                $start_page = $pdf->getPage();
                                $start_row_y = $pdf->GetY();
                            }

                        }
                        $field_i++;
                    }
                    $start_cell_x = $start_cell_x + $px_width + 10;

                    $coll_i++;
                }



            }
//            var_dump($layout->type);
            if($layout->type == 'category_pdf'){
//                var_dump($layout_params['views']['subcategories_layout']); exit;
                if($layout_params['views']['sub_category_level'] == 1 && $layout_params['views']['subcategories_layout']){
//                    $is_exist_sub_categories = self::is_exist_curr_and_subcategory_items($category->cid, $layout->fk_eid);
//                    var_dump($category->cid);
//                    var_dump($layout->fk_eid);
//                    var_dump($not_stop);
                    $query = "SELECT * FROM #__os_cck_categories WHERE parent_id = $category->cid";
//                    print_r($query);
                    $db->setQuery($query);
                    $subcategories = $db->loadObjectList();

                    if(!empty($subcategories)){
                        $cat_y = $pdf->cat_y;
                        $subcat_shift += 20;
                        foreach($subcategories as $subcategory){
                            
                            $cat_params = Category::showCategory('com_os_cck', $subcategory->cid, $layout_params['views']['subcategories_layout'],$layout_params, 0, true);
                            
                            $cat_y = self::displayCckPdf($subcategory, $cat_params['instancies'], $cat_params['layout'], $cat_params['layout_params'], 0, $width, $pdf, $subcat_shift);
//                            $pdf->cat_y = $pdf->getY();
                            
                            if($cat_y > $pdf->getY()){
                               $pdf->setY($cat_y);
                            }
                            if($pdf->getPage() > $pdf->cat_page){
                                $pdf->cat_page = $pdf->getPage();
                            }
                            
                        }
                    }

                }
                
            }
        }
        
        if(!$not_stop){
            
        $pdf->lastPage();
        if(!$input->get('debug', false)){
            ob_end_clean();
        }
//        ob_end_clean();
        $pdf->Output('CCK.pdf', 'I');
        exit;
        }
        
  }
  
  static function displayCckPdfInstance($pdf, $entityInstance, $layout, $width, $body = '', $start_cell_x = 0, $start_row_y = false){
      global $doc, $db, $entityFieldLists, $input, $os_cck_configuration, $entities_type;
      $db = new os_cckDb();
        if(!$start_row_y) $start_row_y = $pdf->getY();
        $user = JFactory::getUser();
        $user_profile_form = new stdClass();
        var_dump($entityInstance->eiid);
        if($entities_type[$layout->fk_eid] == 'joomla_user'){
                
            $user = JFactory::getUser($entityInstance->eiid);
//            $dispatcher = JDispatcher::getInstance();
          JPluginHelper::importPlugin('user');
          JForm::addFormPath(JPATH_SITE . '/plugins/user/profile');
          $user_profile_form = JForm::getInstance('com_users.user', 'profile');
          $results2 = JFactory::getApplication()->triggerEvent('onContentPrepareData', array('com_users.user', $user));
          $results = JFactory::getApplication()->triggerEvent('onContentPrepareForm', array($user_profile_form, $user));
          $user_profile_form->bind($user);
        }
        $layout_params = unserialize($layout->params);
        $layout_params['custom_fields'] = unserialize($layout->custom_fields);
        $layout_form_params = new JRegistry;
        $layout_form_params = $layout_form_params->loadString($layout_params['form_params']);
        
//        $margin_top = $layout_form_params->get('marginTop', '0');
//        $start_row_y = $margin_top
//        var_dump($margin_top); exit;
        $layout_html = urldecode($layout->getLayoutHtml(3));
        $fields = $entityFieldLists[$layout->fk_eid];
        if($entities_type[$layout->fk_eid] == 'joomla_user' || $entities_type[$layout->fk_eid] == 'custom_sql'){
            $fields = cckConvertFieldList($fields);
        }
//        var_dump($fields);
        if($layout->type != 'pdf'){
            return;
        }
//        var_dump($layout->type);
        $height_px = 0;
        
//        $start_row_y = $pdf->GetY();
        $start_cell_y = $pdf->GetY();
        $start_page = $pdf->getPage();
        $child_entities = (isset($layout_params['child_entities'])) ? $layout_params['child_entities'] : '';
        
        $assoc_child_enteties = array();
        foreach($child_entities as $ch_e){
            $assoc_child_enteties[$ch_e->data_field_name] = $ch_e;
        }
        
        $form_fontSize = $layout_form_params->get('fontSize');
        $form_fontWeight = $layout_form_params->get('fontWeight');
        $form_fontColor = $layout_form_params->get('fontColor');
        
        $start_cell_x += $layout_form_params->get('marginLeft', 0);
        $temp_cell_x = $start_cell_x;
//        var_dump($start_cell_x);
        $pdf_structure = json_decode($layout->pdf_structure);
        if($body == ''){
            $body = [];
            
            foreach($pdf_structure as $row){
                
                if($row->pdf_type == 'body'){
                    $body[] = $row;
                }
            }
        }
//        var_dump(count($body)); //exit;
        $cont = 1;
//        var_dump($start_cell_x);
        foreach($body as $row){
//        if($cont == count($body)){            //var_dump($row); }//exit;}
//            var_dump($row); exit;
            $row_content = false;
            foreach($row as $collumn){
                if(is_object($collumn) && property_exists($collumn, 'placeholders')){
                    $column_content = (array) $collumn->placeholders;
                    if(!empty($column_content)){
                        $row_content = true;
                    }
                }
            }
            
            if(!$row_content){
//                var_dump($row_content); exit;
                continue;
            } 

            $coll_i = 1;
            
//            $start_cell_x = 20;
            $start_row_page = $start_page;
            $start_cell_y = $start_row_y;
            $temp_cell_y = 0;
            $temp_page = 0;
            $start_cell_x = $temp_cell_x;
            if(property_exists($row, 'row_styles') && property_exists($row->row_styles, 'marginTop')){
//                var_dump($row->row_styles);
                $row_styles['top_margin'] = $row->row_styles->marginTop;
                $row_styles['right_margin'] = $row->row_styles->marginRight;
                $row_styles['bottom_margin'] = $row->row_styles->marginBottom;
                $row_styles['left_margin'] = $row->row_styles->marginLeft;
                
                $row_styles['top_padding'] = $row->row_styles->paddingTop;
                $row_styles['right_padding'] = $row->row_styles->paddingRight;
                $row_styles['bottom_padding'] = $row->row_styles->paddingBottom;
                $row_styles['left_padding'] = $row->row_styles->paddingLeft;
                
                $row_styles['backgroundColor'] = $row->row_styles->backgroundColor;
                $row_styles['borderSize'] = $row->row_styles->borderSize;
                $row_styles['borderColor'] = $row->row_styles->borderColor;
                $row_styles['fontSize'] = $row->row_styles->fontSize;
                $row_styles['fontWeight'] = $row->row_styles->fontWeight;
                $row_styles['fontColor'] = $row->row_styles->fontColor;
            }else{
                $row_styles['top_margin'] = false;
                $row_styles['right_margin'] = false;
                $row_styles['bottom_margin'] = false;
                $row_styles['left_margin'] = false;
                
                $row_styles['top_padding'] = false;
                $row_styles['right_padding'] = false;
                $row_styles['bottom_padding'] = false;
                $row_styles['left_padding'] = false;
                
                $row_styles['backgroundColor'] = false;
                $row_styles['borderSize'] = false;
                $row_styles['borderColor'] = false;
                $row_styles['fontSize'] = false;
                $row_styles['fontWeight'] = false;
                $row_styles['fontColor'] = false;
            }
            
             if($row_styles['fontSize'] == false && $row_styles['fontSize'] == ''){
                $row_styles['fontSize'] = $form_fontSize;
            }
            if($row_styles['fontWeight'] == false && $row_styles['fontWeight'] == ''){
                $row_styles['fontWeight'] = $form_fontWeight;
            }
            if($row_styles['fontColor'] == false && $row_styles['fontColor'] == ''){
                $row_styles['fontColor'] = $form_fontColor;
            }
            if($row_styles['top_margin']){
                $start_cell_y = $start_cell_y + $row_styles['top_margin'];
            }
            if($row_styles['left_margin']){
                $start_cell_x = $start_cell_x + $row_styles['left_margin'];
            }
//            var_dump($start_cell_y);
            $start_rect_x = $start_cell_x;
            $start_rect_y = $start_cell_y;
            
            
            $row_margin = 0;
            if($row_styles['right_margin']){
                $row_margin += $row_styles['right_margin'];
            }
            if($row_styles['left_margin']){
                $row_margin += $row_styles['left_margin'];
            }
            
            $row_padding = 0;
            if($row_styles['right_padding']){
                $row_padding += $row_styles['right_padding'];
            }
            if($row_styles['left_padding']){
                $row_padding += $row_styles['left_padding'];
                $start_cell_x = $start_cell_x + $row_styles['left_padding'];
            }
            if($row_styles['top_padding']){
                $start_cell_y = $start_cell_y + $row_styles['top_padding'];
            }
            if($row_styles['borderSize']){
                
                $start_cell_y = $start_cell_y + $row_styles['borderSize'];
                $start_cell_x = $start_cell_x + $row_styles['borderSize'];
                
                
                $row_border_margin = $row_styles['borderSize'] * 2;
            }
            $row_width = 0;
//            var_dump($start_cell_x);
            $temp_start_cell_y = $start_cell_y;
//            $pdf->SetLineStyle( array( 'width' => 15, 'color' => array(0,0,0)));
            foreach($row as $key => $collumn){
//                var_dump($collumn);
                $start_cell_y = $temp_start_cell_y;
                if(!is_object($collumn) || $key == 'row_styles'){continue;}
//                var_dump($collumn->col_params);
                if(property_exists($collumn, 'col_params')){
                    $col_params = json_decode($collumn->col_params);
//                    var_dump($col_params);
                    $col_styles['top_margin'] = property_exists($col_params, 'marginTop') ? $col_params->marginTop : false;
                    $col_styles['right_margin'] = property_exists($col_params, 'marginRight') ? $col_params->marginRight : false;
                    $col_styles['bottom_margin'] = property_exists($col_params, 'marginBottom') ? $col_params->marginBottom : false;
                    $col_styles['left_margin'] = property_exists($col_params, 'marginLeft') ? $col_params->marginLeft : false;

                    $col_styles['top_padding'] = property_exists($col_params, 'paddingTop') ? $col_params->paddingTop : false;
                    $col_styles['right_padding'] = property_exists($col_params, 'paddingRight') ? $col_params->paddingRight : false;
                    $col_styles['bottom_padding'] = property_exists($col_params, 'paddingBottom') ? $col_params->paddingBottom : false;
                    $col_styles['left_padding'] = property_exists($col_params, 'paddingLeft') ? $col_params->paddingLeft : false;

                    $col_styles['backgroundColor'] = property_exists($col_params, 'backgroundColor') ? $col_params->backgroundColor : false;
                    $col_styles['borderSize'] = property_exists($col_params, 'borderSize') ? $col_params->borderSize : false;
                    $col_styles['borderColor'] = property_exists($col_params, 'borderColor') ? $col_params->borderColor : false;
                    $col_styles['fontSize'] = property_exists($col_params, 'fontSize') ? $col_params->fontSize : false;
                    $col_styles['fontWeight'] = property_exists($col_params, 'fontWeight') ? $col_params->fontWeight : false;
                    $col_styles['fontColor'] = property_exists($col_params, 'fontColor') ? $col_params->fontColor : false;
                }else{
                    $col_styles['top_margin'] = false;
                    $col_styles['right_margin'] = false;
                    $col_styles['bottom_margin'] = false;
                    $col_styles['left_margin'] = false;

                    $col_styles['top_padding'] = false;
                    $col_styles['right_padding'] = false;
                    $col_styles['bottom_padding'] = false;
                    $col_styles['left_padding'] = false;

                    $col_styles['backgroundColor'] = false;
                    $col_styles['borderSize'] = false;
                    $col_styles['borderColor'] = false;
                    $col_styles['fontSize'] = false;
                    $col_styles['fontWeight'] = false;
                    $col_styles['fontColor'] = false;
                }
                if($col_styles['fontSize'] == false && $col_styles['fontSize'] == ''){
                    $col_styles['fontSize'] = $row_styles['fontSize'];
                }
                if($col_styles['fontWeight'] == false && $col_styles['fontWeight'] == ''){
                    $col_styles['fontWeight'] = $row_styles['fontWeight'];
                }
                if($col_styles['fontColor'] == false && $col_styles['fontColor'] == ''){
//                    var_dump($row_styles['fontColor']);
                    $col_styles['fontColor'] = $row_styles['fontColor'];
                }
                if($col_styles['backgroundColor'] == false && $col_styles['backgroundColor'] == ''){
                    $col_styles['backgroundColor'] = $row_styles['backgroundColor'];
                }
                if($col_styles['top_margin']){
                    $start_cell_y = $start_cell_y + $col_styles['top_margin'];
                }
//                var_dump($col_styles['top_margin']);
                if($col_styles['left_margin']){
                    $start_cell_x = $start_cell_x + $col_styles['left_margin'];
                }
                $start_coll_rect_x = $start_cell_x;
                $start_coll_rect_y = $start_cell_y; 
                
                $page = $start_row_page;
                $new_page = $pdf->getPage();
//                var_dump($page);
//                var_dump($new_page);
                if($new_page != $page){
                    $pdf->setPage($page);
                }
                $start_y = $start_cell_y;
                $col_margin = 0;
                if($col_styles['right_margin']){
                    $col_margin += $col_styles['right_margin'];
                }
                if($col_styles['left_margin']){
                    $col_margin += $col_styles['left_margin'];
                }

                $col_padding = 0;
                if($col_styles['right_padding']){
                    $col_padding += $col_styles['right_padding'];
                }
                if($col_styles['left_padding']){
                    $col_padding += $col_styles['left_padding'];
                }
                if($col_styles['top_padding']){
                    $start_cell_y = $start_cell_y + $col_styles['top_padding'];
                }
                if($col_styles['borderSize']){
                
                    $start_cell_y = $start_cell_y + $col_styles['borderSize'];
                    $start_cell_x = $start_cell_x + $col_styles['borderSize'];


                    $col_border_margin = $col_styles['borderSize'] * 2;
                }else{
                    $col_border_margin = 0;
                }
                $col_width = 0;
                
                $collumn_width = $collumn->width;
                $px_width = (($width / 12) * $collumn_width) - (($layout_form_params->get('marginLeft') + $layout_form_params->get('marginRight')  + $row_margin) / (count(get_object_vars($row)) -2));
//                if($px_width > $row_width){
                    
//                }
                $row_width += $px_width;
//                var_dump($px_width);
                $px_width = $px_width - ($row_padding / (count(get_object_vars($row))-2)) - $row_border_margin;
                
                
//                var_dump($col_margin);
                $px_width = $px_width - $col_margin;
//                var_dump($px_width);
                if($px_width > $col_width){
                    $col_width = $px_width;
                }
//                var_dump($col_width); exit;
                $px_width = $px_width - $col_padding - $col_border_margin;
                
                $field_i = 1;
//                $column_content = (array) $collumn->placeholders;
//                if(empty($column_content)) continue;
                foreach($collumn->placeholders as $field_cell){
//                    var_dump($field_cell);
                    $symbols_array = array('{|', '|}');
                    $field_cell_wo_symbols = str_replace($symbols_array, '', $field_cell);
//                    var_dump($field_cell);
//                    var_dump($field_cell_wo_symbols);
//                    var_dump($field_i);
//                    var_dump($start_cell_x);
//                    var_dump($pdf);
                    if(stripos($field_cell, '{|f-') !== false || stripos($field_cell, '{|e-p-ch-') !== false || stripos($field_cell, "{|f-custom_code_field_") !== false || isset($assoc_child_enteties[$field_cell_wo_symbols])){
                        
                        $pdf->getFieldCell($field_cell, $field_i, $layout_params, $entityInstance, $fields, $layout, $start_cell_y, $row, $px_width, $coll_i, $start_cell_x, $entityInstance->eiid, $layout_html, $child_entities, '', $user_profile_form, $user, $col_styles['fontSize'], $col_styles['fontWeight'], $col_styles['fontColor'], $col_styles['backgroundColor']);
                        
                    }
                    
                    if(count(get_object_vars($collumn->placeholders)) == $field_i){
//                        echo '444444444444';
//                        var_dump($pdf->getPage());
//                        var_dump($temp_page);
                        if($pdf->GetY() > $start_row_y){
                            if($pdf->getPage() == $start_page && ($temp_page == $pdf->getPage() || $temp_page == 0)){
                                $start_row_y = $pdf->GetY();
                            }
                        }
                        
                        if($temp_page < $pdf->getPage()){
                            $temp_page = $pdf->getPage();
                        }
                        
                        if($pdf->getPage() > $start_page){
                            $start_page = $pdf->getPage();
                            $start_row_y = $pdf->GetY();
                        }
                        

                    }else{
//                        echo '55555555555';
//                        var_dump($pdf->getPage());
//                        var_dump($start_page);
//                        var_dump($temp_page);
                        
//                        var_dump($pdf->getPageHeight());
                        if($pdf->GetY() > $start_row_y){
                            if($pdf->getPage() == $start_page && $temp_page == $pdf->getPage()){
                                $start_row_y = $pdf->GetY();
                            }
                        }
//                        var_dump($start_row_y);
                        if($temp_page < $pdf->getPage()){
                            $temp_page = $pdf->getPage();
                        }
                    }
//                    var_dump($pdf->GetY());
//                    var_dump($start_row_y);
//                    echo '<br>';
                    $field_i++;
                }
                $start_cell_x = $start_cell_x + $px_width;
                if($col_styles['bottom_padding']){
                    $stop_coll_rect_y = $pdf->GetY() + $col_styles['bottom_padding'];
                }else{
                    $stop_coll_rect_y = $pdf->GetY();
                }
//                var_dump($stop_coll_rect_y);
//                var_dump($col_styles['borderSize']); exit;
                if($col_styles['borderSize'] != ''){
                    $stop_coll_rect_y += $col_styles['borderSize'];
                }
                $array = ['rgba(',  ')', ' '];
                $borderColor = str_ireplace($array, '', $col_styles['borderColor']);
                $borderColor = explode(',', $borderColor);

                unset($borderColor[3]);

                $style4 = array('all' => array('width' => ($col_styles['borderSize'] != '') ? $col_styles['borderSize'] : 0, 'color' => $borderColor));
//                var_dump($style4);
//                var_dump($stop_coll_rect_y-$start_coll_rect_y); exit;
                if($col_styles['borderSize']){
                    $pdf->Rect($start_coll_rect_x, $start_coll_rect_y, $col_width, $stop_coll_rect_y-$start_coll_rect_y, 'S', $style4);
                }
                if($row_styles['borderSize']){
                    $pdf->SetY($pdf->GetY() + $row_styles['borderSize']);
                }
                if($col_styles['bottom_margin'] && ($col_styles['bottom_margin'] + $pdf->GetY()) > $start_row_y){
                    $start_row_y = $pdf->GetY() + $col_styles['bottom_margin'];
                }
                $coll_i++;
            }
            
            if($row_styles['bottom_padding']){
                $stop_rect_y = $start_row_y + $row_styles['bottom_padding'];
            }else{
                $stop_rect_y = $start_row_y;
            }
            if($row_styles['borderSize']){
                $stop_rect_y += $row_styles['borderSize'];
            }
//              var_dump($row_styles);
            $array = ['rgba(',  ')', ' '];
            $borderColor = str_ireplace($array, '', $row_styles['borderColor']);
            $borderColor = explode(',', $borderColor);
            
            unset($borderColor[3]);
//            var_dump($start_rect_x);
//            var_dump($start_rect_y); exit;
            $style4 = array('all' => array('width' => ($row_styles['borderSize']) ? $row_styles['borderSize'] : 0, 'color' => $borderColor));
            if($row_styles['borderSize']){
                $pdf->Rect($start_rect_x, $start_rect_y, $row_width, $stop_rect_y-$start_rect_y, 'S', $style4);
            }
            if($row_styles['borderSize']){
                $start_row_y += $row_styles['borderSize'];
            }
            if($row_styles['bottom_margin']){
                $start_row_y = $start_row_y + $row_styles['bottom_margin'];
                $pdf->SetY($start_row_y);
            }
            
            $cont++;
        }
        
//        var_dump($start_row_y);
        $pdf->SetY($start_row_y);
        $pdf->setPage($temp_page);
  }
  
  
  static function changeQuantityCart(){
      global $db, $session;
      $db = new os_cckDb();
      $input = JFactory::getApplication()->input;
      $index = $input->get('index', 0, 'INT');
      
      $eiid = $input->get('eiid', 0, 'INT');
      
      $coupon = $input->get('coupon', -1, 'INT');
      
      $cart = $session->get('cart', '');
      
      $jsonPriceFields = $input->get('jsonPriceFields', '', 'STRING');
      
//      $cart[$eiid]['price_fields'] = $jsonPriceFields;
//      var_dump($cart);
      foreach($cart as $key => $cart_item){
          if($cart_item['eiid'] == $eiid){
              $cart[$key]['price_fields'] = $jsonPriceFields;
          }
       }
      $cart_count = 0;
        foreach($cart as $cart_item){
            if($cart_item['eiid'] == $eiid){
            }
            $price_fields = json_decode($cart_item['price_fields']);
            $cart_count += $price_fields[0]->quantity;

        }
      $session->set('cart', $cart);
//      var_dump($cart);
//      var_dump($_REQUEST);
//      exit;
  	  
      echo json_encode(array("success"=>true, "cart_count"=>$cart_count));
      return;
  }
  
  static function payment_notice() {
      global $db, $os_cck_configuration, $app;
        $db = new os_cckDb();
        define("DEBUG", false);
        define("LOG_FILE", "./authorize.log");
    //    $payload = @file_get_contents('php://input');
    //var_dump(json_decode($payload));

        $operation=protectInjectionWithoutQuote('operation');
        $input = JFactory::getApplication()->input;
        
        $plugin_name = protectInjectionWithoutQuote('plugin');
        
        if($operation == 'checkout'){
            $plugin = JPluginHelper::importPlugin( 'payment',$plugin_name);

            if ( version_compare(JVERSION, "4.0.0-alpha10", "ge") ) { 
                JFactory::getApplication()->triggerEvent('onCheckout'.ucfirst($plugin_name));
            } else {

             $dispatcher = JDispatcher::getInstance();
             $results = $dispatcher->trigger('onCheckout'.ucfirst($plugin_name));
            }
        }elseif($operation == 'success'){
            $plugin = JPluginHelper::importPlugin( 'payment',$plugin_name);

            if ( version_compare(JVERSION, "4.0.0-alpha10", "ge") ) { 
                JFactory::getApplication()->triggerEvent('onSuccess'.ucfirst($plugin_name));
            } else {

             $dispatcher = JDispatcher::getInstance();
             $results = $dispatcher->trigger('onSuccess'.ucfirst($plugin_name));
            }
            http_response_code(200);
        }else{
            $inputData = file_get_contents('php://input');
            file_put_contents("input_payment_logs.txt", date("Y-m-d H:i:s") . " - " . $inputData . "\n", FILE_APPEND);
        }
  }

  //this function use in admin for manage: requests, buy_requests, rent_requests,show_in_reviews, rent_history,orders
  //here we create data for second row 
  //$manager_name: 'show_in_requests','show_in_buy_requests','show_in_rent_requests','show_in_reviews','show_in_rent','show_in_orders'
  //$request_ids - this part only for orders or rent_history, when we have not only parents but also and request connected to order  
  static function second_row_prepere( $table,$rows_item,$manager_name,$request_ids=array()) {
      global $entityFieldLists;
        $db = new os_cckDb();

        //prepere fields for second row: Data
        $data_second_row = array();
        $second_row_fields_title = array();
        $kkk = 0;
        if(!isset( $rows_item->fid_parent ) || empty( $rows_item->fid_parent ) ) {

          if(isset($rows_item->lay_title) ) {
              //if we have't parent, so for second row show only layout name
              $second_row_fields_title[][] = 'Layout Title' ;
              $data_second_row[][] = $rows_item->lay_title;;
          }
        } else {

          $parent_ids = explode(",",$rows_item->fid_parent );
 
          foreach($parent_ids as $parent_id){
            //if for 1 request many parents - we show in one row namy data for every parent,
            //one new row with data for 1 parent
            $second_row_fields_title_one = array() ;
            $data_second_row_one = array() ;

            $show_parent_fields = array();

            $parentInstance = new os_cckEntityInstance($db->_db);
            $parentInstance->load($parent_id);
            
            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);
                //where show fields: $manager_name: 
                //'show_in_requests','show_in_buy_requests','show_in_rent_requests','show_in_reviews','show_in_rent','show_in_orders'
                if($params->get($manager_name, '') == 'yes'){
                    $show_parent_fields[] = $field;
                }
            }

            $second_row_fields_title_one[] = 'Parent Title' ;
            $data_second_row_one[] = $parentInstance->title;

            foreach ($show_parent_fields as $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' || $value[0]->data == '1970-01-01 00:00:00' ) ){
                    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, 'pricefield_number') !== false){
                  if( empty($value[0]->price_value) ) continue ;
                  $print_value = $value[0]->price_value ;
                }
                elseif($field->field_type == 'categoryfield' ){
                  if( empty($value[0]->title) ) continue ;
                  $print_value = $value[0]->title;
                }elseif(isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data')){
                  $print_value = $value[0]->data;
                }

                if(isset($print_value) && strlen($print_value) > 40)
                {
                    $print_tooltip = htmlspecialchars(strip_tags( $print_value ));
                    $print_value = strip_tags(substr( $print_value , 0, 40) . ' ..');
                    $print_value = '<span rel="tooltip" data-toggle="tooltip" data-placement="top" title="'.$print_tooltip.'">'
                        . $print_value.'</span>';
                }

                //if for 1 request many parent inctances(for request) or products and connected requests(for order) or .. 
                //- we show in one row namy data for every parent
                //in 1 array data from 1 parent(instance, request.. )
                $second_row_fields_title_one[] = $field->field_name ;
                $data_second_row_one[] = $print_value ;
            }


            //if for 1 request many parent inctances(for request) or products and connected requests(for order) or .. 
            //- we show in one row namy data for every parent
            //$kkk - new parent
            $second_row_fields_title[$kkk] = $second_row_fields_title_one ;
            $data_second_row[$kkk] = $data_second_row_one ;
            
            $kkk++;
          }//foreach($parent_ids 
      }

          //use $kkk - from "for loop" befor
          //this part only for orders, when we have not only parents but also and request connected to order  
          foreach($request_ids as $request_id){

            //if for 1 request many parents - we show in one row namy data for every parent,
            //one new row with data for 1 parent
            $second_row_fields_title_one = array() ;
            $data_second_row_one = array() ;

            $show_request_fields = array();

            $requestInstance = new os_cckEntityInstance($db->_db);
            $requestInstance->load($request_id);
            
            if(isset($entityFieldLists[$requestInstance->fk_eid])){
              $fields = $entityFieldLists[$requestInstance->fk_eid];
            }else{
              $fields = array();
            }
            foreach($fields as $field){
                $params = new JRegistry;
                $params->loadString($field->params);
                if( ($manager_name == 'show_in_orders' && $params->get('show_in_orders', '') == 'yes' )
                    ||  ( $manager_name == 'show_in_rent' && $params->get('show_in_rent', '') == 'yes' )  
                ){
                    $show_request_fields[] = $field;
                }
            }

            if($rows_item->instance_type == "Rent"){
                $second_row_fields_title_one[] = "Rent request ID";
            }else{
                $second_row_fields_title_one[] = "Buy request ID";
            }
            $data_second_row_one[] = $request_id;

            foreach ($show_request_fields as $field){

                $value = $requestInstance->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' || $value[0]->data == '1970-01-01 00:00:00' ) ){
                    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, 'pricefield_number') !== false){
                  if( empty($value[0]->price_value) ) continue ;
                  $print_value = $value[0]->price_value ;
                }
                elseif($field->field_type == 'categoryfield' ){
                  if( empty($value[0]->title) ) continue ;
                  $print_value = $value[0]->title;
                }elseif(isset($value[0]) && is_object($value[0]) && property_exists($value[0], 'data')){
                  $print_value = $value[0]->data;
                }

                if(isset($print_value) && strlen($print_value) > 40)
                {
                    $print_tooltip = htmlspecialchars(strip_tags( $print_value ));
                    $print_value = strip_tags(substr( $print_value , 0, 40) . ' ..');
                    $print_value = '<span rel="tooltip" data-toggle="tooltip" data-placement="top" title="'.$print_tooltip.'">'
                        . $print_value.'</span>';
                }

                //if for 1 request many parent inctances(for request) or products and connected requests(for order) or .. 
                //- we show in one row namy data for every parent
                //in 1 array data from 1 parent(instance, request.. )
                $second_row_fields_title_one[] = $field->field_name ;
                $data_second_row_one[] = $print_value ;
            }


            //if for 1 request many parent inctances(for request) or products and connected requests(for order) or .. 
            //- we show in one row namy data for every parent
            //$kkk - new request
            $second_row_fields_title[$kkk] = $second_row_fields_title_one ;
            $data_second_row[$kkk] = $data_second_row_one ;
            
            $kkk++;
          }//foreach($request_ids           


        //here create data and title for all  Parents connected to row with request
        //if for 1 request many parents - we show in one row namy data for every parent
        $table->create_second_row_collumn( $second_row_fields_title, "font-weight: 500;" );
        $table->create_second_row_data( array($data_second_row) );

  }


  //this function use in admin for manage: requests, buy_requests, rent_requests,show_in_reviews, rent_history,orders
  //here we create columns Titles for first row, for additional fields from $show_fields  
  static function create_first_row_collumns_titles( $table,$show_fields,$sort_arr ) {
    global $entityFieldLists;
    $db = new os_cckDb();

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

  //this function use in admin for manage: requests, buy_requests, rent_requests,show_in_reviews, rent_history,orders
  //here we create columns Date (from $rows_item) for first row, for additional fields (from $show_fields)  
  static function create_first_row_collumns_data( $table,$rows_item, $show_fields ) {
    $db = new os_cckDb();
  
    $return_data = array();
    foreach($show_fields as $key => $value){
      foreach($value as $field){
        $html = '';
        if($rows_item->fk_eid != $key){
          $return_data[] = '<div class="admin-order-standart-fields-email"></div>';
          continue;
        }
        if($field->field_type == 'categoryfield'){
          $return_data[] = $rows_item->category;
          continue;
        }

        $entityInstance = new os_cckEntityInstance($db->_db);
        $entityInstance->load($rows_item->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) . ' ..');
        }


        // $img_style = ($field->field_type=='imagefield'  && isset($field->options['width']) && isset($field->options['height'])) ? ('width:'.$field->options['width'].'px; height:'.$field->options['height'].'px;'):('');
        $img_style = ($field->field_type=='imagefield') ? ('width:50px; height:50px;'):('');

        $html .= '<div><span class="col_box" style="display:block;'.$img_style.'">';

        ob_start();
        require getSiteShowFiledViewPath('com_os_cck', $field->field_type);
        $html .= ob_get_contents();
        ob_end_clean();
        $html .= '</span></div>';
        $return_data[] = $html;
                 
      }
    }

    return $return_data;

  }

      
  
}

