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

abstract class OSCCKHelperRoute{

  protected static $lookup = array();

  protected static $lang_lookup = array();

  public static function getCCKAssocPropertyRoute($id, $lid){

    $database = JFactory::getDBO();


    $link = array();
    $instanceIdArr = array();
    $associate_instance = array();
    if( isset($id) ){
        $query = "SELECT associate_instances FROM #__os_cck_entity_instance WHERE eiid = $id";
        $database->setQuery($query);
        $associate_cck = $database->loadResult();

        if($associate_cck != "" ) $associate_instance = unserialize($associate_cck);

        if(count($associate_instance) > 0){
            foreach($associate_instance as $oneInstance){
                if($oneInstance != 0 && $oneInstance != ''){
                    $instanceIdArr[] = $oneInstance;
                }
            }

            $instanceIdStr = implode(',', $instanceIdArr);
            if($instanceIdStr == '') return $link;
            $query = "SELECT eiid, language
                        FROM #__os_cck_entity_instance
                        WHERE eiid in ( $instanceIdStr )";
            $database->setQuery($query);
            $assocInstance = $database->loadAssocList();
            
            $query = "SELECT associate_layout FROM #__os_cck_layout WHERE lid=$lid";
            $database->setQuery($query);
            $assocLayout = $database->loadResult();
            
            if($assocLayout != '' && $assocLayout != null){
                $assocLayout = unserialize($assocLayout);
            }

            foreach ($assocInstance as $value) {
                $lang = $value['language'];
                $CurId = $value['eiid'];
                
                if(isset($assocInstance)){
                    $query = "SELECT fk_cid
                                  FROM #__os_cck_categories_connect
                                  WHERE fk_eiid = $CurId";
//                    var_dump($query); exit;
                    $database->setQuery($query);
                    $assocInstanceCat = $database->loadResult();
                }
                if(isset($assocLayout[$lang])){
                    $lid = $assocLayout[$lang];
                }
                
                $link[$lang] = "index.php?option=com_os_cck&task=instance&lid=$lid&catid=$assocInstanceCat&eiid=$CurId";

                $needles = array();
                $needles['view'] = 'view';
                $app = JFactory::getApplication();
                $menus    = $app->getMenu('site');
                if(isset($menus)){
                  $active = $menus->getActive();
                  if(isset($active)){
                    $needles[$active->query['view']] = $active->query['view'];
                  }
                }

                if ( $lang != "*" && JLanguageMultilang::isEnabled())
                {
                  self::buildLanguageLookup();

                  if (isset(self::$lang_lookup[$lang]))
                  {
                    $link[$lang] .= '&lang=' . self::$lang_lookup[$lang];
                    $needles['language'] = $lang;
                  }
                }

                if ($item = self::_findItem($needles))
                {

                  $link[$lang] .= '&Itemid=' . $item;
                }


            }
        }
    }

    return $link;
  }

  public static function getCCKAssocCategoryRoute($catid, $lid){

    $database = JFactory::getDBO();
    $link = array();
    $assos_ids = array();

    if(isset($catid) ){
      $catIdArr = array();

      $query = "SELECT associate_category FROM #__os_cck_categories WHERE cid = $catid";
      $database->setQuery($query);
      $ids = $database->loadResult();

      if($ids != "" ) $assos_ids = unserialize($ids);


      if(count($assos_ids) > 0){
          foreach($assos_ids as $oneCat){
              if($oneCat != 0){
                  $catIdArr[] = $oneCat;
              }
          }

          $catIdStr = implode(',', $catIdArr);
          $query = "SELECT cid, language
                      FROM #__os_cck_categories
                       WHERE cid in ($catIdStr)";
          $database->setQuery($query);
          $assocCategory = $database->loadAssocList();
          
          $query = "SELECT associate_layout FROM #__os_cck_layout WHERE lid=$lid";
            $database->setQuery($query);
            $assocLayout = $database->loadResult();
            
            if($assocLayout != '' && $assocLayout != null){
                $assocLayout = unserialize($assocLayout);
            }

          foreach ($assocCategory as $value) {
              $lang = $value['language'];
              $CurId = $value['cid'];
              
              if(isset($assocLayout[$lang])){
                  $lid = $assocLayout[$lang];
              }

              $link[$lang] = "index.php?option=com_os_cck&task=category&catid=$CurId&lid=$lid";

              $needles = array();
              $needles['category'] = 'category';
              $app    = JFactory::getApplication();
              $menus    = $app->getMenu('site');
              $active = $menus->getActive();
              $needles[$active->query['view']] = $active->query['view'];

              if ( $lang != "*" && JLanguageMultilang::isEnabled())
              {
                self::buildLanguageLookup();

                if (isset(self::$lang_lookup[$lang]))
                {
                  $link[$lang] .= '&lang=' . self::$lang_lookup[$lang];
                  $needles['language'] = $lang;
                }
              }

              if ($item = self::_findItem($needles))
              {
                $link[$lang] .= '&Itemid=' . $item;
              }
          }
      }
    }
    return $link;
  }
  
