<?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 from data defination for Entity
*/

class os_cckEntity extends JTable{

  var $_entity_name = null;

  /** @var name for define second table */
  var $eid = null;
  var $asset_id = null;
  var $name = null;
  var $type = null;
  var $fk_userid = null;
  var $published = null;
  var $approved = null;
  var $created = null;
  var $changed = null;
  var $checked_out = null;
  var $checked_out_time = null;
  var $sql_select = '';
  var $custom_fields = '';

  /**
   * @param database - A database connector object
   */
  function __construct(&$db){
    parent::__construct('#__os_cck_entity', 'eid', $db);
  }

  function quoteName($name){
    $return = $this->_db->quoteName($name);
    return $return;
  }

  /**
   * Check exist this type entity
   *
   * @param string  entity_name    The table type to instantiate
   * @param array $options Configuration array for model. Optional.
   * @return database A database object
   * @since 1.5
   */
  static function is_entity_name_exist($entity_name, $config = array()){
    $db = JFactory::getDBO();

    $db->setQuery("SELECT name FROM #__os_cck_entity WHERE name = '$entity_name' ");
    $tmp = $db->loadResult();
    
    if (isset($tmp) == 0) {
      return false;
    }
    return true;
  }


  // overloaded check function
  // function check(){
  // }

  /**
   * Default delete method
   *
   * can be overloaded/supplemented by the child class
   *
   * @access public
   * @return true if successful otherwise returns and error message
   */
  function delete($oid = null){
    global $entities_type, $entityFieldLists;
    $app = JFactory::getApplication();
    $k = $this->_tbl_key;
    if ($oid) {
      $this->$k = $oid;
    }
    if (!$this->is_entity_name_exist($this->name)) {
      $app->enqueueMessage("Before delete Entity you must save it!", 'error');
      return false;
    }
    if($entities_type[$this->eid] != 'joomla_user' && $entities_type[$this->eid] != 'custom_sql'){
        $fields = $entityFieldLists[$this->eid];
        if(is_array($fields)) {
            $lastField = count($fields);
        }else{
            $lastField = 0;
        }
        $count = 0;
        if($lastField){
          foreach ($fields as $field) {
            $count++;
            $os_cckEntityField = new os_cckEntityField($this->_db);
            $os_cckEntityField->load($field->fid);
            $os_cckEntityField->delete();
          }
        }
        $query = "DROP TABLE #__os_cck_content_entity_" . $this->eid;
        $this->_db->setQuery($query);
        if (!$this->_db->execute()) {
          //error create new table
          $this->setError($this->_db->getErrorMsg());
          return false;
        }
    }else{
        $query = "DROP TABLE #__os_cck_content_entity_" . $this->eid;
        $this->_db->setQuery($query);
        if (!$this->_db->execute()) {
          //error create new table
          $this->setError($this->_db->getErrorMsg());
          return false;
        }
    }

    $pk = (is_null($oid)) ? $this->$k : $oid;
    // If no primary key is given, return false.
    if ($pk === null) {
      throw new UnexpectedValueException('Null primary key not allowed.');
    }
    // Delete the row by primary key.
    $query = $this->_db->getQuery(true);
    $query->delete();
    $query->from($this->_tbl);
    $query->where($this->_tbl_key . ' = ' . $this->_db->quote($pk));
    $this->_db->setQuery($query);
    // Check for a database error.
    $this->_db->execute();
    $ret = true;
    recursiveRemoveDir(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$this->eid);
    return $ret;
  }

  function getField($fid){
    $query = "SELECT * FROM #__os_cck_entity_field WHERE fid = '".$fid."'";
    $this->_db->setQuery($query);
    return $this->_db->loadObject();
  }

