<?php

/**
* @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
*/
defined('_JEXEC') or die;
use Joomla\CMS\Component\Router\RouterBase;
//use Joomla\CMS\Component\Router\RouterInterface;

$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path'] = JPATH_SITE;
//require_once($mosConfig_absolute_path . "/components/com_os_cck/os_cck.php");
if(!function_exists("pu_auto_include")){
    function pu_auto_include($path_to_files)
    {
      $component_path = JPath::clean(JPATH_SITE . $path_to_files);
      if (is_dir($component_path) && ($component_layouts = JFolder::files($component_path, '^[^-]*\.php$', false, true))) {
          foreach ($component_layouts as $i => $file) {
              require_once($file);
          }
      }
    }
}
if (version_compare(JVERSION, "4.0.0", "lt")) {
    pu_auto_include('/libraries/os_lib/src');
    // require_once($mosConfig_absolute_path . "/libraries/os_lib/src/os_libHtmlInputs.php");
    // require_once($mosConfig_absolute_path . "/libraries/os_lib/src/os_libHtmlSelect.php");
    // require_once($mosConfig_absolute_path . "/libraries/os_lib/src/os_libMain.php");
    // require_once($mosConfig_absolute_path . "/libraries/os_lib/src/os_libPagination.php");
}
require_once($mosConfig_absolute_path . "/components/com_os_cck/classes/instance.class.php");
require_once($mosConfig_absolute_path . "/components/com_os_cck/classes/entity.class.php");
require_once($mosConfig_absolute_path . "/components/com_os_cck/classes/layout.class.php");
require_once($mosConfig_absolute_path . "/components/com_os_cck/functions.php");
require_once($mosConfig_absolute_path . "/components/com_os_cck/classes/sefurl.class.php");
require_once($mosConfig_absolute_path . "/components/com_os_cck/classes/cckDb.class.php");
require_once($mosConfig_absolute_path . "/components/com_os_cck/classes/field.class.php");

$GLOBALS['pu_debug'] = false;
function pu_log_cck($msg, $request=false ) {

    global $pu_debug;

    if($pu_debug){
              // Write out new initialization file
        $logFilePath =  "./components/com_os_cck/log_debug.log" ;
        $fd = fopen($logFilePath, "a+")
                or die("Cannot create ./components/com_os_cck/log_debug.log file.");
        if(!empty($msg) ){
          fwrite($fd, "---------------".date( "d M Y G:i:s" ) ."\n");
          fwrite($fd, $msg ."\n" );
        } 
        if($request){
          if(is_string( $request ) || is_int( $request ) )  fwrite($fd,  $request ."\n" );
          else if(is_array( $request ) || is_object( $request ) ) 
            foreach($request as $key=>$value){
                if(is_string( $value ) || is_int( $value ) ) 
                    fwrite($fd,  "[".$key."] = ".$value ."\n" );
                else if(is_array( $value ) || is_object( $value ) ) {
                    fwrite($fd,  "[".$key."] = ".pu_log_cck("",$value) ."\n" );
                }
            }
        }
        fclose($fd);    
      }
}