  public static function getCCKAssocParentChildRoute($id, $lid){

    $database = JFactory::getDBO();
    $link = array();
    $associate_instance = array();
    if( isset($id) ){
        $query = "SELECT associate_instances FROM #__os_cck_entity_instance WHERE eiid = $id";
        $database->setQuery($query);
        $associate_cck = $database->loadResult();

        if($associate_cck != "" ) $associate_instance = unserialize($associate_cck);

        if(count($associate_instance) > 0){
            foreach($associate_instance as $oneInstance){
                if($oneInstance != 0){
                    $instanceIdArr[] = $oneInstance;
                }
            }

            $instanceIdStr = implode(',', $instanceIdArr);
            $query = "SELECT eiid, language
                        FROM #__os_cck_entity_instance
                        WHERE eiid in ( $instanceIdStr )";
            $database->setQuery($query);
            $assocInstance = $database->loadAssocList();
            
            $query = "SELECT associate_layout FROM #__os_cck_layout WHERE lid=$lid";
            $database->setQuery($query);
            $assocLayout = $database->loadResult();
            
            if($assocLayout != '' && $assocLayout != null){
                $assocLayout = unserialize($assocLayout);
            }

            foreach ($assocInstance as $value) {
                $lang = $value['language'];
                $CurId = $value['eiid'];
                
                
                if(isset($assocLayout[$lang])){
                    $lid = $assocLayout[$lang];
                }
                
                $link[$lang] = "index.php?option=com_os_cck&task=parent_child&lid=$lid&eiid=$CurId";

                $needles = array();
                $needles['view'] = 'view';
                $app = JFactory::getApplication();
                $menus    = $app->getMenu('site');
                if(isset($menus)){
                  $active = $menus->getActive();
                  if(isset($active)){
                    $needles[$active->query['view']] = $active->query['view'];
                  }
                }

                if ( $lang != "*" && JLanguageMultilang::isEnabled())
                {
                  self::buildLanguageLookup();

                  if (isset(self::$lang_lookup[$lang]))
                  {
                    $link[$lang] .= '&lang=' . self::$lang_lookup[$lang];
                    $needles['language'] = $lang;
                  }
                }

                if ($item = self::_findItem($needles))
                {

                  $link[$lang] .= '&Itemid=' . $item;
                }


            }
        }
    }
    return $link;
  }

  public static function getCCKAssocCartRoute($lid){

    $database = JFactory::getDBO();
    $link = array();
    $associate_instance = array();
    
                        
            $query = "SELECT associate_layout FROM #__os_cck_layout WHERE lid=$lid";
            $database->setQuery($query);
            $assocLayout = $database->loadResult();
            
            if($assocLayout != '' && $assocLayout != null){
                $assocLayout = unserialize($assocLayout);
            }
            // var_dump($assocLayout); exit;
            foreach ($assocLayout as $lang => $value) {
                
                $lid = $value;
                
                
                     // JRoute::_('index.php?option=com_os_cck&amp;view=cart&amp;lid='.$layout->lid.'&amp;Itemid='.$itemId)         
                $link[$lang] = "index.php?option=com_os_cck&view=cart&lid=$lid";

                $needles = array();
                $needles['view'] = 'view';
                $app = JFactory::getApplication();
                $menus    = $app->getMenu('site');
                if(isset($menus)){
                  $active = $menus->getActive();
                  if(isset($active)){
                    $needles[$active->query['view']] = $active->query['view'];
                  }
                }

                if ( $lang != "*" && JLanguageMultilang::isEnabled())
                {
                  self::buildLanguageLookup();

                  if (isset(self::$lang_lookup[$lang]))
                  {
                    $link[$lang] .= '&lang=' . self::$lang_lookup[$lang];
                    $needles['language'] = $lang;
                  }
                }

                $link[$lang] .= '&Itemid=' . $app->input->get('Itemid');


            }
        
    
    return $link;
  }
  
  