  function getFieldList($layout_html = ''){
    $fields = array();
    if($this->type == 'os_cck_entity'){
        //var_dump($this); exit;
      $query = ' SELECT f.* FROM #__os_cck_entity_field AS f '.
              ' WHERE f.fk_eid = ' . $this->eid . ' ORDER BY field_name';
      $this->_db->setQuery($query);
      $result = $this->_db->loadObjectList();
      //select only exist layout field for NEXT update/store function
      if($layout_html){
        $fields = array();
        $layout_html = urldecode($layout_html);
        foreach ($result as $field) {
          if(strpos($layout_html,"{|f-".$field->fid."|}")){
            $fields[] = $field;
          }
        }
      }else{
        $fields = $result;
      }
      //var_dump($fields);
    }elseif($this->type == 'joomla_user'){
        if (version_compare(JVERSION, "4.0.0-alpha10", "ge")) {
              $joom_user = JFactory::getUser();

              JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
              JPluginHelper::importPlugin('user');
              JForm::addFormPath(JPATH_SITE . '/components/com_users/forms');

              $user_profile_form = JForm::getInstance('com_users.user', 'profile');

              $offset = 0;
              $plug_params = 1;
               //run mambot onPrepareContent on plug_row object
              // Trigger the onContentPrepare event.
              $results2 = JFactory::getApplication()->triggerEvent('onContentPrepareData', array("com_users.user", $joom_user));
              $results = JFactory::getApplication()->triggerEvent('onContentPrepareForm', array($user_profile_form, $joom_user));

              $user_profile_form->bind($joom_user);
              
              $user_profile = JUserHelper::getProfile($joom_user->id);
              $fieldsets = $user_profile_form->getFieldsets();

          }else{
              $user = JFactory::getUser();
              // Load the fields helper
              JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
              // Gets the fields associated with the 'com_users.user' instance
              // Since we give an actual object instance (and not, for example, just the id), in returned $customFields there will be a 'value' property for every additional fields
              $customFields = FieldsHelper::getFields('com_users.user');

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

              $user_profile = JUserHelper::getProfile($user->id);
              $fieldsets = $user_profile_form->getFieldsets();
          }
        //$user_fields = $user_profile_form->getFieldset($fieldsets['fields-0']->name);
        //var_dump($user_profile_form);
        $fild_list = unserialize($this->custom_fields);
        $fields = array();
        foreach($fild_list['standart'] as $key => $temp_field){
            if($temp_field != '0'){
                switch ($temp_field){
                    case 'text':
                    case 'title':
                        $field_type = 'text_textfield';
                        break;
                    
                    case 'textarea':
                        $field_type = 'text_textarea';
                        break;
                    
                    case 'img':
                        $field_type = 'imagefield';
                        break;
                    
                    case 'date':
                        $field_type = 'datetime_popup';
                        break;
                    
                    case 'number':
                        $field_type = 'decimal_textfield';
                        break;
                    
                    case 'url':
                        $field_type = 'text_url';
                        break;
                    
                    default :
                        $this->setError(cck_lang_text("COM_OS_CCK_FIELD_TYPE_ERROR"));
                        return false;
                        
                }
                $field = new os_cckEntityField($this->_db);
                $field->fid = $key;
                $field->fk_eid = $this->eid;
                $field->field_name = ucfirst($key);
                $field->field_type = $field_type;
                $field->db_field_name = 'user_'.'standart_'.$key;
                $field->published = 1;
                $fields[] = $field;
            }
        }
        
        foreach ($fieldsets as $fieldset){
            if($fieldset->name == 'actionlogs'){continue;}
            if(isset($fild_list[$fieldset->name])){
                $temp_field_list = $user_profile_form->getFieldset($fieldset->name);
                foreach($temp_field_list as $temp_field){
                    if(isset($fild_list[$fieldset->name][$temp_field->fieldname]) && $fild_list[$fieldset->name][$temp_field->fieldname] != '0'){
                        switch ($fild_list[$fieldset->name][$temp_field->fieldname]){
                            case 'text':
                            case 'title':
                                $field_type = 'text_textfield';
                                break;

                            case 'textarea':
                                $field_type = 'text_textarea';
                                break;

                            case 'img':
                                $field_type = 'imagefield';
                                break;

                            case 'date':
                                $field_type = 'datetime_popup';
                                break;

                            case 'number':
                                $field_type = 'decimal_textfield';
                                break;

                            case 'url':
                                $field_type = 'text_url';
                                break;

                            default :
                                $this->setError(cck_lang_text("COM_OS_CCK_FIELD_TYPE_ERROR"));
                                return false;

                        }
                        $field = new os_cckEntityField($this->_db);
                        $field->fid = $temp_field->fieldname;
                        $field->fk_eid = $this->eid;
                        //var_dump(trim(strip_tags($temp_field->label)));
                        $field->field_name = trim(trim(strip_tags($temp_field->label)), ':');
                        $field->field_type = $field_type;
                        $field->db_field_name = 'user_'.$fieldset->name.'_'.$temp_field->fieldname;
                        $field->published = 1;
                        $fields[] = $field;
                    }
                      
                }
                
            }
            
            
        }
        //var_dump($fild_list);
    }elseif ($this->type == 'custom_sql') {
          
    
        $fild_list = unserialize($this->custom_fields);
                
                if($fild_list) {
                    foreach ($fild_list as $key => $temp_field) {

                        if ($temp_field != '0' && $temp_field != 'custom_child_ids' && $key != 'custom_child_ids') {
                            switch ($temp_field) {
                                case 'id':
                                case 'title':
                                case 'text':
                                case 'child_id':
                                    $field_type = 'text_textfield';
                                    break;

                                case 'textarea':
                                    $field_type = 'text_textarea';
                                    break;

                                case 'img':
                                    $field_type = 'imagefield';
                                    break;

                                case 'date':
                                    $field_type = 'datetime_popup';
                                    break;

                                case 'number':
                                    $field_type = 'decimal_textfield';
                                    break;

                                case 'url':
                                    $field_type = 'text_url';
                                    break;

                                case 'pricefield_number':
                                    $field_type = 'pricefield_number';
                                    break;

                                default :
                                    $this->setError(cck_lang_text("COM_OS_CCK_FIELD_TYPE_ERROR"));
                                    return false;

                            }
                            $field = new os_cckEntityField($this->_db);
                            $field->fid = $key;
                            $field->fk_eid = $this->eid;
                            $field->field_name = ucfirst($key);
                            $field->field_type = $field_type;
                            $field->db_field_name = 'custom_sql_'.str_replace(' ', '_', $key);
                            $field->published = 1;
                            $fields[] = $field;
                        }
                    }
                }
    }
  return $fields;
}

