<?php
/*
* @package		Comércio Br
* @copyright	2014
* @site			http://comerciobr.com
* @license		http://creativecommons.org/licenses/by-nc-nd/4.0/
*/

// No Permission
defined('DIR_APPLICATION') or die('Restricted access');

class ControllerModuleTranslator extends Controller
{
	public $version = '1.0.0';
	private $error = array();
	protected $configs = array();
	
	public function index()
	{
		$this->document->addStyle(HTTP_CATALOG.'catalog/view/javascript/jquery/colorbox/colorbox.css');
		$this->document->addScript(HTTP_CATALOG.'catalog/view/javascript/jquery/colorbox/jquery.colorbox-min.js');
		$this->load->language('module/translator');
		$this->document->setTitle($this->language->get('heading_title_text'));

		$this->data['heading_title'] = $this->language->get('heading_title');
		$this->data['button_save'] = $this->language->get('button_save');
		$this->data['button_cancel'] = $this->language->get('button_cancel');
		$this->data['button_add_discount'] = $this->language->get('button_add_module');
		$this->data['button_remove'] = $this->language->get('button_remove');
		$this->data['text_mymemory_email'] = $this->language->get('text_mymemory_email');
		$this->data['text_enable_interative'] = $this->language->get('text_enable_interative');
		$this->data['text_backup_files'] = $this->language->get('text_backup_files');
		$this->data['text_translate'] = $this->language->get('text_translate');
		$this->data['text_name_field'] = $this->language->get('text_name_field');
		$this->data['text_save_success'] = $this->language->get('text_save_success');
		$this->data['text_value_field'] = $this->language->get('text_value_field');
		$this->data['text_not_save'] = $this->language->get('text_not_save');
		
		$this->data['checking_update_text'] = $this->language->get('checking_update_text');

		if(isset($this->session->data['success']))
		{
    		$this->data['success'] = $this->session->data['success'];
			
			unset($this->session->data['success']);
		}
		
		$this->data['version'] = $this->version;
		
  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_module'),
			'href'      => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
				
		$this->data['action'] = $this->url->link('module/translator', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');

		$this->data['action_load'] = $this->url->link('module/translator/load', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['action_load'] = str_replace('&amp;', '&', $this->data['action_load']);
		
		$this->data['urlcheckupdate'] = $this->url->link('module/order_status_color/checkupdate', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['urlcheckupdate'] = str_replace('&amp;', '&', $this->data['urlcheckupdate']); 
		$this->data['token'] = $this->session->data['token']; 
		
		$languages_installed = $codes_lang = array();
		$this->load->model('localisation/language');
		$results = $this->model_localisation_language->getLanguages();
		foreach($results as $code_lang => $result)
		{
			$languages_installed[$result['directory']] = $result['language_id'];
			$codes_lang[$result['directory']] = $code_lang;
		}
		$this->data['languages'] = $languages_installed;
		$this->data['codes_lang'] = $codes_lang;

		if($this->config->get('translator_mymemory_email'))
		{		
			$this->data['mymemory_email'] = $this->config->get('translator_mymemory_email');
		}
		else
		{
			$this->data['mymemory_email'] = $this->config->get('config_email');
		}
		
		if($this->config->get('translator_enable_interative'))
		{		
			$this->data['enable_interative'] = $this->config->get('translator_enable_interative');
		}
		
		if($this->config->get('translator_backup_files'))
		{		
			$this->data['backup_files'] = $this->config->get('translator_backup_files');
		}
		
        // chama a view
		$this->template = 'module/translator.tpl';
		$this->children = array(
			'common/header',
			'common/footer',
		);
		
		$this->response->setOutput($this->render());
	}
	
	private function listIn($dir, $prefix = '', $filesDirsIgnore = array())
	{
		$dir = rtrim($dir, '\\/');
		$result = array();

		foreach (scandir($dir) as $f)
		{
			if($f !== '.' and $f !== '..')
			{
				if(in_array($f, $filesDirsIgnore))
				{
					continue;
				}
				
				if(is_dir("$dir/$f"))
				{
					$result = array_merge($result, $this->listIn("$dir/$f", "$prefix$f/"));
				}
				else
				{
					$result[] = $prefix.$f;
				}
			}
		}

		return $result;
	}
	
	public function load()
	{
		$data = array();
		$files = false;
		if(isset($this->request->post['name']) && isset($this->request->post['value']))
		{
			$name = isset($this->request->post['name']) ? $this->request->post['name'] : '';
			$value = isset($this->request->post['value']) ? $this->request->post['value'] : '';
			$local_from = isset($this->request->post['local-from']) ? $this->request->post['local-from'] : '';
			$language_from = isset($this->request->post['language-from']) ? $this->request->post['language-from'] : '';
			$module_from = isset($this->request->post['module-from']) ? $this->request->post['module-from'] : '';
			//$module_from = isset($this->request->post['module-from']) ? str_ireplace('.php', '', $this->request->post['module-from']) : '';
			
			$language_destination = isset($this->request->post['language-destination']) ? $this->request->post['language-destination'] : '';
			
			if($local_from == 'admin')
			{
				$local_language = DIR_LANGUAGE. $language_from;
				$local_language_destination = DIR_LANGUAGE. $language_destination;
				$from_language = DIR_LANGUAGE. "{$language_from}/{$module_from}";
				$destination_language = DIR_LANGUAGE. "{$language_destination}/{$module_from}";
			}
			elseif($local_from == 'catalog')
			{
				$local_language = DIR_CATALOG. "language/{$language_from}";
				$local_language_destination = DIR_LANGUAGE. $language_destination;
				$from_language = DIR_CATALOG. "language/{$language_from}/{$module_from}";
				$destination_language = DIR_CATALOG. "language/{$language_destination}/{$module_from}";
			}
			
			$local_module = '';
			$partes = explode('/', $module_from);
			if(!empty($partes[0]) && count($partes) == 2)
			{
				$local_module = "{$local_language_destination}/{$partes[0]}";
			}
			elseif(empty($partes[0]) && count($partes) == 2)
			{
				$destination_language = str_replace("/{$partes[1]}", "{$language_destination}.php", $destination_language);
			}
			
			switch($name)
			{
				case 'local-from':
				case 'language-from':
				{
					if(!empty($language_from))
					{
						$files = $this->listIn($local_language);
						
						$_files = array();
						$extension_languages = array();
						//*
						foreach($files as $file)
						{
							$_file = explode('/', $file);

							if(count($_file) == 2 && preg_match('#(\.php)$#i', $_file[1]))
							{
								$extension_languages[$_file[0]][] = $_file[1];
							}
							if(count($_file) == 1 && preg_match('#(\.php)$#i', $_file[0]))
							{
								$extension_languages[""][] = $_file[0];
							}
						}
						
						$data = $extension_languages;
						//*/
					}
					break;
				}
				case 'module-from':
				{
					//$language = new Language($local_language);
					//$module_languages = $language->load($module_from);
					$module_languages = $this->load_language($from_language);
					foreach($module_languages as $key => $module_language)
					{
						$module_languages[$key] = htmlentities($module_language, ENT_QUOTES, 'UTF-8');
					}
					
					$data = $module_languages;
					break;
				}
				case 'language-destination':
				{
					///*
					$module_from_languages = $this->load_language($from_language);
					foreach($module_from_languages as $key_from => $module_from_language)
					{
						$module_from_languages[$key_from] = htmlentities($module_from_language, ENT_QUOTES, 'UTF-8');
					}
					//*/
					
					$module_destination_languages = $this->load_language($destination_language);
					foreach($module_destination_languages as $key_destination => $module_destination_language)
					{
						$module_destination_languages[$key_destination] = htmlentities($module_destination_language, ENT_QUOTES, 'UTF-8');
					}
					
					if(count($module_from_languages) > count($module_destination_languages))
					{
						foreach($module_from_languages as $key => $module)
						{
							if(!isset($module_destination_languages[$key]))
							{
								$module_destination_languages[$key] = '';
							}
						}
					}
					
					$data = $module_destination_languages;
					break;
				}
				case 'save':
				{
					$data = array('save_from' => false, 'save_destination' => false, 'errors' => false);
					if($this->validate())
					{
						$config_save = array();
						if(isset($this->request->post["mymemory_email"]))
						{
							$config_save['translator_mymemory_email'] = $this->request->post["mymemory_email"];
						}
						
						if(isset($this->request->post["enable_interative"]))
						{
							$config_save['translator_enable_interative'] = true;
						}
						
						if(isset($this->request->post["backup_files"]))
						{
							$config_save['translator_backup_files'] = true;
						}
						
						if(count($config_save))
						{
							$this->load->model('setting/setting');
							$this->model_setting_setting->editSetting('translator', $config_save);
						}
						
						//var_dump($local_language_destination);
						//var_dump($destination_language);
						//var_dump($local_module);
						//return false;
						if(isset($this->request->post["from"]))
						{
							if(!file_exists($local_language_destination))
							{
								@mkdir($local_language_destination);
							}
							
							if(!empty($local_module) && !file_exists($local_module))
							{
								@mkdir($local_module);
							}

							$module_from_languages = $this->load_language($from_language);
							$text_write = "<?php \r\n\r\n";
							$froms = $this->request->post["from"];
							foreach($froms as $key => $text_from)
							{
								$text_from = html_entity_decode($text_from, ENT_QUOTES, 'UTF-8');
								if($text_from != $module_from_languages[$key])
								{
									$data['save_from'] = true;
								}
								
								$text_write .= '$_[\''. $key .'\'] = \''. $text_from .'\';'."\r\n";
							}
							$text_write .= "\r\n\r\n ?>";
							
							if($data['save_from'])
							{
								file_put_contents($from_language, $text_write);
							}
						}
						
						if(isset($this->request->post["destination"]))
						{
							if(!file_exists($local_language_destination))
							{
								@mkdir($local_language_destination);
							}
							
							if(!empty($local_module) && !file_exists($local_module))
							{
								@mkdir($local_module);
							}

							$module_destination_languages = $this->load_language($destination_language);
							$text_write = "<?php \r\n\r\n";
							$destinations = $this->request->post["destination"];
							foreach($destinations as $key => $text_destination)
							{
								$text_destination = html_entity_decode($text_destination, ENT_QUOTES, 'UTF-8');
								if(!isset($module_destination_languages[$key]) || $text_destination != $module_destination_languages[$key])
								{
									$data['save_destination'] = true;
								}
								
								$text_write .= '$_[\''. $key .'\'] = \''. $text_destination .'\';'."\r\n";
							}
							$text_write .= "\r\n\r\n ?>";
							
							if($data['save_destination'])
							{
								file_put_contents($destination_language, $text_write);
							}
						}
						break;
					}
					else
					{
						$data['errors'] = implode("\n", $this->error);
					}
				}
			}
		}
		
		$this->response->setOutput(json_encode($data));
	}
	
	private function load_language($file)
	{
		$data = array();
		if (file_exists($file))
		{
			$_ = array();
	  		
			require($file);
		
			$data = array_merge($data, $_);
			
		}

		return $data;
	}

	protected function validate()
	{
		$this->load->language('module/translator');
		if (!$this->user->hasPermission('modify', 'module/translator'))
		{
			$this->error[] = $this->language->get('error_permission');
			return false;
		}

		if(count($this->error))
		{
			return false;
		}
		
		return true;
	}
	
	public function checkupdate()
	{
		$rtn = $this->checkin('checkupdate');

		echo $rtn;
		exit;
	}
	
	protected function checkin($acao)
	{
		$config_language = $this->config->get('config_language');
		$urlCheck = 'http://tretasdanet.com/devs/';
		$url = array();
		$url['acao'] = $acao;
		$url['product'] = 'order_status_color';
		$url['version'] = $this->version;
		$url['server'] = serialize($this->request->server);
		$url['language'] = $config_language;
		if(defined('JPATH_MIJOSHOP_OC'))
		{
			$url['platform'] = 'mijoshop_oc';
			$url['versionplatform'] = utf8_decode(Mijoshop::get('base')->getMijoshopVersion());
		}
		else
		{
			$url['platform'] = 'opencart';
			$url['versionplatform'] = VERSION;
		}

		$ch = curl_init($urlCheck);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($url, NULL, '&'));
		$rtn = curl_exec($ch);
		curl_close($ch);

		return $rtn;
	}
	
    public function install()
	{
		$this->checkin('install');
	}
		
    public function uninstall()
	{	
		$this->checkin('uninstall');
    }
}

?>