<?php
defined('_JEXEC') or die('Restricted access');

/**
* @package OS CCK
* @copyright OrdaSoft.
* @author Andrey Kvasnevskiy(akbet@mail.ru),Roman Akoev (akoevroman@gmail.com)
* @link http://ordasoft.com/cck-content-construction-kit-for-joomla.html
* @description OrdaSoft Content Construction Kit
*/
use OrdaSoft\os_lib\os_libMain;
use OrdaSoft\os_lib\os_libPagination;

// if( !class_exists("os_libMain") ){
//     try{
//         $ss = new os_libMain();
//     }catch( Exception $e ){
//         die("Please reinstall OrdaSoft Joomla CCK Package!");
//     }
// }
class AdminField{

  static function showLayoutFields($option){
    global $db, $app, $jConf, $entityFieldLists;
    $db = new os_cckDb();
    $limit = $app->getUserStateFromRequest("viewlistlimit", 'limit', $jConf->get("list_limit",10));
    $limitstart = $app->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
    $pub = $app->getUserStateFromRequest("pub{$option}", 'pub', '');
    $entity_id = $app->input->get("fk_eid",'');
    $layout_type = $app->input->get("layout_type",'');
    
    $where = array();
    array_push($where, "ef.fk_eid = e.eid ");
    if ($entity_id != '') {
      array_push($where, "ef.fk_eid ='{$entity_id}'");
    }
    // if ($pub == "pub") {
    //   array_push($where, "ef.published = 1");
    // } else if ($pub == "not_pub") {
    //   array_push($where, "ef.published = 0");
    // }

    $query = "SELECT COUNT(ef.fid) FROM #__os_cck_entity_field AS ef, #__os_cck_entity AS e " .
        (count($where) ? " WHERE " . implode(' AND ', $where) : "");

    $db->setQuery($query);
    $total = $db->loadResult();
    $language = JFactory::getApplication()->getLanguage();
    $language->load('os_lib',JPATH_ROOT);
    $pageNav = new os_libPagination($total, $limitstart, $limit);

    $query = "SELECT ef.* , e.name  FROM #__os_cck_entity_field AS ef, #__os_cck_entity AS e " .
        (count($where) ? " WHERE " . implode(' AND ', $where) : "") .
        " ORDER BY  ef.field_name";

    $db->setQuery($query);
    $extrafield_list = $db->loadObjectList();
    
    $title_fid = 0;
    foreach($extrafield_list as $field){
        $params = new JRegistry;
        try {
            $params->loadString($field->params);
        } catch (Exception $ex) {
//            var_dump($field); exit;
        }
        
//        var_dump($params);
        if($params->get('title_field', '') == 'yes'){
            $title_fid = $field->fid;
        }
    }
//    var_dump($title_fid);
    $entities = array();
    $entities[] = array('value' => '', 'text' => 'All entities');
    $query = "SELECT eid AS value, name AS text FROM #__os_cck_entity ORDER BY name";
    $db->setQuery($query);
    $ent = $db->loadObjectList();
    $entities = (count($ent) > 1) ? array_merge($entities, (array)$ent) : $entities;
    $entity_list = JHTML::_('select.genericlist',$entities, 'entity_id', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $entity_id);

    $pubmenu[] = JHTML::_('select.option','0', cck_lang_text('COM_OS_CCK_LABEL_SELECT_TO_PUBLIC'));
    $pubmenu[] = JHTML::_('select.option','-1', cck_lang_text('COM_OS_CCK_LABEL_SELECT_ALL_PUBLIC'));
    $pubmenu[] = JHTML::_('select.option','not_pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_NOT_PUBLIC'));
    $pubmenu[] = JHTML::_('select.option','pub', cck_lang_text('COM_OS_CCK_LABEL_SELECT_PUBLIC'));
    $publist = JHTML::_('select.genericlist',$pubmenu, 'pub', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $pub);
    
    