class Os_cckRouter extends RouterBase
{
    public function build(&$query)
    {
        global $entityFieldLists, $entities_type;
        $db = new os_cckDb();


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


pu_log_cck("CckRouter:build 1:",$query);          
        $os_cck_configuration = JComponentHelper::getParams('com_os_cck');
//         var_dump($query);
        
        if($os_cck_configuration->get('sef_url' , '1') == '1'){
pu_log_cck("CckRouter:build 10:",$query);
            $segments = array();
            $segments_with_id = array(); //need if same $segments exist for other URL(same instance name.. )
            if (isset($query['view']))   $view =$query['view'] ;
            if (isset($query['task']))   $task =$query['task'] ;
            else if(isset($query['view']))  $task =$query['view'] ;

            if(isset($view) && isset($task) &&  $view != $task ) $view = $task ;
            
            if(!isset($task)){
pu_log_cck("CckRouter:build 11:",$query);          
                
                $task = 'cck_layout'; 
                $query['view'] = 'cck_layout'; 
//                $query['task'] = 'cck_layout';
            }

            if(isset($view) && !isset($query['view']) ) $query['view'] = $view ;
            if(isset($task) && !isset($query['view']) ) $query['view'] = $task ;
            

            if($task == 'edit_instance' || $task == 'instance_manager' || $task == 'show_rent_request_instances' || $task == 'show_request_instances' || $task == 'show_user_rent_history') {
pu_log_cck("CckRouter:build 12:",$query);          
                return $segments;
            }

            if (isset($query['Itemid']) ) { 
                //for menu items - not use router
                
                if(!isset($task) ) {
pu_log_cck("CckRouter:build 2:",$segments);          
                    return $segments;
                }
                
                if (isset($query['view']) ) { 
                    
                    $url_alias = get_menu_url_alias_cck($query['Itemid'],$query['view'],$task) ;
                    if(!empty($url_alias) ) {
                        //we in some exectly menu
                        
                        if ( !isset($query['start']) && !isset($query['limitstart'])
                            )  {
//                                 var_dump($url_alias);
                            unset($query['view']);
                            unset($query['layout']);
pu_log_cck("CckRouter:build 3:",$segments);          
                
                            return $segments;
                        }

                    }
                }
            }


            // if((isset($query['start']) || isset($query['limitstart'])) && (isset($query['view']) && $query['view'] == 'cck_layout')){
            if((!isset($task) || $task == 'cck_layout') && (isset($query['view']) && $query['view'] == 'cck_layout')){
pu_log_cck("CckRouter:build 31:",$query);          
                $menu = new JTableMenu($db->_db);
                $menu->load($query['Itemid']);
                $menu_params = new JRegistry;
                if($menu->params){
                  $menu_params->loadString($menu->params);
                }  

                $task = $menu_params->get('layout_type');
                $query['view'] = $task;
                $query['lid'] = $menu_params->get('layout');

                $entity_type = $menu_params->get('entity_type', 'os_cck_entity');
                if($task == 'parent_child' && $entity_type == 'joomla_user'){
                    $query['eiid'] = $menu_params->get('user');
                }elseif($task == 'parent_child' && ($entity_type == 'custom_sql' || $entity_type == 'os_cck_entity')){
                    $query['eiid'] = $menu_params->get('instance');
                }

                if($task == 'user_instances'){
                    $query['userId'] = $menu_params->get('user');
                }


pu_log_cck("CckRouter:build 311:",$query);          
                
            }

            //if "view" and "task" not exist - as example for some menu item
            if ( (!isset($task) OR $task == '' ) && (!isset($view) OR $view == '') ){
                $app = JFactory::getApplication();
                $menu = $app->getMenu() ;
                $item  = $menu->getActive();
                if( isset($item) ) $GLOBALS['task'] = $query['task'] = $query['view'] = $item->query['view'];
            }
            
            // if((isset($query['start']) || isset($query['limitstart'])) && !isset($query['lid']) && isset($query['Itemid'])){
            if( !isset($query['lid']) && isset($query['Itemid']) ){
pu_log_cck("CckRouter:build 32:",$query);          

                $menu = new JTableMenu($db->_db);
                $menu->load($query['Itemid']);
                $menu_params = new JRegistry;
                if($menu->params){
                  $menu_params->loadString($menu->params);
                }  

                if($query['view'] == 'all_instance'){
                    $query['lid'] = $menu_params->get('all_instance_layout');
                    if(!$query['lid']){
                        $menu_params->get('layout');
                    }
                }elseif($query['view'] == 'category'){
                    $query['lid'] = $menu_params->get('category_layout');
                    
                    if(!$query['lid']){
                        $menu_params->get('layout');
                    }
                    $query['catid'] = $menu_params->get('category');
                    // var_dump($menu_params);
                }
            }
            if(isset($query['view']) && $query['view'] == 'category' && !isset($query['catid']) && isset($query['Itemid'])){
pu_log_cck("CckRouter:build 33:",$query);          

                $menu = new JTableMenu($db->_db);
                $menu->load($query['Itemid']);
                $menu_params = new JRegistry;
                if($menu->params){
                  $menu_params->loadString($menu->params);
                }  

                $query['catid'] = $menu_params->get('category');
            }
            
            // var_dump($query);
            // remove 'Itemid' from "vars query" for DB, because start menu items may be many
            $query_tmp = array();
            foreach ($query as $key => $val) {
                if( $key == 'Itemid' ) continue ;
                $query_tmp[$key] = $query[$key];
            }
            $sefurl = new osCckSefurl($db->_db);
            
pu_log_cck("CckRouter:build 40:",$query_tmp);        
            $ser_vars = serialize($query_tmp) ;
            $hash_vars = md5( $ser_vars );
pu_log_cck("CckRouter:build 41:",$hash_vars);        
            $sefurl = $sefurl->loadByHashVars($hash_vars);
pu_log_cck("CckRouter:build 42:",$query);          
            
            if($sefurl != null ) {
            
                //if this url aready created
                foreach ($query as $key => $val) {
                    if( $key == 'option' ) continue ;
                    if( $key == 'Itemid' ) continue ;
                    unset($query[$key]);
                }
                $segments = unserialize( $sefurl->ser_url_segments ) ;
        
            //exit;
pu_log_cck("CckRouter:build 43:",$segments);          

                return $segments;
            } else{
                
pu_log_cck("CckRouter:build 43:",$segments);          

                //if this url not exist
        
                $sefurl = new osCckSefurl($db->_db);
                $sefurl->ser_vars = $ser_vars;
                $sefurl->hash_vars = $hash_vars ;

            
                $s = getWhereUsergroupsConditionCCK("c");

                if($task == 'secret_image') return $segments;
    // pu_log_cck("CckRouter:build 22:".$task."::",$query);             
                if(isset($query['eiid']) && 
                    ( $task == 'instance' || $task == 'parent_child' || $task == 'show_request_layout' || $task == 'displayCckPdf')) {
                    

                    if( $task == 'displayCckPdf' ) {
                        $segments[] = 'pdf';
                    }       
                
                    if(isset($query['catid']) && $query['catid'] > 0){
                        $sql = "SELECT name FROM #__os_cck_categories WHERE cid=" . $query['catid'];
                        $db->setQuery($sql);
                        $cat_name = $db->loadResult();

                        $cat_name = JFilterOutput::stringURLUnicodeSLug($cat_name);
                        $segments[] = $query['catid'] . '-' .$cat_name;
                        unset($query['catid']);
                    }elseif(isset($query['catid'])){
                        unset($query['catid']);
                    }
                    
                    if(isset($query['eiid'])){
                        
                        if(is_array($query['eiid'])){
                            $eiid = $query['eiid'][0];
                        }else{
                            $eiid = $query['eiid'];
                        }
                        
                        if(isset($query['lid'])){
                            $lid = $query['lid'];
                        }

                        $sql = "SELECT fk_eid FROM #__os_cck_layout WHERE lid=".$lid;
                        $db->setQuery($sql);
                        $fk_eid = $db->loadResult();

                        if(!isset($entities_type[$fk_eid])) return array();
                        $entity_type = $entities_type[$fk_eid];
                        
                        if($entity_type == 'os_cck_entity'){
                        
                            $entityInstanse = new os_cckEntityInstance($db->_db);
                            if($eiid > 0){
                                $entityInstanse->load($eiid);
                            }
                        }elseif($entity_type == 'joomla_user'){
                            $entityInstanse = ConvertEntityInstanceToUser($fk_eid, $eiid);
                        }elseif($entity_type == 'custom_sql'){
                            $entity = new os_cckEntity($db->_db);
                            $entity->load($fk_eid);
                            $entityInstanse = ConvertEntityInstanceToCustomSql($entity, $eiid);
                        }
                        //$fk_eid = $entityInstanse->fk_eid;

                        
                        if(isset($lid) && isset($fk_eid)){


                            if($entity_type == 'os_cck_entity'){

                                $value[0] = new stdClass();
                                
                                if($eiid > 0){
                                    $value[0]->data = getInstanceTitle($entityInstanse);
                                }else{
                                    $value[0]->data = '';
                                }
                            }elseif($entity_type == 'joomla_user'){
                                foreach($entityFieldLists[$fk_eid] as $i => $field){
                                    if($field->db_field_name == 'user_standart_name'){
                                        $title_field = $entityFieldLists[$fk_eid][$i];
                                    }
                                }
                                
                                if(isset($title_field)){
                                    $title_field_array = explode('_', $title_field->db_field_name);
                                    
                                    if($title_field_array[1] == 'standart'){
                                        $user = jFactory::getUser($entityInstanse->eiid);
                                        $user_profile_form = '';
                                        $value = $entityInstanse->getFieldValue($title_field, $entity_type, $user_profile_form, $user);
                                    }else{
                                        $user = jFactory::getUser($entityInstanse->eiid);
                                        
                                        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);
                                        $value = $entityInstanse->getFieldValue($title_field, $entity_type, $user_profile_form, $user);
                                    }
                                }
                            }elseif($entity_type == 'custom_sql'){
                                foreach($entityFieldLists[$fk_eid] as $i => $field){
                                    if($field->custom_field_type == 'title'){
                                        $title_field = $entityFieldLists[$fk_eid][$i];
                                    }
                                }
                                // var_dump($field);
                                $value = $entityInstanse->getFieldValue($title_field, $entity_type);
                            }

                            if(isset($value) && $value[0]->data != '') {
                                $segments[] = JFilterOutput::stringURLUnicodeSLug($value[0]->data);
                                $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug($value[0]->data.'-'.$eiid.$lid);
                            }else{
                                $segments[]=$eiid . $lid;
                            }

                        }else{
                            $segments[]=$entityInstanse->eiid;
                        }
                    }
                } 

                if(isset($query['catid']) && $task == 'category') {
                    if(isset($query['catid']) && isset($query['lid'])){
                        $sql = "SELECT name FROM #__os_cck_categories WHERE cid=" . intval($query['catid']);
                        $db->setQuery($sql);
                        $cat_name = $db->loadResult();

                        $cat_name = JFilterOutput::stringURLUnicodeSLug($cat_name);
                        $segments[] = $cat_name;
                        $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug($cat_name.'-'.$query['catid'].$query['lid']);
                    }
                }

                if($task == 'all_categories') {
                    unset($query['view']);

                }    
                if($task == 'show_search') {
                    if(isset($query['lid'])){
                        $segments[] = JFilterOutput::stringURLUnicodeSLug('show_search');
                        $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug('show_search'.'-'.$query['lid']);
                    }
                }    

                if($task == 'search') {
                    //search always not same, add hash for pagenator
                    $segments[] = JFilterOutput::stringURLUnicodeSLug('search'.'-'.$hash_vars);
                    $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug('search'.'-'.$hash_vars);

                    //remove "start" for search URL (we added uniq hash)
                    if( isset( $query['limitstart'] ) ) unset( $query['limitstart'] );
                    if( isset( $query['start'] ) ) unset( $query['start'] );
                }

                if($task == 'all_instance') {
                    if(isset($query['lid'])){
                        $segments[] = JFilterOutput::stringURLUnicodeSLug('all_instance');
                        $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug('all_instance'.'-'.$query['lid']);
                    }
                    if(isset($query['event_date'])){
                        // var_dump($query['event_date']);
                        $segments[] = JFilterOutput::stringURLUnicodeSLug($query['event_date']);
                        $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug($query['event_date']);
                    }
                }  

                if($task == 'cart') {
                    if(isset($query['lid'])){
                        $segments[] = JFilterOutput::stringURLUnicodeSLug('cart');
                        $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug('cart'.'-'.$query['lid']);
                    }

                }  

                if(isset($query['userId']) && $task == 'user_instances') {
                    if(isset($query['userId']) && isset($query['lid'])){
                        $sql = "SELECT name FROM #__users WHERE id=" . intval($query['userId']);
                        $db->setQuery($sql);
                        $user_name = $db->loadResult();

                        $user_name = JFilterOutput::stringURLUnicodeSLug($user_name);
                        $segments[] = $user_name;
                        $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug($user_name.'-'.$query['userId'].$query['lid']);
                        unset($query['userId']);
                    }
                }
            
                if (isset($query['start'])) {
                    //if(count($segments) == 0 ) $segments[] = $task;
                    $segments[] = JFilterOutput::stringURLUnicodeSLug("s_".$query['start']);
                    $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug("s_".$query['start']);
                    unset( $query['start'] );
                } else if (isset($query['limitstart'])) {
                    //if(count($segments) == 0 ) $segments[] = $task;
                    $segments[] = JFilterOutput::stringURLUnicodeSLug("s_".$query['limitstart']);
                    $segments_with_id[] = JFilterOutput::stringURLUnicodeSLug("s_".$query['limitstart']);
                    unset($query['limitstart']);
                }

                
                // unset($query['id']);
                // unset($query['layout']);
                // unset($query['is_show_data']);
                // unset($query['tab']);
                // if(isset($query['catid'])) unset($query['catid']);
                // if(isset($query['lid'])) unset($query['lid']);
                // if(isset($query['view'])) unset($query['view']);
                // if(isset($query['task'])) unset($query['task']);
                // if(isset($query['Itemid'])) unset($query['Itemid']);
                // if(isset($query['price_fields'])) unset($query['price_fields']);
                // if(isset($query['language'])) unset($query['language']);
                // if(isset($query['eiid'])) unset($query['eiid']);
                // if(isset($query['userId'])) unset($query['userId']);
                // if(isset($query['event_date'])) unset($query['event_date']);
                // if(isset($query['event_date_field'])) unset($query['event_date_field']);
                //if this url aready created
                foreach ($query as $key => $val) {
                    if( $key == 'option' ) continue ;
                    if( $key == 'Itemid' ) continue ;
                    unset($query[$key]);
                }                

                $sefurl->ser_url_segments = serialize($segments);
                $sefurl->hash_url_segments = md5( $sefurl->ser_url_segments ) ;

                $sefurl_new = new osCckSefurl($db->_db);
                $sefurl_new = $sefurl_new->loadByHashUrlSegments($sefurl->hash_url_segments);

                if($sefurl_new != null 
                    && count($segments_with_id) > 0 
                    && $sefurl->hash_vars == $sefurl_new->hash_vars ) {
                    //this mean exist some duplecate with same url, so add to URL the ID
                    //$sefurl->hash_vars == $sefurl_new->hash_vars - mean all vars 
                    // in url same(not only in segment)
                    $sefurl->ser_url_segments = serialize($segments_with_id);
                    $sefurl->hash_url_segments = md5( $sefurl->ser_url_segments ) ;
                    $segments = $segments_with_id;

                    $sefurl_new = $sefurl_new->loadByHashUrlSegments($sefurl->hash_url_segments);  
                    if($sefurl_new != null ){
                        //this url exist, so add to URL the some hash code
                        $segments[] = $sefurl->hash_vars;
                        $sefurl->ser_url_segments = serialize($segments);
                        $sefurl->hash_url_segments = md5( $sefurl->ser_url_segments ) ;
                    }                     
                }else if($sefurl_new != null 
                    && count($segments_with_id) == 0 
                    && $sefurl->hash_vars == $sefurl_new->hash_vars  ) {
                    //this mean exist some duplecate with same url, 
                    //$sefurl->hash_vars == $sefurl_new->hash_vars - mean all vars 
                    // in url same(not only in segment)
                    //so add to URL the some hash code
                    //need additional check for SEaRCH tasks, 
                    //so task may check with date and hint, and remove all old 1 month
                    //this condition must not happened, other some error  !!!!
                    $hash = md5( serialize($query) ) ;
                    $segments[] = $hash;
                    $sefurl->ser_url_segments = serialize($segments);
                    $sefurl->hash_url_segments = md5( $sefurl->ser_url_segments ) ;
                }else if($sefurl_new != null 
                    && count($segments_with_id) > 0 
                    && $sefurl->hash_vars != $sefurl_new->hash_vars ) {
                    //this mean exist some duplecate with same url, 
                    //$sefurl->hash_vars != $sefurl_new->hash_vars - mean all vars 
                    // in url NOT same(not only in segment)(may be exist other item with same name)
                    $sefurl->ser_url_segments = serialize($segments_with_id);
                    $sefurl->hash_url_segments = md5( $sefurl->ser_url_segments ) ;
                    $segments = $segments_with_id;

                    $sefurl_new = $sefurl_new->loadByHashUrlSegments($sefurl->hash_url_segments);  
                    if($sefurl_new != null ){
                        //this url exist, so add to URL the some hash code
                        $segments[] = $sefurl->hash_vars;
                        $sefurl->ser_url_segments = serialize($segments);
                        $sefurl->hash_url_segments = md5( $sefurl->ser_url_segments ) ;
                    } 
                      
                }else if( !isset($sefurl_new) ) {
                    ;//all good, this new SEF url
                } elseif($sefurl_new != null 
                    && $sefurl->hash_vars != $sefurl_new->hash_vars 
                    && count($segments_with_id) == 0  
                ) {
                    //this url exist, so add to URL the some hash code
                    $segments[] = $sefurl->hash_vars;
                    $sefurl->ser_url_segments = serialize($segments);
                    $sefurl->hash_url_segments = md5( $sefurl->ser_url_segments ) ;
                }

                $sefurl->store();

  pu_log_cck("CckRouter:build 5:",$segments);          
              return $segments;

            }
        }else{


            $segments = array();
            $session = JFactory::getSession();
            $db = new os_cckDb();
            // var_dump($query);
    //                var_dump($query);
            if(isset($query['task'])){
                $query['view'] = $query['task'];
            }
            
            if(isset($query['view'])){
                switch($query['view']){
                case "instance":
                case "parent_child":
                case "show_request_layout":
                    
                    if(isset($query['catid']) && $query['catid'] > 0){
                        $sql = "SELECT name FROM #__os_cck_categories WHERE cid=" . $query['catid'];
                        $db->setQuery($sql);
                        $cat_name = $db->loadResult();

                        $cat_name = JFilterOutput::stringURLUnicodeSLug(str_replace(' ', '_', $cat_name));
                        $segments[] = $query['catid'] . '-' .$cat_name;
                        unset($query['catid']);
                    }elseif(isset($query['catid'])){
                        unset($query['catid']);
                    }
                    
                    if(isset($query['eiid'])){
                        
                        if(is_array($query['eiid'])){
                            $eiid = $query['eiid'][0];
                        }else{
                            $eiid = $query['eiid'];
                        }
                        
                        if(isset($query['lid'])){
                            $lid = $query['lid'];
                        }
                        
    
                        $sql = "SELECT fk_eid FROM #__os_cck_layout WHERE lid=".$lid;
                        $db->setQuery($sql);
                        $fk_eid = $db->loadResult();
                        
                        if(!isset($entities_type[$fk_eid])) return array();
                        $entity_type = $entities_type[$fk_eid];
                        
                        if($entity_type == 'os_cck_entity'){
                            
                                $entityInstanse = new os_cckEntityInstance($db->_db);
                                if($eiid > 0){
                                    $entityInstanse->load($eiid);
                                }
                        }elseif($entity_type == 'joomla_user'){
                            $entityInstanse = ConvertEntityInstanceToUser($fk_eid, $eiid);
                        }
                        //$fk_eid = $entityInstanse->fk_eid;

                        
                        if(isset($lid) && isset($fk_eid)){

                            //get params
                            $sql = "SELECT params FROM #__os_cck_layout
                                    \nWHERE lid =".intval($lid);

                            $db->setQuery($sql);
                            $params = $db->loadResult();
                            $params = unserialize($params);


                            //search Title field if exists
    //                          for($i=0;$i<count($entityFieldLists[$fk_eid]);$i++){
                            foreach($entityFieldLists[$fk_eid] as $i => $field){
                                if(isset($params['fields'][$entityFieldLists[$fk_eid][$i]->db_field_name.'_title_field']) && $params['fields'][$entityFieldLists[$fk_eid][$i]->db_field_name.'_title_field'] == 1){
    //                                $title_field = $entityFieldLists[$fk_eid][$i]->db_field_name;
                                    $title_field = $entityFieldLists[$fk_eid][$i];
                                }
                            }
                            //var_dump($entityInstanse);
                            // var_dump($title_field);
    //                          if(empty($title_field)){
    //                            
    //                          }else{
                                if($entity_type == 'os_cck_entity'){
    //                                  $value = $entityInstanse->getFieldValue($title_field);
                                    $value[0] = new stdClass();
                                    
                                    if($eiid > 0){
                                        $value[0]->data = getInstanceTitle($entityInstanse);
                                    }else{
                                        $value[0]->data = '';
                                    }
                                }elseif($entity_type == 'joomla_user'){
                                    foreach($entityFieldLists[$fk_eid] as $i => $field){
                                        if($field->db_field_name == 'user_standart_name'){
                                            $title_field = $entityFieldLists[$fk_eid][$i];
                                        }
                                    }
                                    
                                    if(isset($title_field)){
                                        $title_field_array = explode('_', $title_field->db_field_name);
                                        
                                        if($title_field_array[1] == 'standart'){
                                            $user = jFactory::getUser($entityInstanse->eiid);
                                            $user_profile_form = '';
                                            $value = $entityInstanse->getFieldValue($title_field, $entity_type, $user_profile_form, $user);
                                        }else{
                                            $user = jFactory::getUser($entityInstanse->eiid);
                                            
                                            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);
                                            $value = $entityInstanse->getFieldValue($title_field, $entity_type, $user_profile_form, $user);
                                        }
                                    }
                                }

                                if(isset($value) && $value[0]->data != '') {
                                $segments[] = JFilterOutput::stringURLUnicodeSLug(str_replace(array(' ', ':'), '_', $value[0]->data)). ':'. $entityInstanse->eiid . ':' . $lid;
                                unset($query['eiid']);
                                }else{
                                    $segments[]=$eiid . ':' . $lid;
                                    unset($query['eiid']);
                                }
    //                          }
                            }else{
                            $segments[]=$entityInstanse->eiid;
                            unset($query['eiid']);
                            }

                            unset($query['lid']);
                    }
                    //var_dump($segments);
                    unset($query['view']);
                    if(isset($query['task'])){
                        unset($query['task']);
                    }
                    if(isset($query['price_fields'])){
                        $session->set('price_fields', $query['price_fields']);
                        unset($query['price_fields']);
                    }
                    if(isset($query['language'])){
                        unset($query['language']);
                    }
                    
                break;

                case "category":
                    if(isset($query['catid']) && isset($query['lid'])){
                        $sql = "SELECT name FROM #__os_cck_categories WHERE cid=" . intval($query['catid']);
                        $db->setQuery($sql);
                        $cat_name = $db->loadResult();

                        $cat_name = JFilterOutput::stringURLUnicodeSLug(str_replace(array(' ', ':'), '_', $cat_name));
                        $segments[] = $query['lid'] . ':' . $query['catid'] . ':' .$cat_name;
                        unset($query['catid']);
                        unset($query['view']);
                        unset($query['lid']);
                        unset($query['task']);
                    }
                    break;
                case "all_categories":
                    unset($query['view']);
                    break;
                case "show_search":
                    if(isset($query['lid'])){
                        $segments[] = 'show_search:' . $query['lid'];
                    }
                    if(isset($query['view'])){
                        unset($query['view']);
                    }
                    if(isset($query['lid'])){
                        unset($query['lid']);
                    }
                    if(isset($query['task'])){
                        unset($query['task']);
                    }
                    break;
                case "search":
                    
                    $segments[] = 'search:' . $query['lid'];
                    unset($query['view']);
                    unset($query['lid']);
                    unset($query['task']);
                    //unset($query['option']);
                    break;
                case "all_instance":
                    if(isset($query['lid'])){
                        $segments[] = 'all_instance:' . $query['lid'];
                    }
                    unset($query['view']);
                    unset($query['task']);
                    if(isset($query['lid'])){
                        unset($query['lid']);
                    }
                    break;
                case "cart":
                    if(isset($query['lid'])){
                        $segments[] = 'cart:' . $query['lid'];
                    }
                    if(isset($query['view'])){
                        unset($query['view']);
                    }
                    if(isset($query['lid'])){
                        unset($query['lid']);
                    }
                    if(isset($query['task'])){
                        unset($query['task']);
                    }
                    break;

                }
                unset($query['view']);
            }
    //           foreach ($segments as $key => $value) {
    //             $segments[$key] = str_replace("'", "", $value);
    //           }
    //        var_dump($query);
    // var_dump($segments);
 pu_log_cck("CckRouter:build 6:",$segments);          
           return $segments;
        }
    }
    
    public function parse(&$segments)
    {
        $os_cck_configuration = JComponentHelper::getParams('com_os_cck');
     pu_log_cck("CckRouter:parse 1:",$segments);            
        
        // var_dump($segments); exit;
        if($os_cck_configuration->get('sef_url' , '1') == '1'){

            $vars = array();
            $db = new os_cckDb();

            $sefurl = new osCckSefurl($db->_db);
            $ser_segments = serialize($segments) ;
            $hash_segments = md5( $ser_segments );
            $sefurl = $sefurl->loadByHashUrlSegments($hash_segments);
//             var_dump($sefurl); exit;
            if($sefurl != null ) {
                foreach ($segments as $key => $value) {
                    unset($segments[$key]);
                }

                $vars = unserialize( $sefurl->ser_vars ) ;
//                var_dump($vars);
                if(isset($vars['start'])){
                    $vars['limitstart'] = $vars['start'];
                }
     pu_log_cck("CckRouter:parse 2:",$vars);            
                return $vars;
            }else{
     pu_log_cck("CckRouter:parse 3:",$vars);            
                return $vars;
            }
        }else{
        
            $vars = array();
            $db = new os_cckDb();
            $vars['option'] = 'com_os_cck';
            $app    = JFactory::getApplication();
            $menu   = $app->getMenu();
            $count = count($segments);
            $parse_var = $segments[$count-1];
            $parse_var_arr = array_reverse(explode(':', $parse_var));
            //$lid = substr($parse_var, strripos($parse_var, ':')+1);
            $lid = $parse_var_arr[0];
    //          var_dump($lid); exit;
            if(intval($lid) == 0){
                $lid = substr($parse_var, 0, stripos($parse_var, ':'));
            }elseif(preg_match('/\D/', $lid) == 1){
                $lid = substr($parse_var, strripos($parse_var, ':')+1);
                $non_title = true;
            }
    //         var_dump($lid); exit;
            //var_dump(preg_match('/[\D:]+/', $parse_var));
            if(preg_match('/[a-zA-Z]+/', $parse_var) == 0){
                $non_title = true;
            }
            

            $layout = new os_cckLayout($db->_db);
            $layout->load($lid);
    //         var_dump($layout); exit;
            
            if($layout->type == 'instance' || $layout->type == 'parent_child'
                    || $layout->type == 'request_instance' || $layout->type == 'review_instance'|| $layout->type == 'buy_request_instance'){
                $vars['view'] = $layout->type;
                if($layout->type == 'request_instance' || $layout->type == 'review_instance' || $layout->type == 'buy_request_instance'){
                    $vars['view'] = 'show_request_layout';
                }
    //             $end_crop = strlen($parse_var) - strripos($parse_var, ':') - 1;
    //             $vars['eiid'] = substr($parse_var, stripos($parse_var, ':')+1, $end_crop);
                $end_crop = strlen($parse_var) - strripos($parse_var, ':');
                $substring = substr($parse_var, stripos($parse_var, ':')+1);
                $vars['eiid'] = $parse_var_arr[1];
                if(intval($vars['eiid']) == 0){
                $vars['eiid'] = substr($substring, 0, stripos($substring, ':'));
                if(isset($non_title) && $non_title == true){
                    $vars['eiid'] = substr($parse_var, 0, stripos($parse_var, ':'));
                }
                }
                $vars['lid']   = $lid;

            }elseif ($layout->type == 'category') {
                $vars['view'] = $layout->type;
                $end_crop = stripos($parse_var, '-') - stripos($parse_var, ':')-1;
                
                $vars['catid'] = intval(substr($parse_var, stripos($parse_var, ':')+1, $end_crop));
    //             var_dump(intval($vars['catid']));
                $vars['lid']   = $lid;

            }elseif ($layout->type == 'search' && $parse_var_arr[1] != 'search') {
                // echo '11111111111111111111';
                $vars['view'] = 'show_search';
                $vars['task'] = 'show_search';
                $vars['lid']   = $lid;
            }elseif ($layout->type == 'search' && $parse_var_arr[1] == 'search') {
                // echo '11111111111111111111';
                $vars['view'] = 'search';
                $vars['task'] = 'search';
                $vars['lid']   = $lid;
            }elseif ($layout->type == 'cart') {
                $vars['view'] = 'cart';
                $vars['task'] = 'cart';
                $vars['lid']   = $lid;
            }elseif($layout->type == 'all_instance'){
                $vars['view'] = 'all_instance';
                $vars['task'] = 'all_instance';
                $vars['lid']   = $lid;
            }
            foreach ($segments as $key => $value) {
                unset($segments[$key]);
            }
        //    var_dump($vars); exit;
     pu_log_cck("CckRouter:parse 4:",$vars);            

            return $vars;
        }
    }
}


function os_cckBuildRoute(&$query) {
//echo"1111111start os_cckBuildRoute";
//print_r($query);echo"<br>";
//    
    $app = JFactory::getApplication();
    $router = new Os_cckRouter($app, $app->getMenu());

    return $router->build($query);

//echo ":111111 end os_cckBuildRoute";
//print_r($query);echo"<br>";

//    return $segments;
}

/**
 * Parse the segments of a URL.
 *
 */
function COM_OS_CCKParseRoute($segments) {
//echo"22222 start os_cckParseRoute";
// print_r($segments);echo"<br>";
//    
    $app = JFactory::getApplication();
    $router = new Os_cckRouter($app, $app->getMenu());
//echo"22222 start os_cckParseRoute";
//print_r($query);echo"<br>";
//exit;
    return $router->parse($segments);
     

//    return $vars;
}
