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

/**
 *
 * @package  MediaLibrary
 * @copyright 2021 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com);
 * Homepage: https://ordasoft.com
 * @version: 4.6 Free
 * @license GNU General Public license version 2 or later; see LICENSE.txt
 *
 */

abstract class MedialibraryHelperRoute {
    protected static $lookup = array();
    protected static $lang_lookup = array();
    public static function getMediaAssocRoute($id, $task, $itemId) {
        $itemId_main = $itemId;

        $database = JFactory::getDBO();
        $link = array();
        $mediaIdArr = array();
        $associate_media = array();

        $arr_params =  array() ;
        $arr_params['task'] = $task;
        $arr_params['id'] = $id;
        $link_params = MediaLibraryHelperRoute::getMLOtherRoute($arr_params, $itemId);

        if (isset($id) ) {
            $query = "SELECT associate_media FROM #__medialibrary WHERE id = $id";
            $database->setQuery($query);
            $associate_ml = $database->loadResult();
            if ($associate_ml != "") $associate_media = unserialize($associate_ml);
            if (count($associate_media) > 0) {
                foreach($associate_media as $oneMedia) {
                    if ($oneMedia != 0) {
                        $mediaIdArr[] = $oneMedia;
                    }
                }
                $mediaIdArr = implode(',', $mediaIdArr);
                $query = "SELECT id,langDescription
                          FROM #__medialibrary
                          WHERE id in ( $mediaIdArr )";
                $database->setQuery($query);
                $assocMedia = $database->loadAssocList();
                foreach($assocMedia as $value) {
                    $lang = $value['langDescription'];
                    $CurId = $value['id'];
                    if (isset($assocMedia)) {
                        $query = "SELECT catid
                                  FROM #__medialibrary_categories
                                  WHERE mediaid = $CurId";
                        $database->setQuery($query);
                        $assocMediaCat = $database->loadResult();
                    }
                    $link[$lang] = "index.php?option=com_medialibrary&task=view&catid=$assocMediaCat"
                                ."&id=$CurId";
                    $needles = array();
                    $needles['view'] = 'view';
                    $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, $itemId)) {
                        $link[$lang].= '&Itemid=' . $item;
                    }
                    // print_r($item);
                }
            } 
            
        }
        foreach ($link_params as $key => $value) {
            if (!array_key_exists($key, $link)) {
                $link[$key] = $value;
            }
        }

        return $link;
    }

    public static function getMediaCategoryRoute($catid, $itemId, $task) {
        $database = JFactory::getDBO();
        $link = array();
        $assos_ids = array();

        $arr_params =  array() ;
        $arr_params['task'] = $task;
        $arr_params['catid'] = $catid ;
        $link_params = MediaLibraryHelperRoute::getMLOtherRoute($arr_params, 0);

        if (isset($catid)) {
            $catIdArr = array();
            $query = "SELECT associate_category FROM #__medialibrary_main_categories WHERE id = $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 id,langDescription
                          FROM #__medialibrary_main_categories
                          WHERE id in ($catIdStr)";
                $database->setQuery($query);
                $assocCategory = $database->loadAssocList();
                foreach($assocCategory as $value) {
                    $lang = $value['langDescription'];
                    $CurId = $value['id'];
                    $link[$lang] = "index.php?option=com_medialibrary&task=alonecategory&catid=$CurId";
                    $needles['alonecategory'] = 'alonecategory';
                    $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;
                    }
                }
            }
        }
        foreach ($link_params as $key => $value) {
            if (!array_key_exists($key, $link)) {
                $link[$key] = $value;
            }
        }

        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;
            }
        }
    }

    public static function getMLOtherRoute ($arr_params, $itemId) { 
        $layout = '';
        $link = array();
        $needles = array();
        foreach ($arr_params as $key => $value) {
          $needles[$key] = $value;
        }
        self::buildLanguageLookup();
        foreach(self::$lang_lookup AS $lang =>$lang_value ){
            $link[$lang] = "index.php?option=com_medialibrary" ;
            foreach ($arr_params as $key => $value) {
                  $link[$lang] .= "&".$key ."=".$value;
            }
            if ( JLanguageMultilang::isEnabled()) {
                if (isset(self::$lang_lookup[$lang])) {
                    $link[$lang].= '&lang=' . self::$lang_lookup[$lang];
                    $needles['language'] = $lang;
                }
            }
            if ($item = self::_findItem($needles, $itemId, $layout)) {
                 $link[$lang].= '&Itemid=' . $item;
            }            
        }
        if ($layout != ''){
            $link = array();
            $needles = array();
            foreach ($arr_params as $key => $value) {
              $needles[$key] = $value;
            }
            self::buildLanguageLookup();
            foreach(self::$lang_lookup AS $lang =>$lang_value ){
                $link[$lang] = "index.php?option=com_medialibrary" ;
                foreach ($arr_params as $key => $value) {
                      $link[$lang] .= "&".$key ."=".$value;
                }
                if ( JLanguageMultilang::isEnabled()) {
                    if (isset(self::$lang_lookup[$lang])) {
                        $link[$lang].= '&lang=' . self::$lang_lookup[$lang];
                        $needles['language'] = $lang;
                    }
                }
                if ($item = self::_findItem($needles, $itemId, $layout)) {
                     $link[$lang].= '&Itemid=' . $item;
                }            
            }
        }
        return $link;
    }

    protected static function _findItem($needles = null, $itemId = 0, &$layout = ''){

    $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','','') ;

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


    $task = isset($needles['task']) ? $needles['task'] : '';
    if (!isset(self::$lookup[$language])){
      self::$lookup[$language] = array();

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

      $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 ($item->id == $itemId){
            $layout = $item->params[$view];
            self::$lookup['layuot'] = $layout;
          } 
          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 != '*')
            {

                if ($item->params[$view]!= ''){
                    self::$lookup[$language][$view][$item->params[$view]] = $item->id;
                } else {
                    self::$lookup[$language][$view][$view] = $item->id;
                }
              //   print_r('<br>');
              // self::$lookup[$language][$view][$item->id] = $item->id;
            }
          }
        }
      }
    } else {
        if (isset(self::$lookup['layuot'])){
            $layout = self::$lookup['layuot'];
        }
    }
    if (!isset(self::$lookup['layuot'])){
        $layout = '';
    }
    //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][$layout][(int) $id])) {
              return self::$lookup[$language][$view][$layout][(int) $id];
            }else if (isset(self::$lookup[$language][$view][(int) $id])){
              return self::$lookup[$language][$view][$view][(int) $id];
            }else if (isset(self::$lookup[$language][$view][$layout])){
              return self::$lookup[$language][$view][$layout];
            }
          }
        }
      }
    }
    // print_r(self::$lookup);exit;
    // check any item from our component
    if ($needles)
    {
      foreach (self::$lookup[$language] as $view => $ids)
      {
        if (isset(self::$lookup[$language][$view]) && $view == $task) //$task
        {
          foreach (self::$lookup[$language][$view] as $id)
          {
            if (isset(self::$lookup[$language][$view][$layout])) {
              return self::$lookup[$language][$view][$layout];
            }else if (isset(self::$lookup[$language][$view])){ 
              foreach (self::$lookup[$language][$view] as $value) {
                return $value;
              }  
            }
          }
        }
      }
    }
    // Check if the active menuitem matches the requested language
    $active = $menus->getActive();
    if ($active && $active->component == 'com_medialibrary' &&
      ($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;
  }
  public static function getPeopleAssocRoute($id, $itemId, $task) {
        $database = JFactory::getDBO();
        $link = array();
        $bookIdArr = array();
        $associate_author = array();

        $arr_params =  array() ;
        $arr_params['task'] = $task;
        $arr_params['pid'] = $id ;
        $link_params = MediaLibraryHelperRoute::getMLOtherRoute($arr_params, 0);
        if (isset($id)) {
            $query = "SELECT associate_people FROM #__medialibrary_people WHERE id = $id";
            $database->setQuery($query);
            $associate_aut = $database->loadResult();
            if ($associate_aut != "") $associate_author = unserialize($associate_aut);
            if (count($associate_author) > 0) {
                foreach($associate_author as $oneAuthor) {
                    if ($oneAuthor != 0) {
                        $AuthorIdArr[] = $oneAuthor;
                    }
                }
                $AuthorIdArr = implode(',', $AuthorIdArr);
                $query = "SELECT id, langshow
                             FROM #__medialibrary_people
                             WHERE id in ($AuthorIdArr)";
                $database->setQuery($query);
                $assocAuthor = $database->loadAssocList();
                foreach($assocAuthor as $value) {
                    $lang = $value['langshow'];
                    $CurId = $value['id'];
                    $link[$lang] = "index.php?option=com_medialibrary&task=view_author&pid=$CurId";

                    $needles = array();
                    $needles['view'] = 'view_author';
                    $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;
                    }
                }
            } 
        }
        foreach ($link_params as $key => $value) {
            if (!array_key_exists($key, $link)) {
                $link[$key] = $value;
            }
        }
        return $link;
    }
}