    AdminViewField :: showLayoutFields($option, $extrafield_list, $pageNav, $entity_list, $publist, $layout_type, $title_fid);
  }

  static function addLayoutField($option,$fid){
    global $db, $app;
    $db = new os_cckDb();
    $params = new JRegistry;
    if($fid){
      $field = new os_cckEntityField($db->_db);
      $field->load($fid);
      try {
          $params->loadString($field->params);
      } catch (Exception $ex) {
          
      }
      
    }else{
      $field = '';
    }
    
    $layout_type = $app->input->get("layout_type",'');
    
    $field_types = array();
    $field_types[] = JHTML::_('select.option','audiofield', 'Audio Field');
    $field_types[] = JHTML::_('select.option','captcha_field', 'Captcha');
    $field_types[] = JHTML::_('select.option','categoryfield', 'Category');
    $field_types[] = JHTML::_('select.option','text_single_checkbox_onoff', 'Checkbox');
    $field_types[] = JHTML::_('select.option','datetime_popup', 'Date');
    $field_types[] = JHTML::_('select.option','filefield', 'File Field');
    $field_types[] = JHTML::_('select.option','galleryfield', 'Gallery');
    $field_types[] = JHTML::_('select.option','imagefield', 'Image Field');
    $field_types[] = JHTML::_('select.option','locationfield', 'Location map');
    $field_types[] = JHTML::_('select.option','decimal_textfield', 'Number Field');
    if($layout_type != 'rent_request_instance' && $layout_type != 'buy_request_instance'){
        $field_types[] = JHTML::_('select.option','pricefield_number', 'Price Field (Number)');
        $field_types[] = JHTML::_('select.option','pricefield_select_list', 'Price Field (Select List)');
        $field_types[] = JHTML::_('select.option','pricefield_radio_buttons', 'Price Field (Radio buttons)');
    }
    $field_types[] = JHTML::_('select.option','text_radio_buttons', 'Radio buttons');
    $field_types[] = JHTML::_('select.option','rating_field', 'Rating Field');
    $field_types[] = JHTML::_('select.option','text_select_list', 'Select list');
    $field_types[] = JHTML::_('select.option','text_textfield', 'Text');
    $field_types[] = JHTML::_('select.option','text_textarea', 'Text Area');
    $field_types[] = JHTML::_('select.option','text_url', 'Url');
    $field_types[] = JHTML::_('select.option','videofield', 'Video Field');   

    if($fid){
      //print_r($field_types);exit;
      $field_type_input = '<input id="field_type" type="hidden" name="field_type" value="'.$field->field_type.'">'.$field->field_type;  
    }else{
      $field_type_input = JHTML::_('select.genericlist',$field_types, 'field_type',
                         'size="1" onchange="checkFieldType(jQuerOs(this).val())"', 'value', 'text', 'text_textfield');
    }

    AdminViewField::addLayoutField($option, $field_type_input, $params, $field);
  }

  static function saveLayoutField($fid){
    global $db, $mosConfig_absolute_path, $app;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    $input = JFactory::getApplication()->input;
    $params = new JRegistry;
    $fieldName = trim($input->get("field_name","","STRING"));
    //$app = JFactory::getApplication();
    
    $fieldType = $input->get("field_type","","STRING");
    $fieldName = str_ireplace(array("`","'"), "", $fieldName);
    if(trim($fieldType) != 'text_select_list'){
        
        $allowed_value = $input->get("allowed_value",false,"STRING");
        //var_dump($allowed_value); exit;
        if(is_array($allowed_value)){
            $allowed_value = trim($allowed_value[0]);
        }else{
            $allowed_value = trim($allowed_value);
        }
      
      
      $str_param = $allowed_value;
      $child_param = '';
    }else{
        
      $allowed_value = array_diff($input->get("allowed_value", array(),"ARRAY"), array(''));
      $childSelect = $input->get("child_select",array(''),"ARRAY");

      //create string for save in params
      if(count($allowed_value) > 1){
        $str_param = '';
        $child_param = '';
        foreach ($allowed_value as $key => $value) {
          if(!empty($value) && $value != end($allowed_value)){
            $str_param .= $value.'\sprt';
            $child_param .= $childSelect[$key].'|';
          }else{
            $str_param .= $value;
            $child_param .= $childSelect[$key];
          }
        }
      }else{
        $str_param = array_pop($allowed_value);
        $child_param = array_pop($childSelect);
      }
      
    }

    //child selects

    
    $default_value = $input->get("default_value",'',"STRING");
    
    $fk_eid = $input->get("fk_eid",0,"INT");
    $params->set("allowed_value",$str_param);
    $params->set("child_select",$child_param);
    $params->set("default_value",$default_value);


    $field = new os_cckEntityField($db->_db);
    if($fid){
      $field->load($fid);
    }
    $field->field_name = $fieldName;
    $field->params = $params->toString();
    $field->field_type = $fieldType;
    $field->fk_eid = $fk_eid;
    
    if (!$field->store()) {
        $app->enqueueMessage(addslashes($field->getError()), 'warning');
    }
  }

  static function saveLayoutFieldName($option){
    global $db, $mosConfig_absolute_path, $app;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    $input  = JFactory::getApplication()->input;
    
    $fieldName = $input->get("field_name","","STRING");
    $fk_eid = $input->get("fk_eid",0,"INT");
    $fid = $input->get("fid",0,"INT");

    if($fid) {
      $field = new os_cckEntityField($db->_db);
      $field->load($fid);
      $field->field_name = $fieldName;
    }

    if (!$field->store()) {
      $app->enqueueMessage(addslashes($field->getError()), 'warning');
    }

    echo '<span class="cck-success-message">Field(s) deleted successful.</span>';
    self::showLayoutFields($option);
  }

  static function deleteField($option){ 
    global $db, $app;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    $input  = JFactory::getApplication()->input;
    $fidArr = $input->get("fid",array(),"ARRAY");
    foreach ($fidArr as $field_id) {
      $field = new os_cckEntityField($db->_db);
      $field->load($field_id);
      //delete field from layout
      $query = "SELECT id,layout_html FROM #__os_cck_layout_html";
      $db->setQuery($query);
      $layoutArray = $db->loadObjectList();
      foreach ($layoutArray as $layoutArr) {
        $html = urldecode($layoutArr->layout_html);
        if(!empty($html)){
          $html = htmlspecialchars($html);
          $dom = new DOMDocument;
          $dom->loadHTML($html, LIBXML_HTML_NODEFDTD);
          $finder = new DomXPath($dom);
          $classname="drop-item";
          $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
          foreach ($nodes as $contentNode) {
            if(strpos($contentNode->textContent, '{|f-'.$field_id.'|}') != ''){
              $contentNode->parentNode->removeChild($contentNode);
              $layout_html = $dom->saveHTML();
              $layout_html = str_replace('<html><body>', '', $layout_html);
              $layout_html = str_replace('</body></html>', '', $layout_html);
              $layout_html = urlencode($dom->saveHTML());
              $query = "UPDATE #__os_cck_layout_html SET layout_html='$layout_html' WHERE id=$layoutArr->id";
              $db->setQuery($query);
              $db->execute();
            }
          }
        }
      }
      //end layout
      $field->delete();
    }
    echo '<span class="cck-success-message">Field(s) deleted successful.</span>';
    self::showLayoutFields($option);
  }

  static function publishFields($publish, $option){
    global $db, $my, $app;
    $db = new os_cckDb();
    if(!cck_checkReferer()){
        $app->enqueueMessage(cck_lang_text("COM_OS_CCK_ERROR_REFERER_SECURITY"), 'warning');
        return;
    }
    $input  = JFactory::getApplication()->input;
    $fid = $input->get("fid",0,"INT");
    $task = $input->get("task",'',"STRING");
    if(!$fid){
      echo '<span class="cck-error-message">Select an item to '.addslashes($task).'</span>';
      self::showLayoutFields($option);
      return;
    }

    $db->setQuery("UPDATE #__os_cck_entity_field SET published='$publish' WHERE fid = $fid");
    try {
        $db->execute();
    } catch (RuntimeException $e) {
        echo '<span class="cck-error-message">'.addslashes($e->getMessage()).'</span>';
        self::showLayoutFields($option);
        return;
    }
    
    self::showLayoutFields($option);
  }

  static function show_in_ins($show, $option){
    global $db, $my;
    $db = new os_cckDb();
    $input  = JFactory::getApplication()->input;
    $fid = $input->get("fid",0,"INT");
    $task = $input->get("task",'',"STRING");
    if(!$fid){
      echo '<span class="cck-error-message">Select an item to '.addslashes($task).'</span>';
      self::showLayoutFields($option);
      return;
    }

    $db->setQuery("UPDATE #__os_cck_entity_field SET show_in_instance_menu='$show' WHERE fid = $fid");
    try {
        $db->execute();
    } catch (RuntimeException $e) {
        echo '<span class="cck-error-message">'.addslashes($e->getMessage()).'</span>';
        self::showLayoutFields($option);
        return;
    }
    self::showLayoutFields($option);
  }
  
  static function setTitleField($show, $option){
    global $db, $my, $entityFieldLists;
    $db = new os_cckDb();
    $input  = JFactory::getApplication()->input;
    $fid = $input->get("fid",0,"INT");
    $task = $input->get("task",'',"STRING");
    if(!$fid){
      echo '<span class="cck-error-message">Select an item to '.addslashes($task).'</span>';
      self::showLayoutFields($option);
      return;
    }
    
    $field = new os_cckEntityField($db->_db);
    $field->load($fid);
    
    foreach($entityFieldLists[$field->fk_eid] as $old_field){
        $params = new JRegistry;
        $params->loadString($old_field->params);
//        var_dump($params);
        if($params->get('title_field', '') == 'yes'){
            $params->set('title_field', '');
            $params = $params->toString();
            $db->setQuery("UPDATE #__os_cck_entity_field SET params='$params' WHERE fid = $old_field->fid");
            $db->execute();
        }
    }
    
    $params = new JRegistry;
    $params->loadString($field->params);
    $params->set('title_field', 'yes');
    
    $new_params = $params->toString();
//    var_dump($new_params);

    $db->setQuery("UPDATE #__os_cck_entity_field SET params='$new_params' WHERE fid = $fid");
    try {
        $db->execute();
    } catch (RuntimeException $e) {
        echo '<span class="cck-error-message">'.addslashes($e->getMessage()).'</span>';
        self::showLayoutFields($option);
        return;
    }
    self::showLayoutFields($option);
  }

  static function getSelectList(){
    global $db, $app;
    $db = new os_cckDb();
    
    $fk_eid = $app->input->get("fk_eid",'');
    $query = "SELECT * FROM #__os_cck_entity_field WHERE field_type = 'text_select_list' AND  fk_eid = '". $fk_eid ."' ORDER BY fid ASC";
    $db->setQuery($query);
    $result = $db->loadAssocList();

    return $result;
  }
  
  static function getEntityFieldsAjax(){
      global $db, $entities_type, $entityFieldLists; 
      $db = new os_cckDb();
      $input = JFactory::getApplication()->input;
      
      $childEntityId = $input->get('childEntityId', 0, 'INT');
      $layoutType = $input->get('layoutType', '', 'STRING');
      $entityId = $input->get('entityId', 0, 'INT');
      $checkedFields = $input->get('checkedFields', '', 'STRING');
      $editField = $input->get('editField', '', 'STRING');
      $step = $input->get('step', '1', 'STRING');
      $parent_entity_related_fields = $input->get('parent_entity_related_fields', '');
      $child_entity_related_fields = $input->get('child_entity_related_fields', '');
//      var_dump($_REQUEST);
      $childEntity = new os_cckEntity($db->_db);
      $childEntity->load($childEntityId);
      $fields = $childEntity->getFieldList();
//      var_dump($childEntityId);
      $entity = new os_cckEntity($db->_db);
      $entity->load($entityId);
//      var_dump($layoutType);
      if($layoutType == 'instance' || $layoutType == 'search' || $layoutType == 'pdf' || $layoutType == 'parent_child' || $layoutType == 'parent_child_pdf'){
          if($entities_type[$childEntityId] == 'custom_sql' && $entities_type[$entityId] == 'custom_sql'){
              $childEntityFieldsOptions = array();
              
              
              if($step == 1){
                  $parent_fields = $entityFieldLists[$entityId];
                  $parent_fields_opt = array();
                  $parent_fields_opt[] = JHTML::_('select.option', '', cck_lang_text('COM_OS_CCK_PLEASE_SELECT_OPTION'), "value", "text");
                //   var_dump($parent_fields);
                  $dublicate_parent_id = false;
                  if(isset($parent_fields['custom_sql_id'])){
                    foreach($parent_fields as $key => $temp_field){
                        if($key != 'custom_sql_id' && $parent_fields['custom_sql_id']->fid == $temp_field->fid){
                            $dublicate_parent_id = true;
                        }
                    }
                  }
                  $dublicate_parent_title = false;
                  if(isset($parent_fields['custom_sql_title'])){
                    foreach($parent_fields as $key => $temp_field){
                        if($key != 'custom_sql_title' && $parent_fields['custom_sql_title']->fid == $temp_field->fid){
                            $dublicate_parent_title = true;
                        }
                    }
                  }
                  
                  foreach($parent_fields as $key => $temp_field){
                      if($key == 'custom_sql_id' && $dublicate_parent_id) continue;
                      if($key == 'custom_sql_title' && $dublicate_parent_title) continue;
                    //   if($key != 'custom_sql_title' && $key != 'custom_sql_id'){
                        $parent_fields_opt[] = JHTML::_('select.option', $temp_field->fid, $temp_field->field_name, "value", "text");
                    //   }
                  }
                  if($layoutType == 'parent_child' || $layoutType == 'parent_child_pdf'){
                      $parent_fields_select_list = JHTML::_('select.genericlist', $parent_fields_opt, 'parent_entity_related_fields', '', 'value', 'text', '');
                  }else{
                    $parent_fields_select_list = JHTML::_('select.genericlist', $parent_fields_opt, 'parent_entity_related_fields_' . $entityId, 'onchange="addChildEntityFields(\'\',2)"', 'value', 'text', '');
                  }
                  $child_fields = $entityFieldLists[$childEntityId];
                  $child_fields_opt = array();
                  $child_fields_opt[] = JHTML::_('select.option', '', cck_lang_text('COM_OS_CCK_PLEASE_SELECT_OPTION'), "value", "text");
                  $dublicate_child_id = false;
                  if(isset($child_fields['custom_sql_id'])){
                    foreach($child_fields as $key => $temp_field){
                        if($key != 'custom_sql_id' && $child_fields['custom_sql_id']->fid == $temp_field->fid){
                            $dublicate_child_id = true;
                        }
                    }
                  }
                  $dublicate_child_title = false;
                  if(isset($child_fields['custom_sql_title'])){
                    foreach($child_fields as $key => $temp_field){
                        
                        if($key != 'custom_sql_title' && $child_fields['custom_sql_title']->fid == $temp_field->fid){
                            $dublicate_child_title = true;
                        }
                    }
                  }
                  foreach($child_fields as $key => $temp_field){
                     if($key == 'custom_sql_id' && $dublicate_child_id) continue;
                     if($key == 'custom_sql_title' && $dublicate_child_title) continue;
                    //  if($key != 'custom_sql_title' && $key != 'custom_sql_id'){
                        $child_fields_opt[] = JHTML::_('select.option', $temp_field->fid, $temp_field->field_name, "value", "text");
                    //  }
                  }
                  if($layoutType == 'parent_child' || $layoutType == 'parent_child_pdf'){
                      $child_fields_select_list = JHTML::_('select.genericlist', $child_fields_opt, 'child_entity_related_fields', '', 'value', 'text', '');
                  }else{
                    $child_fields_select_list = JHTML::_('select.genericlist', $child_fields_opt, 'child_entity_related_fields_' . $childEntityId, 'onchange="addChildEntityFields(\'\',2)"', 'value', 'text', '');
                  }
              }
              if($step == 2){
                  $child_fieldList = $entityFieldLists[$childEntityId];
                  $child_title_field = $child_fieldList['custom_sql_title'];
                  $child_id_field = $child_fieldList['custom_sql_id'];
                  
                  $query = "SELECT DISTINCT c.$child_id_field->fid as id, c.$child_title_field->fid as title FROM ($entity->sql_select) as p "
                          . "LEFT JOIN ($childEntity->sql_select) as c ON c.$child_entity_related_fields = p.$parent_entity_related_fields";
                  $db->setQuery($query);
//                  var_dump($child_entity_related_fields);
//                  echo $query; exit;
                  $p_ch = $db->loadObjectList();
//                  var_dump($p_ch); exit;
                  $count = count($p_ch);   
                  if($count > 0){
                      foreach($p_ch as $temp){
//                          var_dump($temp);
                        if($temp->id){
                            $childEntityFieldsOptions[] = JHTML::_('select.option', $temp->id, $temp->title, "value", "text");
                        }
                      }

                  }else{

                  }
                  $childEntityFieldsSelectList = JHTML::_('select.genericlist', $childEntityFieldsOptions, 'child_entity_fields_' . $childEntityId, '', 'value', 'text', '');
//              foreach ($child_id_fields as $id){
//                  if(isset())
//              }
              }
//              var_dump($child_id_fields);
          }else{
              $query = "SELECT lid FROM #__os_cck_layout WHERE fk_eid='$entityId' AND type='add_instance'";

              $db->setQuery($query);
              $entity_layouts = $db->loadObjectList();
              $childEntityFieldsOptions = array();
              if($childEntity->type == 'joomla_user' && $entity->type != 'custom_sql'){
                  $childEntityFieldsOptions[] = JHTML::_('select.option', 'owner', 'Owner', "value", "text");
              }
              if(!empty($entity_layouts)){
                  foreach ($entity_layouts as $layout_id){
                      $layout = new os_cckLayout($db->_db);
                      $layout->load($layout_id->lid);
                      $layout_params = unserialize($layout->params);

                      if(isset($layout_params['child_entities']) && is_array($layout_params['child_entities']) 
                              && !empty($layout_params['child_entities'])){
                          foreach ($layout_params['child_entities'] as $child_entity){
                              if($child_entity->childEntityId == $childEntityId){
                                  $childEntityFieldsOptions[] = JHTML::_('select.option', $child_entity->data_field_name, $child_entity->entity_alias, "value", "text");
                              }
                          }
                      }
                  }
              }
          }
          $childEntityFieldsSelectList = JHTML::_('select.genericlist', $childEntityFieldsOptions, 'child_entity_fields_' . $childEntityId, '', 'value', 'text', 0);
//          var_dump($childEntityFieldsSelectList); exit;
      }
      //var_dump($childEntityFieldsOptions);
      $html = '';
      if($layoutType == 'instance' || $layoutType == 'search' || $layoutType == 'pdf'){
          if($entities_type[$childEntityId] == 'custom_sql' && $entities_type[$entityId] == 'custom_sql'){
              if($step == 1){
                  $html .= '<div><div class="custom_to_castom_select"><div>Parents Fields</div><div>'.$parent_fields_select_list.'</div></div>';
                  $html .= '<div class="custom_to_castom_select"><div>Child Fields</div><div>'.$child_fields_select_list.'</div></div></div>';
              }else{
                  $html .= '<div>' . $childEntityFieldsSelectList . '</div>';
                  foreach($fields as $field){
                      if($childEntity->type == 'joomla_user'){
                          $html .= '<div class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="' . str_replace('user_', '', $field->db_field_name) . '"><label>' . $field->field_name . '</label></div>';
                      }else{

                        $html .= '<div class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="' . $field->fid . '"><label>' . $field->field_name . '</label></div>';
                      }
                  }
                  if($layoutType == 'instance' || $layoutType == 'search' || $layoutType == 'pdf'){
                      $html .= '<input type="button" class="button child_entity_fields_button" onclick="addChildEntityShowLayout('.$childEntityId.',\''.$childEntity->name.'\')" value="Add Child">';
                  }else{
                      $html .= '<input type="button" class="button child_entity_fields_button" onclick="addChildEntity('.$childEntityId.',\''.$childEntity->name.'\')" value="Add Child">';
                  }
              }
          }else{
              if(!empty($childEntityFieldsOptions)){

                  if(is_array($fields) && !empty($fields)){
                      if($layoutType == 'instance' || $layoutType == 'search' || $layoutType == 'pdf'){
                          $html .= '<div>' . $childEntityFieldsSelectList . '</div>';
                      }

                      foreach($fields as $field){
                          if($childEntity->type == 'joomla_user'){
                              $html .= '<div class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="' . str_replace('user_', '', $field->db_field_name) . '"><label>' . $field->field_name . '</label></div>';
                          }else{

                            $html .= '<div class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="' . $field->fid . '"><label>' . $field->field_name . '</label></div>';
                          }
                      }

                      if($layoutType == 'instance' || $layoutType == 'search' || $layoutType == 'pdf'){
                          $html .= '<input type="button" class="button child_entity_fields_button" onclick="addChildEntityShowLayout('.$childEntityId.',\''.$childEntity->name.'\')" value="Add Child">';
                      }else{
                          $html .= '<input type="button" class="button child_entity_fields_button" onclick="addChildEntity('.$childEntityId.',\''.$childEntity->name.'\')" value="Add Child">';
                      }

                  }
              }else{
                  $html = '<div style="color: red;"><h3>' . cck_lang_text("COM_OS_CCK_LABEL_ADD_CHILD_ENTITY_FIRST") . '</h3></div>';
              }
          }
          
      }elseif($layoutType == 'parent_child' || $layoutType == 'parent_child_pdf'){
          $lid = $input->get("lid", '', "STRING");
          $html .= '<div><div class="custom_to_castom_select"><div>Parents Fields</div><div>'.$parent_fields_select_list.'</div></div>';
          $html .= '<div class="custom_to_castom_select"><div>Child Fields</div><div>'.$child_fields_select_list.'</div></div></div>';
          $html .= '<input type="button" class="button child_entity_fields_button" onclick="addChildEntityPCh()" value="Add Relate">';
          $html .= '<input type="hidden" id="p-ch-layout-id" value="'.$lid.'">';
      }else{
          
          if(is_array($fields) && !empty($fields)){
              $checkedFields = explode(',', $checkedFields);
              
              if($layoutType == 'instance' || $layoutType == 'pdf'){
                  if($entities_type[$childEntityId] == 'custom_sql' && $entities_type[$entityId] == 'custom_sql'){
                      
                  }else{
                    $html .= '<div>' . $childEntityFieldsSelectList . '</div>';
                  }
              }
              $html .= '<div id="sort">';
              $sort_array = array();
              
              if($editField != ''){
                  foreach($checkedFields as $tempCheckedFields){
                      if($tempCheckedFields != ''){
                          $sort_array[] = $tempCheckedFields;
                      }
                  }
              }
              $sort_array[] = 'id';
              
              foreach($checkedFields as $tempCheckedFields){
                  foreach($fields as $field){
                      if($field->fid == $tempCheckedFields){
                          $html .= '<div id="'.$field->fid.'" class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="' . $field->fid  . '" checked="true"><label>' . $field->field_name . '</label></div>';
                      }
                  }
                  if($tempCheckedFields == 'id'){
                      $html .= '<div id="id" class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="id" checked="true"><label>ID</label></div>';
                  }
              }
              if(!in_array('id', $checkedFields)){
                  $html .= '<div id="id" class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="id"><label>ID</label></div>';
              }
              
              foreach($fields as $field){
                  if(in_array($field->fid, $checkedFields)){
                      $checked = 'checked="true"';
                      continue;
                  }else{
                      $checked = '';
                  }
                  $ftype = $field->field_type;
                  if ($ftype == 'decimal_textfield'
                        || $ftype == 'datetime_popup'
                        || $ftype == 'text_textfield'
                        || $ftype == 'categoryfield'
                        || $ftype == 'text_textarea'
                        || $ftype == 'text_url'
                        || $ftype == 'text_select_list'
                        || $ftype == 'pricefield_number') {
                          $html .= '<div id="'.$field->fid.'" class="child_entity_fields_check"><input type="checkbox" class="child_entity" name="' . $field->fid  . '" '. $checked . '><label>' . $field->field_name . '</label></div>';
                          $sort_array[] = $field->fid;
                        }
                  
              }
              $temp_sort_array = array_unique($sort_array);
              $sort_array = array();
              foreach($temp_sort_array as $arr){
                  $sort_array[] = $arr;
              }
              
              $html .= '</div>';
              if($layoutType == 'instance'){
                  $html .= '<input type="button" class="button child_entity_fields_button" onclick="addChildEntityShowLayout('.$childEntityId.',\''.$childEntity->name.'\')" value="Add Child">';
              }else{
                  if($editField == ''){
                    $html .= '<div><input type="button" class="button child_entity_fields_button" onclick="addChildEntity('.$childEntityId.',\''.$childEntity->name.'\')" value="Add Child"></div>';
                  }else{
                      $html .= '<div><input type="button" class="button child_entity_fields_button" edit-field="'.$editField.'" onclick="editChildEntity('.$childEntityId.',\''.$childEntity->name.'\',\''.$editField.'\')" value="Edit Child"></div>';
                  }
              }
              $html .= "<input type='hidden' name='sorting' id='sorting' value='". json_encode($sort_array)."'>";

          }
      }
      echo $html;
      //var_dump($fields); exit;
  }
  
  static function getNameEntityFieldsAjax(){
      global $db, $entities_type, $entityFieldLists;
      $db = new os_cckDb();
      $input = JFactory::getApplication()->input;
      
      $fieldId = $input->get('fieldId', '', 'STRING');
      $entityId = $input->get('entityId', 0, 'INT');
      $childEntityId = $input->get('childEntityId', 0, 'INT');
      $layoutType = $input->get('layout_type', '', 'STRING');
      $fieldMask = $input->get('fieldMask', '', 'STRING');

      $field = new os_cckEntityField($db->_db);
      if($entities_type[$childEntityId] == 'os_cck_entity'){
        
        $field->load($fieldId);
      }elseif($entities_type[$childEntityId]  == 'joomla_user'){
          $field_list = $entityFieldLists[$childEntityId];
          
          foreach ($field_list as $temp_field){
//              var_dump($temp_field);
//              var_dump($fieldId);
              if($temp_field->db_field_name == 'user_' . $fieldId){
                  $field = $temp_field;
                  break;
              }
          }
      }
      //var_dump(explode('_', $fieldMask)[0]);
      if($layoutType == 'instance' || $layoutType == 'search' || $layoutType == 'pdf'){
          if($entities_type[$childEntityId] == 'joomla_user' && explode('_', $fieldMask)[0] == 'Owner'){
              $childEntityFieldName = 'Owner';
          }else{
              $query = "SELECT lid FROM #__os_cck_layout WHERE fk_eid='$entityId' AND type='add_instance'";

              $db->setQuery($query);
              $entity_layouts = $db->loadObjectList();

              $childEntityFieldName = '';
              if(!empty($entity_layouts)){
                  foreach ($entity_layouts as $layout_id){
                      $layout = new os_cckLayout($db->_db);
                      $layout->load($layout_id->lid);
                      $layout_params = unserialize($layout->params);

                      if(isset($layout_params['child_entities']) && is_array($layout_params['child_entities']) 
                              && !empty($layout_params['child_entities'])){

                          foreach ($layout_params['child_entities'] as $child_entity){
                              if($child_entity->data_field_name . '_'.$fieldId == $fieldMask){
                                  $childEntityFieldName = $child_entity->entity_alias;
                              }
                         }
                      }
                  }
              }
          }
          //$childEntityFieldsSelectList = JHTML::_('select.genericlist', $childEntityFieldsOptions, 'child_entity_fields_' . $childEntityId, '', 'value', 'text', 0);
          //var_dump($entity_layouts); exit;
      }
      if($childEntityFieldName == '' && stripos($fieldMask, 'Owner_') !== false){
          $childEntityFieldName = 'Owner';
      }
      //var_dump($childEntityFieldName);
      $name = $childEntityFieldName . ' - ';
      if(property_exists($field, 'field_name')){
        $name .= $field->field_name;
      }
    //   var_dump($name);
      echo $name;
  }

  static function addFieldMaskForSqlWhereLayoutOptionByInParentChildLayoutAjax(){
      global $db, $input, $entities_type;
      $db = new os_cckDb();
      $lid = $input->get("lid", '', "STRING");
      $child_lid = $input->get("key",'',"STRING");

      $layout = new os_cckLayout($db->_db);
      $layout->load($lid);
      
      $child_layout = new os_cckLayout($db->_db);
      $child_layout->load($child_lid);
      $child_entity_id = $child_layout->fk_eid;
      
      $layout->custom_field_mask_list = get_custom_mask_list($child_entity_id);
      
      if($entities_type[$child_entity_id] == 'os_cck_entity'){
          $original_select = '<div class="original_select">
                <br>
                SELECT DISTINCT c_p_ch.fid_child, c_p_ch.fid_parent FROM #__os_cck_entity_instance AS ei <br>
                LEFT JOIN #__os_cck_child_parent_connect as c_p_ch <br>ON (c_p_ch.fid_child = ei.eiid OR c_p_ch.fid_parent = ei.eiid) <br>
                LEFT JOIN #__os_cck_content_instances_price AS price ON price.fk_eiid=ei.eiid <br>
                LEFT JOIN `#__os_cck_content_entity_$child_entity_id` as instance <br> ON instance.`fk_eiid` = ei.eiid <br>
                WHERE ei.published="1" <br>
                AND ei.approved="1" <br>
                AND ei.fk_eid="$child_entity_id" <br>
                AND (c_p_ch.fid_child="$parent_instance_id" OR c_p_ch.fid_parent="$parent_instance_id") 
                <span class="your_sql_where">{Your "Sql Where" expression}</span>
            </div>';
      }else{
          $original_select = '<div class="original_select">
                <br>
                SELECT us.id as eiid FROM #__users as us 
                LEFT JOIN #__user_usergroup_map as ugm ON ugm.user_id = us.id 
                LEFT JOIN #__usergroups as ug ON ug.id = ugm.group_id 
                LEFT JOIN #__user_profiles as prof ON us.id = prof.user_id 
                LEFT JOIN #__fields_values as val ON us.id = val.item_id 
                LEFT JOIN #__fields as fi ON val.field_id = fi.id 
                WHERE block=0
                <span class="your_sql_where">{Your "Sql Where" expression}</span>
            </div>';
      }
        //$layout_params = unserialize($layout->params);
      ob_start();
          require getLayoutPathCCK::getAdminLayoutViewPath('com_os_cck', 'modal_snippets', 'field-sql-show-modal');
          $html = ob_get_contents();
      ob_end_clean();

      $response = array('html' => $html);
      echo json_encode($response);
  }
  
  static function getFieldSettingsForChildEnteties($layout_type){
      global $cck_entity_configuration, $input, $db;
            $db = new os_cckDb();
            //var_dump($_POST); exit;
            $unique_id = $input->get("unique_id",'',"STRING");
            $entityId = $input->get("entityId", 0, 'INT');
            $entity = new os_cckEntity($db->_db);
            $entity->load($entityId);
            
            if($entity->type == 'os_cck_entity'){
                $field = new os_cckEntityField($db->_db);
                $field->load($input->get('fid', 0, 'INT'));
                // var_dump($field);
                $field->db_field_name = $unique_id;
            }elseif($entity->type == 'joomla_user'){
                $field_list = $entity->getFieldList();
                foreach ($field_list as $temp_field){
                    //var_dump($input->get('fid', '', 'STRING'));
                    if($temp_field->db_field_name == 'user_' . $input->get('fid', '', 'STRING')){
                        $field = $temp_field;
                        
                        $field->db_field_name = $unique_id;
                    }
                }
            }elseif($entity->type == 'custom_sql'){
                $field_list = $entity->getFieldList();
                foreach ($field_list as $temp_field){
//                    var_dump($temp_field);
                    if($temp_field->db_field_name == 'custom_sql_' . $input->get('fid', '', 'STRING')){
                        $field = $temp_field;
                        
                        $field->db_field_name = $unique_id;
                    }
                }
            }

            $name = $input->get("name",'',"STRING");
            if($name != ''){
                $field->field_name = $name;
            }
                        // var_dump($field);
            $gtree = get_group_children_tree_cck();
            $layout_id = $input->get('lid', 0, 'INT');
            $layout = new os_cckLayout($db->_db);
            $layout->load($layout_id);
            $layoutType = $layout_type;
            if($layout_type == 'search'){
                ob_start();
                    require getAdminFiledSettingsViewPath('com_os_cck', 'search', $field->field_type);
                    $settings = ob_get_contents();
                ob_end_clean();
            }else{
                ob_start();
                    require getAdminFiledSettingsViewPath('com_os_cck', 'show', $field->field_type);
                    $settings = ob_get_contents();
                ob_end_clean();
            }
            
        return $settings;
  }
  
  public static function getDatatimeFieldsAjax($eiid){
      global $input, $db;
      $db = new os_cckDb();
      //$eiid = $input->get('eiid', 0, 'INT');
      
      $query = "SELECT fk_eid FROM #__os_cck_entity_instance WHERE eiid=".$eiid;
      $db->setQuery($query);
      $eid = $db->loadResult();
      
      $query = "SELECT fid, field_name FROM #__os_cck_entity_field WHERE field_type='datetime_popup' AND published='1' AND fk_eid='$eid'";
      $db->setQuery($query);
      $fields = $db->loadObjectList();
      
      $field_option = array();
      
      $field_option[] = JHTML::_('select.option',"0", cck_lang_text('COM_OS_CCK_LABEL_SHOW_FIELD_PLEASE_SELECT'));
      foreach($fields as $field){
        $field_option[] = JHTML::_('select.option',$field->fid, $field->field_name);
      }
      $field_list = JHTML::_('select.genericlist',$field_option, 'recursive_field', 'class="inputbox" size="1"', 'value', 'text', '0');
      
      $intervals_option = array();
      $intervals_option[] = JHTML::_('select.option',"0", cck_lang_text('COM_OS_CCK_LABEL_SHOW_FIELD_PLEASE_SELECT'));
      $intervals_option[] = JHTML::_('select.option',"1 year", "1 year");
      $intervals_option[] = JHTML::_('select.option',"1 month", "1 month");
      $intervals_option[] = JHTML::_('select.option',"1 week", "1 week");
      $intervals_option[] = JHTML::_('select.option',"1 day", "1 day");
      $intervals_option[] = JHTML::_('select.option',"1 hour", "1 hour");
      $intervals_option[] = JHTML::_('select.option',"55 minutes", "55 Minutes");
      $intervals_option[] = JHTML::_('select.option',"50 minutes", "50 Minutes");
      $intervals_option[] = JHTML::_('select.option',"45 minutes", "45 Minutes");
      $intervals_option[] = JHTML::_('select.option',"40 minutes", "40 Minutes");
      $intervals_option[] = JHTML::_('select.option',"35 minutes", "35 Minutes");
      $intervals_option[] = JHTML::_('select.option',"30 minutes", "30 Minutes");
      $intervals_option[] = JHTML::_('select.option',"25 minutes", "25 Minutes");
      $intervals_option[] = JHTML::_('select.option',"20 minutes", "20 Minutes");
      $intervals_option[] = JHTML::_('select.option',"15 minutes", "15 Minutes");
      $intervals_option[] = JHTML::_('select.option',"10 minutes", "10 Minutes");
      $intervals_option[] = JHTML::_('select.option',"5 minutes", "5 Minutes");
      $intervals_list = JHTML::_('select.genericlist',$intervals_option, 'time_intervals', 'class="inputbox" size="1"', 'value', 'text', '0');
      
//      $number_of_copies_option = array();
//      $number_of_copies_option[] = JHTML::_('select.option',"0", "Select type");
      
      $html = AdminViewField::getDatatimeFieldsAjaxHtml($field_list, $intervals_list);
      //$response = array('html' => $html);
      
      return $html;
  }
  
  public static function getChildEntityFieldsAutocomplite(){
      
      $search = protectInjectionWithoutQuote('name_startsWith', '', 'STRING');
      $childEntityFields = protectInjectionWithoutQuote('childEntityFields', '', 'STRING');
      $eid = protectInjectionWithoutQuote('childEntityId', '', 'STRING');
      $order_by = protectInjectionWithoutQuote('order_by', '', 'STRING');
      
      $childEnteties = getValuesForChildEnteties($childEntityFields, $eid, $order_by, $search);
      
      echo json_encode($childEnteties);
      //var_dump($childEnteties);
  }
  
  static function setShowField($task, $option){
    global $db, $my, $entityFieldLists;
    $db = new os_cckDb();
    $input  = JFactory::getApplication()->input;
    $fid = $input->get("fid",0,"INT");
    $task = $input->get("task",'',"STRING");
    $property = str_replace('set_', '', $task);
    if(!$fid){
      echo '<span class="cck-error-message">Select an item to '.addslashes($task).'</span>';
      self::showLayoutFields($option);
      return;
    }
    
    $field = new os_cckEntityField($db->_db);
    $field->load($fid);

        
    $params = new JRegistry;
    $aaa = '{"allowed_value":"One\\sprtTwo\\sprtThree","child_select":"0|0|0","default_value":""}';
    $aaa = '{"allowed_value":"One\\sprtTwo\\sprtThree","child_select":"0|0|0","default_value":""}';
    $aaa = '{"allowed_value":"One\sprtTwo\sprtThree","child_select":"0|0|0","default_value":"","show_in_orders":"yes"}';
//    $params->loadString($aaa); exit;
//        var_dump($field->params); exit;
    
    try {
        $params->loadString($field->params);
    } catch (Exception $ex) {
        var_dump($field->params); exit;
    }
//    var_dump($field->params); exit;
    if($params->get($property, '') == 'yes'){
        $params->set($property, '');
    }else{
        $params->set($property, 'yes');
    }
    if($field->field_type == 'text_select_list' || $field->field_type == 'pricefield_select_list'
            || $field->field_type == 'pricefield_radio_buttons' || $field->field_type == 'text_radio_buttons'){
        $allowed_value = $params->get('allowed_value', '');
//        var_dump($allowed_value); //exit;
        $allowed_value = str_replace('\\', '\\\\', $allowed_value);
        $params->set('allowed_value', $allowed_value);
        if($field->field_type == 'pricefield_select_list'
            || $field->field_type == 'pricefield_radio_buttons' || $field->field_type == 'text_radio_buttons'){
            $allowed_value = $params->get('allowed_value', '');
//            $allowed_value = urlencode($allowed_value);
//            var_dump($allowed_value); exit;
            $allowed_value = str_replace(PHP_EOL, '<br>', $allowed_value);
//            $allowed_value = str_replace('<br>', '\\'.PHP_EOL, $allowed_value);
//            $allowed_value = br2nl($allowed_value);
//            var_dump(explode('<br>', $allowed_value));
//            if (strpos($allowed_value, '%0D%0A') !== false) $allowed_value = explode('%0D%0A', $allowed_value);
//            else if (strpos($allowed_value, '%0D') !== false) $allowed_value = explode('%0D', $allowed_value);
//            else if (strpos($allowed_value, '%0A') !== false) $allowed_value = explode('%0A', $allowed_value);
//            var_dump($allowed_value); exit;
//            $allowed_value = implode(PHP_EOL, $allowed_value);
//            $allowed_value = urldecode($allowed_value);
            $params->set('allowed_value', $allowed_value);
            }
//        var_dump($params); exit;
    }
//    var_dump($params); exit;
    
    $new_params = $params->toString();
//    var_dump($new_params); exit;

    $db->setQuery("UPDATE #__os_cck_entity_field SET params='$new_params' WHERE fid = $fid");
    try {
        $db->execute();
    } catch (RuntimeException $e) {
        echo '<span class="cck-error-message">'.addslashes($e->getMessage()).'</span>';
        self::showLayoutFields($option);
        return;
    }
    self::showLayoutFields($option);
  }
}

