<?php
class ClassFeatureTranslation extends ClassFeature {
  public function __construct(){}
  public function __destruct(){}
  
  public function getFeatureTranslation($code, $lang='source'){
    $this->_code = $code;
    $this->_lang = $lang;
    $oPDOLink = ClassConfig::databaseConnect();
    
    $sql="
    SELECT ".$this->_lang."
    FROM core_feature_translation
    WHERE code=:code
    LIMIT 1
    ";
    $execSQL = $oPDOLink->prepare($sql);
    $execSQL->execute(array(':code'=>$this->_code));
    $row = $execSQL->fetch(PDO::FETCH_ASSOC);
    if($row[$this->_lang] != ''){
      return $row[$this->_lang];
    } else {
      return $row['source'];
    }
  }
  
  public function getFeatureTranslationById($id, $lang){
    //TODO get translation from APC cache
    $this->_id = $id;
    $this->_lang = $lang;
    $oPDOLink = ClassConfig::databaseConnect();
    
    $sql="
    SELECT source, ".$this->_lang."
    FROM core_feature_translation
    WHERE id=:id
    LIMIT 1
    ";
    $execSQL = $oPDOLink->prepare($sql);
    $execSQL->execute(array(':id'=>$this->_id));
    $row = $execSQL->fetch(PDO::FETCH_ASSOC);
    if($row[$this->_lang] != ''){
      return $row[$this->_lang];
    } else {
      return $row['source'];
    }
  }
  
  public function getURLTranslation($lang_code_source, $lang_code_dest, $page_url){
    //TODO get translation from APC cache
    $this->_langCodeSource = $lang_code_source;
    $this->_langCodeDest = $lang_code_dest;
    $this->_pageUrl = $page_url;
    $config = ClassConfig::getConfig();
    $oPDOLink = ClassConfig::databaseConnect();
    
    $regex = '#(?<='.ClassConfig::getURLRoot().')[a-z0-9-]*#';
    preg_match($regex, $this->_pageUrl, $page);

    $sql = "
    SELECT source, ".$this->_langCodeDest."
    FROM core_feature_translation
    WHERE (".$this->_langCodeSource."=:page OR source=:page_2)
        AND code LIKE 'menu_%_url';
    ";
    
    $execSQL = $oPDOLink->prepare($sql);
    $execSQL->execute(array(
        ':page'=>$page[0],
        ':page_2'=>$page[0]
    ));
    $row = $execSQL->fetch(PDO::FETCH_ASSOC);
    
    if(!isset($row[$this->_langCodeDest])){
        $new_page = $page[0];
    }
    else if($row[$this->_langCodeDest] != ''){
        $new_page = $row[$this->_langCodeDest];
    } else{
        $new_page = $row['source'];
    }

    $new_page_url = preg_replace('/'.$page[0].'/', $new_page, $this->_pageUrl, 1);
    
    return $new_page_url;
  }
}
