<?php 
namespace App\Controllers\Admin;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;

class Langsettings extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 17 Jun, 2016
	 * This controller to manage site setting page.
	 * Created saravana kumar.
	 * @see http://ihyip.com/admin/sitesettings/
	 * Last Updated: 29 Jun, 2016
	 * End
	 * 
	 */

	public function __construct() {
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}

		helper('filesystem');

		// admin login only
		if($session->get('admin_login')) {
		
			// form validation library
			// $this->load->library('form_validation');

			helper('file');
			$this->isSubadmin();

			
		} else {
			if(isset($_COOKIE['remember_token'])) {

				$myencrypt = new MyEncrypt;
				$token_value = $myencrypt->decode($this->input->cookie('remember_token'));
				$this->isCookie($token_value);	

			} else {
				$session->set('last_page', current_url());
				return redirect()->to('admin/login');
			}
		}

	}

	private function isSubadmin() {
$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		if($session->get('user_type') == 'subadmin') {
			$controller = $this->router->controllerName();
			$pages = json_decode($session->get('permission'));
		
			if(!in_array(ucfirst($controller), $pages)) {
				return redirect()->to('admin');
			}
		}
	}

	private function isCookie($values) {

		$value = explode('|', $values);
		$result = $this->common_model->getPassword($value[0]);
		$hashed_password = $result->password;

		if(crypt(urlencode($value[1]), $hashed_password)) {

			$array = array(
				"logged_in" => TRUE,
				"userid" => $result->id,
				"admin_login" => TRUE
			);
			$session->set($array);

		} else {
			return redirect()->to('admin/login');
		}
	}

	public function index()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => 'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_settings')
		);
		$this->data['module_name'] = 'settings';
		$this->data['lang_data'] = $this->common_model->GetResults('language_controls');

		echo view('admin/settings/language',$this->data);

	}
	public function add() {
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_language')
		);
		$this->data['module_name'] = 'settings';
		$this->data['countries'] = $this->common_model->GetResults('country');
		$this->data['action'] =  'admin/langsettings/add';

		$id = ($uri->getSegment(4)) ? $uri->getSegment(4) : '';

		if($id) {
			$myencrypt = new MyEncrypt;
			$language_id = $myencrypt->decode($id);
			$condition = "language_id = '".$language_id."'";
			$this->data['lang_data'] = $this->common_model->GetRow('language_controls', $condition);
		}
		if($this->request->getPost()) {
			if($this->request->getPost('language_id')) {
				$language_id = $this->request->getPost('language_id');
                $validation->setRules([
                	'name' => ['label' => 'Language Name', 'rules' => 'trim|required|alpha|min_length[4]|edit_unique[language_controls.language_name'.$language_id.']']
                ]);
				// $this->form_validation->set_rules('name', 'Language name', 'trim|required|alpha|min_length[4]|edit_unique[language_controls.language_name'.$language_id.']');
			} else {
				$validation->setRules([
                	'name' => ['label' => 'Language Name', 'rules' => 'trim|required|alpha|min_length[4]|is_unique[language_controls.language_name]']
                ]);
				// $this->form_validation->set_rules('name', 'Language name', 'trim|required|alpha|min_length[4]|is_unique[language_controls.language_name]');
			}

			$validation->setRules([
                	'code' => ['label' => 'Language Code', 'rules' => 'trim|required|max_length[2]']
                ]);

			// $this->form_validation->set_rules('code', 'Langage code', 'trim|required|max_length[2]');

			// check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {
				if($this->request->getPost('default')) {
					$lang_up_data = array(
						"language_default" => '0'
					);
				// $this->db->where('language_id!=',$this->request->getPost('language_id'));
					$this->db->table('language_controls')->update($lang_up_data);
				}

				$new_path = 'app/Language/'.strtolower($this->request->getPost('name'));
				$url = explode('/',base_url());
				array_pop($url);
				$basepath = implode('/', $url);
				$context = stream_context_create(
				array(
				"http" => array(
				"header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
				)
				)
				);

				$url=$basepath.'/app/Language/en/language_lang.php';
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$language_data=curl_exec($ch);

$ur11 = $basepath.'/app/Language/en/index.html';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url1);
$language_index=curl_exec($ch);


				// $language_data = file_get_contents($basepath.'/app/Language/en/language_lang.php',false,$context);
				// $language_index = file_get_contents($basepath.'/app/Language/en/index.html');

				if($this->request->getPost('language_id')) {

					$condition = "language_id = '".$language_id."'";
					$ext_lang_data = $this->common_model->GetRow('language_controls', $condition);
					$existing_name = $ext_lang_data->language_name;

					if(strtolower($this->request->getPost('name')!=$existing_name)){
						$old_path = 'app/Language/'.$existing_name;

						if(mkdir($new_path, 0777, true)) {
							
							if(write_file($new_path.'/language_lang.php', $language_data)){
								if(write_file($new_path.'/index.html', $language_index)){
									unlink($old_path.'/language_lang.php');
									rmdir($old_path);
								}
							}
						}
					}

					$languagedata = array(
						"language_name"	=>	strtolower($this->request->getPost('name')),
						"language_default"	=>	($this->request->getPost('default')) ? '1' : '0',
						"language_code"	=>	strtolower($this->request->getPost('code')),
						"language_status"	=>	($this->request->getPost('status')) ? '1' : '0'
					);
					if($this->request->getPost('default')){
						$languagedata["language_status"] = '1';
					}
					
				
					$query_status = $this->db->table('language_controls')->where('language_id',$this->request->getPost('language_id'))->update($languagedata);

				} else {

					if(mkdir($new_path, 0777, true)) {
						if(write_file($new_path.'/language_lang.php', $language_data)){
							if(write_file($new_path.'/index.html', $language_index)){

								$languagedata = array(
									"language_name"	=>	strtolower($this->request->getPost('name')),
									"language_default"	=>	($this->request->getPost('default')) ? '1' : '0',
									"language_code"	=>	strtolower($this->request->getPost('code')),
									"language_status"	=>	($this->request->getPost('status')) ? '1' : '0'
								);
								
								$query_status = $this->db->table('language_controls')->insert($languagedata);
							}
						} 	
					}

				}

				if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.lang_success_message'));
					return redirect()->to('admin/langsettings');
				} else {
					$session->setFlashData('error_message', lang('language_lang.lang_error_message'));
					return redirect()->to('admin/langsettings');
				}
				
			} 
			
		}
		echo view('admin/settings/addlanguage',$this->data);
	}

	public function delete($id = "") {
		$session = session();
		$uri = service('uri');
        $id = ($uri->getSegment(4)) ? $uri->getSegment(4) : '';
		if($id) {
			$myencrypt = new MyEncrypt;
			
			$language_id = $myencrypt->decode($id);

			if($language_id!='1') {

				$condition = "language_id = '".$language_id."' ";
				$lang_data = $this->common_model->GetRow('language_controls',$condition);
				
				if($lang_data->language_default=='1') {
					
					$lang_up_data = array(
						"language_default" => '1'
					);

					
					$update_status = $this->db->table('language_controls')->where('language_id', '1')->update($lang_up_data);
					
					if($update_status){

						/* delete language table */
					
						$delete_status = $this->db->table('language_controls')->where('language_id',$language_id)->delete();

						/* delete site settings */
						$delete_status = $this->db->table('site_controls')->where('language_id',$language_id)->delete();

						/* delete CMS page */
						$delete_status = $this->db->table('page_controls')->where('language_id',$language_id)->delete();
					}
					
				} else {

					/* delete language table */
					$delete_status = $this->db->table('language_controls')->where('language_id',$language_id)->delete();

					/* delete site settings */
					$delete_status = $this->db->table('site_controls')->where('language_id',$language_id)->delete();

					/* delete CMS page */
					$delete_status = $this->db->table('page_controls')->where('language_id',$language_id)->delete();

				}

				if($delete_status) {
					$file_path = 'application/language/'.$lang_data->language_name;
					// unlink($file_path.'/admin/language_lang.php');
					// unlink($file_path.'/user/language_lang.php');
					if(is_dir($file_path)) {
						if(file_exists($file_path.'/language_lang.php')) {
							unlink($file_path.'/language_lang.php');		
						}
						if(file_exists($file_path.'/index.html')) {
							unlink($file_path.'/index.html');
						}
						rmdir($file_path);
					}
					// rmdir($file_path.'/admin');
					// rmdir($file_path.'/user');
					if($delete_status){
						$session->setFlashData('success_message', lang('language_lang.lang_success_message'));
						return redirect()->to('admin/langsettings');
					}
				} else {
					$session->setFlashData('error_message', lang('language_lang.lang_error_message'));
					return redirect()->to('admin/langsettings');
				}

			} else {
				$session->setFlashData('error_message', lang('language_lang.lang_error_default_message'));
				return redirect()->to('admin/langsettings');
			}

		} else {
			return redirect()->to('admin/langsettings');
		}
	}

	// make default language
	public function makedefaults() {

		if($this->request->getPost()) {
			$myencrypt = new MyEncrypt;
			$language_id = $myencrypt->decode($this->request->getPost('id'));
			$condition = "language_id = '".$language_id."' ";
			$curr_data = $this->common_model->GetRow('language_controls',$condition);
			if($curr_data->language_default==0)
			{
				$cur_up_data = array(
					"language_default" => '0'
				);
				$this->db->table('language_controls')->update($cur_up_data);

				$cur_up_data1 = array(
					"language_default" => '1'
				);

			
				$default_status = $this->db->table('language_controls')->where('language_id',$language_id)->update($cur_up_data1);

				if($default_status){
					$this->config->set_item('language',$curr_data->language_name);
					// $session->set('site_lang', $curr_data->language_name);
					$session->setFlashData('success_message', lang('language_lang.lang_success_message_default'));
					echo 1;
				} else {
					$session->setFlashData('error_message', lang('language_lang.lang_error_message_default'));
					echo 0;
				}

			}

		}
	}

}

