<?php
defined('_JEXEC') or die('Restricted access');
/**
* @package OS CCK
* @copyright 2019 OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com), Vladislav Prikhodko (vlados.vp1@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/
//var_dump($layout->lid);
if(isset($layout_params['custom_fields']) && count($layout_params['custom_fields'])){
    
  foreach ($layout_params['custom_fields'] as $cust_key => $custom_field) {
      
    if(strpos($layout_html,"{|f-custom_code_field_".$cust_key."|}")){
        
//        var_dump($layout_params['custom_fields']);
        
      //check access
      if(isset($custom_field['custom_code_field_'.$cust_key.'_access'])
          && $custom_field['custom_code_field_'.$cust_key.'_access'] != '1'){
        $user = JFactory::getUser();
        if(!checkAccess_cck($custom_field['custom_code_field_'.$cust_key.'_access'], $user->groups, $layout->fk_eid, 'fields')){
          $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", '', $layout_html);
          continue;
        }
      }
      // $dispatcher = JDispatcher::getInstance();
      JPluginHelper::importPlugin('content');
      $plug_row = new stdClass();
      $plug_row->text = $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
      preg_match_all('#\{loadmoduleid [0-9]*\}#', $plug_row->text, $matches);
      foreach($matches as $res){
        foreach($res as $str){
          
          $moduleId = str_replace('{loadmoduleid ', '', $str);
          $moduleId = str_replace('}', '', $moduleId);

          $mod_row =  JTable::getInstance ( 'Module', 'JTable' );//load module tables and params

          if (! $mod_row->load ( $moduleId )) {

            throw new Exception($mod_row->getError (), 500);
          }

          $module = JModuleHelper::getModule($mod_row->module,$mod_row->title);
          $options  = array('style' => 'xhtml');
          $mod_html = JModuleHelper::renderModule($module,$options);

          $plug_row->text = str_replace($str, $mod_html, $plug_row->text);

        }
      }
      // $dispatcher->trigger('onContentPrepare', array('com_os_cck', &$plug_row, &$plug_params, 0));
      // $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = $plug_row->text;
      //if below fn works , that this is add_instance view
      $code_type = $custom_field['custom_code_field_'.$cust_key.'_custom_code_type'];
      $plug_row->text = str_replace("{|this_entity_filesfolder|}", JURI::root() . '/components/com_os_cck/files/entity_files_'.$layout->fk_eid.'/', $plug_row->text);
      $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_replace("{|this_entity_filesfolder|}", JURI::root() . '/components/com_os_cck/files/entity_files_'.$layout->fk_eid.'/', $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
      // var_dump(JURI::root() . 'images/os-cck/');
      $plug_row->text = str_ireplace("{|cck_images_folder|}", JURI::root() . 'images/os-cck/', $plug_row->text);
      $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_ireplace("{|cck_images_folder|}", JURI::root() . 'images/os-cck/', $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
      
      $plug_row->text = $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_ireplace('{|this_site|}', JURI::root(), $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
      preg_match_all('#{|layout_id-[0-9]*|}#', $custom_field['custom_code_field_'.$cust_key.'_custom_code'], $matches);
      if(!empty($matches)){
          foreach ($matches as $res){
              foreach($res as $str){
                  if(stripos($str, 'layout_id') !== false){
                      $str_arr = explode('-', $str);
                      
                      $plug_row->text = $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_replace('{|layout_id-'.$str_arr[1].'|}', 'lid='.$str_arr[1], $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
//                      var_dump($custom_field['custom_code_field_'.$cust_key.'_custom_code']);
                  }
//                var_dump(stripos($str, 'layout_id'));
              }
          }
      }
      
      preg_match_all('#{|instance_id-[0-9]*|}#', $custom_field['custom_code_field_'.$cust_key.'_custom_code'], $matches);
      if(!empty($matches)){
          foreach ($matches as $res){
              foreach($res as $str){
                  if(stripos($str, 'instance_id') !== false){
                      $str_arr = explode('-', $str);
                      
                      $plug_row->text = $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_replace('{|instance_id-'.$str_arr[1].'|}', 'eiid='.$str_arr[1], $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
//                      var_dump($custom_field['custom_code_field_'.$cust_key.'_custom_code']);
                  }
//                var_dump(stripos($str, 'layout_id'));
              }
          }
      }
      
      preg_match_all('#{|category_id-[0-9]*|}#', $custom_field['custom_code_field_'.$cust_key.'_custom_code'], $matches);
      if(!empty($matches)){
          foreach ($matches as $res){
              foreach($res as $str){
                  if(stripos($str, 'category_id') !== false){
                      $str_arr = explode('-', $str);
                      
                      $plug_row->text = $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = str_replace('{|category_id-'.$str_arr[1].'|}', 'catid='.$str_arr[1], $custom_field['custom_code_field_'.$cust_key.'_custom_code']);
//                      var_dump($custom_field['custom_code_field_'.$cust_key.'_custom_code']);
                  }
//                var_dump(stripos($str, 'layout_id'));
              }
          }
      }
//            var_dump($matches);
            
      if($code_type == 'SCRIPT'){
        $custom_code = '<script type="text/javascript">';
        $custom_code .= $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
        $custom_code .= '</script>';
        $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_code, $layout_html);
      }elseif($code_type == 'PHP'){
//          echo '11111111111111';
          if(!isset($child_entities)){
              $child_entities = array();
          }
        if(!isset($entityInstance)) $entityInstance = new os_cckEntityInstance($db->_db);
        $func_result = replaceMaskCustomCodePHP($entityInstance,$plug_row->text, $layout_params, $layout_html, $layout, $child_entities);
        
        $custom_field['custom_code_field_'.$cust_key.'_custom_code'] = $func_result['custom_code_str'];
        //get variables for custom code
        extract($func_result['variables_arr']);
        
        ob_start();
        $custom_code = eval($custom_field['custom_code_field_'.$cust_key.'_custom_code']);
        $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", ob_get_contents(), $layout_html);
        ob_end_clean();
        
      }elseif($code_type == 'CSS'){
        $custom_css = '<style>'.$custom_field['custom_code_field_'.$cust_key.'_custom_code'].'</style>';
        $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_css, $layout_html);
      }else{
        $custom_code = $custom_field['custom_code_field_'.$cust_key.'_custom_code'];
        $layout_html = str_replace("{|f-custom_code_field_".$cust_key."|}", $custom_code, $layout_html);
      }
    }
  }
}

//echo '22222222222222'; exit;