  function store($updateNulls = false){
    $new = false;
    
    if(!$this->eid)$new = true;

    if(!parent::store()){
        var_dump($this);
        var_dump($this->getError()); exit;
        echo $this->getError();
        return false;
    }
    
    if($new && $this->eid){
        //We use the Engine InnoDB for the os_cck_content_entity table to avoid an error with more than 64 keys.
      $query = "CREATE TABLE #__os_cck_content_entity_" . $this->eid .
        " (`ceid` int(11) unsigned NOT NULL AUTO_INCREMENT, " .
        " `fk_eiid` int(11) unsigned NOT NULL , " .
        " PRIMARY KEY `ceid` (`ceid`), foreign KEY  (`fk_eiid`) REFERENCES #__os_cck_entity_instance(`eiid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ";

      $this->_db->setQuery($query);
      if (!$this->_db->execute()) {
        //error create new table
        $this->setError($this->_db->getErrorMsg());
        return false;
      }

      if(!file_exists(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$this->eid)){
        mkdir(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$this->eid, 0755, true);
        file_put_contents(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$this->eid . '/index.html', '');
        file_put_contents(JPATH_SITE . '/components/com_os_cck/files/entity_files_'.$this->eid . '/custom.css', '');
      }
    }
    return true;
  }

  function getIndexedFieldList(){
    $fields = $this->getFieldList();
    $indexed = array();
    foreach($fields as $key => $field) {
      if($field->field_type == "categoryfield" || $field->field_type == "rating_field"
        || $field->field_type == "datetime_popup" || $field->field_type == "decimal_textfield"
        || $field->field_type == "decimal_textfield" || $field->field_type == "text_textfield"
        || $field->field_type == "pricefield_number"){
        $indexed[$key]['text'] = $field->field_name;
        $indexed[$key]['value'] = $field->db_field_name;
      }
    }

    usort($indexed, function($a, $b){
                    if ($a['text'] == $b['text']) return 0;
                    return ($a['text'] < $b['text']) ? -1 : 1;
                  }
          );

    return $indexed;
  }



  function getEventTitleFieldList(){
    $fields = $this->getFieldList();
    $indexed = array();

    foreach($fields as $key => $field) {
      if($field->field_type == "text_textfield"){
        $indexed[$key]['text'] = $field->field_name;
        $indexed[$key]['value'] = $field->db_field_name;
      }
    }
    return $indexed;
  }

  function getDatePopupFieldList(){
    $fields = $this->getFieldList();
    $indexed = array();
    foreach($fields as $key => $field) {
      if($field->field_type == "datetime_popup"){
        $indexed[$key]['text'] = $field->field_name;
        $indexed[$key]['value'] = $field->db_field_name;
      }
    }
    return $indexed;
  }

  function getTextAreaFieldList(){
    $fields = $this->getFieldList();
    $indexed = array();
    foreach($fields as $key => $field) {
      if($field->field_type == "text_textarea"){
        $indexed[$key]['text'] = $field->field_name;
        $indexed[$key]['value'] = $field->db_field_name;
      }
    }
    return $indexed;
  }

  function getLocationFieldList(){
    $fields = $this->getFieldList();
    $indexed = array();
    foreach($fields as $key => $field) {
      if($field->field_type == "locationfield"){
        $indexed[$key]['text'] = $field->field_name;
        $indexed[$key]['value'] = $field->db_field_name;
      }
    }
    return $indexed;
  }




}