  protected static function buildLanguageLookup()
  {

    if (count(self::$lang_lookup) == 0)
    {
      $db    = JFactory::getDbo();
      $query = $db->getQuery(true)
        ->select('a.sef AS sef')
        ->select('a.lang_code AS lang_code')
        ->from('#__languages AS a');

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

      foreach ($langs as $lang)
      {
        self::$lang_lookup[$lang->lang_code] = $lang->sef;
      }
    }
  }


  protected static function _findItem($needles = null)
  {



    $app      = JFactory::getApplication();
    $menus    = $app->getMenu('site');
    $language = isset($needles['language']) ? $needles['language'] : '*';

    $active = $menus->getActive();

    
    //get associated menus 
    if(JLanguageAssociations::isEnabled() ) {
      $menu_associations = JLanguageAssociations::getAssociations('com_menu', '#__menu', 'com_menus.item', $active->id , 'id','','') ;
//      print_r($menu_associations[$language]);

      if($language != "" && $language != "*" &&  array_key_exists($language, $menu_associations) )
       return $menu_associations[$language]->id ;
    } 

    // Prepare the reverse lookup array.
    if (!isset(self::$lookup[$language]))
    {
      self::$lookup[$language] = array();

      $component  = JComponentHelper::getComponent('com_os_cck');

      $attributes = array('component_id');
      $values     = array($component->id);

      if ($language != '*')
      {
        $attributes[] = 'language';
        $values[]     = array($needles['language'], '*');
      }

      $items = $menus->getItems($attributes, $values);

      foreach ($items as $item)
      {
        if (isset($item->query) && (isset($item->query['view']) || isset($item->query['task'] ) ) )
        {
          if ( isset($item->query['view'] ) )  $view = $item->query['view'];
          else $view = $item->query['task'];

          if (!isset(self::$lookup[$language][$view]))
          {
            self::$lookup[$language][$view] = array();
          }

          if (isset($item->id))
          {
            /**
             * Here it will become a bit tricky
             * language != * can override existing entries
             * language == * cannot override existing entries
             */
            if (!isset(self::$lookup[$language][$view][$item->id]) || $item->language != '*')
            {
              self::$lookup[$language][$view][$item->id] = $item->id;
            }
          }
        }
      }
    }

    //check item with exectly view
    if ($needles)
    {

      foreach ($needles as $view => $ids)
      {
        if (isset(self::$lookup[$language][$view]))
        {

          foreach (self::$lookup[$language][$view] as $id)
          {

            if (isset(self::$lookup[$language][$view][(int) $id]))
            {
              return self::$lookup[$language][$view][(int) $id];
            }
          }
        }
      }
    }


    //check any item from our component
    if ($needles)
    {

      foreach (self::$lookup[$language] as $view => $ids)
      {
        if (isset(self::$lookup[$language][$view]))
        {

          foreach (self::$lookup[$language][$view] as $id)
          {

            if (isset(self::$lookup[$language][$view][(int) $id]))
            {
              return self::$lookup[$language][$view][(int) $id];
            }
          }
        }
      }
    }


    // Check if the active menuitem matches the requested language
    $active = $menus->getActive();

    if ($active && $active->component == 'com_os_cck' &&
      ($language == '*' || in_array($active->language, array('*', $language)) || !JLanguageMultilang::isEnabled()))
    {
      return $active->id;
    }

    // If not found, return language specific home link
    $default = $menus->getDefault($language);

    return !empty($default->id) ? $default->id : null;
  }


}