<?php 
require_once "app/class-language-manager.php"; 

/**
 * Language Context
 * 
 * Enables user translation of application descriptions and resources
 * @author balexandre - Advantis Solutions
 * @package Backend\Languages
 * 
 */
class context_languages extends context {
	
	function context_languages(){
		main::check_auth_session();
	}
	
	/**
	 * 
	 * Context Entry point
	 * 
	 */
	function index(){
		
		$this->list_resources();
			
	}
	/**
	 * 
	 * Shows resource screen with the available resources for the given language
	 */
	function list_resources()  {
		
		$langid = $_REQUEST['langid'];
		
		if(!$langid) {
			$langid = Session::get_language()->id;
		} 
		
		$em = new EntityManager("languages");
		
		$language_list = $em->load();
		
		$em = new EntityManager("resources");
		
		$list = $em->load("languageid=:defaultlang or languageid=:langid order by code asc", array(':defaultlang' => __DEFAULTLANG, ':langid' => $langid));
		
		$indexedlist = array();
		
		foreach($list as $lang) {
			$indexedlist[$lang->code."_".$lang->languageid] = $lang;  
		}
		
		$this->screen("/languages/translate",array('page'=>'resources','language_list'=>$language_list,'list'=>$indexedlist,'lang_selected'=>$langid));
	}
	
	/**
	 * 
	 * Shows description screen with the available descriptions for the given language
	 */
	
	function list_descriptions()  {
		
		$langid = $_REQUEST['langid'];
		
		if(!$langid) {
			$langid = Session::get_language()->id;
		} 
		
		$em = new EntityManager("languages");
		
		$language_list = $em->load();
		
		$em = new EntityManager("descriptions");
		
		$list = $em->load("languageid=:defaultlang or languageid=:langid order by code asc", array(':defaultlang' => __DEFAULTLANG, ':langid' => $langid));
		
		$indexedlist = array();
		
		foreach($list as $lang) {
			$indexedlist[$lang->code."_".$lang->languageid] = $lang;  
		}
		
		$this->screen("/languages/translate",array('page'=>'descriptions','language_list'=>$language_list,'list'=>$indexedlist,'lang_selected'=>$langid));
		
	}
	
	/**
	 * 
	 * saves posted descriptions
	 */
	function descriptions_save() {
				
		foreach($_POST as $key => $value) {
			
			$pieces = explode("_",$key);
			
			if($pieces[0] == "valuetext") {
				
				$id = $pieces[1];
				
				if ($_POST['changed_'.$id]) {
					
					$obj = new Entity("descriptions");
					
					$obj->id = $id;
					
					$obj->valuetext = $value;
					
					$obj->save();
				}
			}
			
		}
		
		
		$this->list_descriptions();
		
	}
	
	/**
	 * 
	 * saves posted resources
	 */
	function resources_save() {
				
		foreach($_POST as $key => $value) {
			
			$pieces = explode("_",$key);
			
			if($pieces[0] == "valuetext") {
				
				$id = $pieces[1];
				
				if ($_POST['changed_'.$id]) {
									
					$obj = new Entity("resources");
					
					$obj->id = $id;
					
					$obj->valuetext = $value;
					
					$obj->save();
				}
			}
			
		}
		
		
		$this->list_resources();
		
	}
	
	
	
}


?>