<?php
/**
 *
 * @package  Real Estate Manager
 * @copyright 2023 Andrey Kvasnevskiy-OrdaSoft (akbet@mail.ru); Rob de Cleen (rob@decleen.com);
 * Homepage: http://www.ordasoft.com
 *
 */

if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
if(!defined('DS'))  define('DS', DIRECTORY_SEPARATOR);

/**
* mosSefurl database table class
*/
jimport( 'joomla.database.table');
class osCckSefurl extends JTable {


//keys
  /** @var int Primary key */
  var $id=null;
  /** @var BLOB */
  var $ser_url_segments=null;
  /** @var varchar(35) */
  var $hash_url_segments=null;
  /** @var BLOB */
  var $ser_vars=null;
  /** @var varchar(35) */
  var $hash_vars=null;
  /** @var varchar(55) */
  var $lang=null;
  /** @var datetime */
  var $date=null;
  /** @var int */
  var $hits=null;
  /** @var boolean */
  var $published=null;


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


    // $query = "delete FROM #__os_cck_sef_urls"; //clean SEF urls tables
    // $this->_db->setQuery($query);
    // $this->_db->execute();
    // exit;

  }

  function loadByHashUrlSegments($hash){

    $this->_db->setQuery("SELECT id FROM #__os_cck_sef_urls WHERE hash_url_segments = '$hash' ");
    $id = intval( $this->_db->loadResult() );
    if ($id) {
      $this->load($id );
      //if url not exist, remove it
      if( !$this->check_url_exist() ){
        return null;
      }

      //if url exist, update it date
      $this->date = date("Y-m-d H:i:s") ;
      $this->store();
      return $this;
      
    }
    else return null;
  }

  function loadByHashVars($hash){
    
    $this->_db->setQuery("SELECT id FROM #__os_cck_sef_urls WHERE hash_vars = '$hash' ");
    $id = intval( $this->_db->loadResult() );
    
    if ($id) {
      $this->load($id );
      //if url not exist, remove it
      
      if( !$this->check_url_exist() ){
        
        return null;
      }
      
      //if url exist, update it date
      $this->date = date("Y-m-d H:i:s") ;
      $this->store();
      return $this;
    }
    else return null;
  }

  function check_url_exist(){
    global $entities_type, $entityFieldLists;

    os_cck_initialization();

    $var_array = unserialize($this->ser_vars)  ;
    if(isset($var_array['task'])){
      $task = $var_array['task'];
    }elseif(isset($var_array['view'])){
      $task = $var_array['view'];
    }
    // var_dump($var_array);
    if(isset($var_array['eiid'])  && 
      ( $task == 'instance' || $task == 'parent_child' || $task == 'show_request_layout' )  ){
      if(isset($var_array['lid'])){
        $query = "SELECT fk_eid FROM #__os_cck_layout WHERE lid=".$var_array['lid'];
        $this->_db->setQuery($query);
        $eid = $this->_db->loadResult();
        
        $entity = new os_cckEntity($this->_db);
        $entity->load($eid);
        // var_dump($entities_type[$eid]);
      }
      // if($task == 'parent_child'){
        // var_dump($var_array);
      // }
      //if link to instance = check so instance exist ?
      if(is_array($var_array['eiid'])){
        $eiid = $var_array['eiid'][0];
      }else{
        $eiid = $var_array['eiid'];
      }
      if($entity->type == 'os_cck_entity'){
        $selectstring = "SELECT eiid FROM #__os_cck_entity_instance WHERE eiid = ". $eiid;
        $this->_db->setQuery($selectstring);
        $instanceData = $this->_db->LoadRow();
      }elseif($entity->type == 'joomla_user'){
        $selectstring = "SELECT id as eiid FROM #__users WHERE id = ". $eiid;
        $this->_db->setQuery($selectstring);
        $instanceData = $this->_db->LoadRow();
      }elseif($entity->type == 'custom_sql'){
        

        $title_field = new stdClass();

        $id_field = 0 ;
        foreach($entityFieldLists[$entity->eid] as $field){
          if($field->custom_field_type == 'id')
          {
            $id_field = $field;
            break;
          }
        }

        $query = "SELECT t.$id_field->fid as eiid FROM ($entity->sql_select) as t WHERE t.$id_field->fid=$eiid";
        $this->_db->setQuery($query);
        $instanceData = $this->_db->LoadRow();
      }

      if( isset($instanceData) && count($instanceData) > 0 ) return $this;
      
      //if Instance not exist - remove this url
      $this->delete();
      return false;

    }else if( isset($var_array['catid']) && 
        isset($task) && $task == "category" ){
      //if link to CATEGORY = check so Instance exist ?
      $selectstring = "SELECT  c.cid FROM #__os_cck_categories AS c "
                      . " WHERE c.cid = " . intval($var_array['catid']);
      $this->_db->setQuery($selectstring);
      $catData = $this->_db->LoadRow();

      if( isset($catData) && count($catData) > 0 ) return $this;

      //if category not exist - remove this url
      $this->delete();
      return false;
    }

    return true;
  }

  
}
