<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Sitesettings extends CI_Controller {

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

	public function __construct() {
		parent::__construct();
		
		// admin login only
		if($this->session->userdata('admin_login')) {
			
			// form validation library
			$this->load->library('form_validation');
			$this->load->model('common_model');
			$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 {
				$this->session->set_userdata('last_page', current_url());
				redirect('admin/login');
			}
		}
	}

	private function isSubadmin() {

		if($this->session->userdata('user_type') == 'subadmin') {
			$controller = $this->router->fetch_class();
			$pages = json_decode($this->session->userdata('permission'));
		
			if(!in_array(ucfirst($controller), $pages)) {
				redirect('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
			);
			$this->session->set_userdata($array);

		} else {
			redirect('admin/login');
		}
	}

	public function index() 
	{

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

		$this->data['breadcrumbs'][] = array(
			'text' => $this->lang->line('text_home'),
			'href' => base_url().'admin'
		);
		
		$this->data['breadcrumbs'][] = array(
			'text' => $this->lang->line('text_settings')
		);
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  base_url().'admin/sitesettings';

		$site_data = $this->common_model->GetSiteSettings('site');
		

		$languageid = ($this->session->userdata('langid')) ? $this->session->userdata('langid'): '1';

		$site_lang_data = $this->common_model->GetSiteSettings('site');
		
		if($site_lang_data){	
			$site_data = array_merge($site_data, $site_lang_data);
		}

		foreach ($site_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}
		
	

		/*
		$site_default_data = $this->common_model->GetSiteSettingsdefault('site');
		// print_r($site_default_data);

		foreach ($site_default_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}
		
		if($site_data) {
			
			foreach ($site_data as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}

		} else {
			$site_data_default = $this->common_model->defaultlangSettingall('site');
			foreach ($site_data_default as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}
		}
		*/

		if($this->input->post()) {


			$this->form_validation->set_rules('name', 'Site name', 'trim|required');
			$this->form_validation->set_rules('url', 'Site URL', 'trim|required');
			$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required');
			
			$this->form_validation->set_rules('meta_title', 'Meta title', 'trim|required|min_length[6]');
			$this->form_validation->set_rules('meta_key', 'Meta keywords', 'trim|required|min_length[6]');
			$this->form_validation->set_rules('meta_description', 'Meta description', 'trim|required|min_length[5]');
			
			if(isset($_FILES['favicon']['tmp_name'])) {
				$this->form_validation->set_rules('favicon', $this->lang->line('site_fav_icon_lbl'), 'trim|xss_clean|callback_validate_favimage');
			}

			if(isset($_FILES['logo']['tmp_name'])) {
				$this->form_validation->set_rules('logo', 'Site Logo', 'trim|xss_clean|callback_validate_image');
			}

				if(isset($_FILES['white']['tmp_name'])) {
				$this->form_validation->set_rules('white', 'whitepaper', 'trim|xss_clean|callback_validate_whiteimage');
			}

			$this->form_validation->set_rules('analytical_code', 'Analytical code', 'trim|required|min_length[10]');
			$this->form_validation->set_rules('live_chat_code', 'Live Chat Code', 'trim|required|min_length[10]');
			$this->form_validation->set_rules('offline_msg', 'Offline message', 'trim|required|min_length[10]');

			// check form validate
			if ($this->form_validation->run() == TRUE) {


				/*if(isset($_FILES['logo']['tmp_name']) && $_FILES['logo']['size'] > 0) {

					$uploads_dir = './content/site';
					$tmp_name = $_FILES["logo"]["tmp_name"];
					        
			        $name = basename($_FILES["logo"]["name"]);
			        if(move_uploaded_file($tmp_name, "$uploads_dir/$name")){
			        	
			        	// delete existing file
			        	if(isset($site_data['site_logo'])){
							unlink('./content/site/'.$site_data['site_logo']);
						}

						$sitedata = array(
							"site_value"	=>	$name
						);
						$this->db->where('settings_name','site');
						$this->db->where('site_key','site_logo');
						$update_status_logo = $this->db->update('site_controls', $sitedata);
			        }
			        else{
			        	echo 'error';
			        }
				
				}


				if(isset($_FILES['white']['tmp_name']) && $_FILES['white']['size'] > 0) {

					$uploads_dir = './content/site';
					$tmp_name = $_FILES["white"]["tmp_name"];
					        
			        $name = basename($_FILES["white"]["name"]);
			        if(move_uploaded_file($tmp_name, "$uploads_dir/$name")){
			        	
			        	// delete existing file
			        	if(isset($site_data['white'])){
							unlink('./content/site/'.$site_data['white']);
						}

						$sitedata = array(
							"site_value"	=>	$name
						);
						$this->db->where('settings_name','site');
						$this->db->where('site_key','whitepaper');
						$update_status_logo = $this->db->update('site_controls', $sitedata);
			        }
			        else{
			        	echo 'error';
			        }
				
				}

				if(isset($_FILES['favicon']['tmp_name']) && $_FILES['favicon']['size'] > 0) {

					$uploads_dir = './content/favicon';
					$tmp_name = $_FILES["favicon"]["tmp_name"];
					        
			        $favicon = basename($_FILES["favicon"]["name"]);
			        if(move_uploaded_file($tmp_name, "$uploads_dir/$favicon")){
			        	
			        	// delete existing file
			        	if(isset($site_data['site_favicon'])){
							unlink('./content/favicon/'.$site_data['site_favicon']);
						}

						$sitedata = array(
							"site_value"	=>	$favicon
						);
						$this->db->where('settings_name','site');
						$this->db->where('site_key','site_favicon');
						$update_status_logo = $this->db->update('site_controls', $sitedata);
			        }
			        else{
			        	echo 'error';
			        }
				
				}*/

				foreach ($site_data as $key => $row) {
					$key_value = str_replace('site_', '', $row->site_key);
					/*
					if($row->language_id > 0) {

						$sitedata = array(
							"site_value"	=>	$this->input->post($key_value)
						);
						$this->db->where('settings_name','site');
						$this->db->where('site_key',$row->site_key);
						$this->db->where('language_id',$languageid);
						
						$update_status = $this->db->update('site_controls', $sitedata);
						
					} else {
						*/

						if($this->input->post($key_value)){

							if($row->site_key=='site_offline_msg' || $row->site_key=='site_name' || $row->site_key=='site_meta_title' || $row->site_key=='site_meta_key' || $row->site_key=='site_meta_description') {
								$sitedata = array(
									"site_value"	=>	$this->input->post($key_value)
								);

								$this->db->where('settings_name','site');
								$this->db->where('site_key',$row->site_key);
								$this->db->where('language_id',$languageid);
								$this->db->from('site_controls');
								$check_status = $this->db->get();
								if($check_status->num_rows()>0) {

									$this->db->where('settings_name','site');
									$this->db->where('site_key',$row->site_key);
									$this->db->where('language_id',$languageid);
									//$update_status = $this->db->update('site_controls', $sitedata);
									
								} else {
									$sitedata = array(
										"settings_name"	=> "site",
										"language_id"	=> $this->session->userdata('langid'),
										"site_key"	=>	$row->site_key,
										"site_value"	=>	$this->input->post($key_value)
									);
									//$update_status = $this->db->insert('site_controls', $sitedata);
								}

							} 
							else if($row->site_key!='site_logo' || $row->site_key!='site_favicon') {
								$sitedata = array(
									"site_value"	=>	$this->input->post($key_value)
								);
								$this->db->where('settings_name','site');
								$this->db->where('site_key',$row->site_key);
								//$update_status = $this->db->update('site_controls', $sitedata);
							} 
							
							
						} else {
							if($row->site_key=='site_status') {
								$sitedata = array(
									"site_value"	=>	'0'
								);

								$this->db->where('settings_name','site');
								$this->db->where('site_key',$row->site_key);
								//$update_status = $this->db->update('site_controls', $sitedata);
							}
						}
					// }

				}
				
			/*
				foreach ($site_default_data as $row) {

					$key_value = str_replace('site_', '', $row->site_key);

					if($this->input->post($key_value)){

						if($row->site_key!='site_logo') {
							$sitedata = array(
								"site_value"	=>	$this->input->post($key_value)
							);
							$this->db->where('settings_name','site');
							$this->db->where('site_key',$row->site_key);
							
							$update_status = $this->db->update('site_controls', $sitedata);
						}
						
					} else {
						if($row->site_key=='site_status') {
							$sitedata = array(
								"site_value"	=>	'0'
							);

							$this->db->where('settings_name','site');
							$this->db->where('site_key',$row->site_key);
							$update_status = $this->db->update('site_controls', $sitedata);
						}
					}
					echo "<br/>".$this->db->last_query();
					
				}
				
				
				// check setting table approprivate lange field values is there
				$languageid = ($this->session->userdata('langid')) ? $this->session->userdata('langid'): '1';
				$condition = "settings_name ='site' AND language_id = '".$languageid."'";
				$data_avail = $this->common_model->GetSettingall_lang($condition);
				// pr($data_avail);exit;
				if($data_avail) {
					foreach ($site_data as $row) {
						
						$key_value = str_replace('site_', '', $row->site_key);

							if($this->input->post($key_value)){

								$sitedata = array(
									"site_value"	=>	$this->input->post($key_value),
									"language_id"	=> ($this->session->userdata('langid')) ? $this->session->userdata('langid') : '1'
								);
								$this->db->where('settings_name','site');
								$this->db->where('site_key',$row->site_key);
								$this->db->where('language_id',$languageid);
								$update_status = $this->db->update('site_controls', $sitedata);
								


							} else {

								$sitedata = array(
									"site_value"	=>	'0'
								);

								$this->db->where('settings_name','site');
								$this->db->where('site_key',$row->site_key);
								$update_status = $this->db->update('site_controls', $sitedata);
								
							}

							// echo "<br/>".$this->db->last_query();
							
							
						}
						// exit;
				} else {
					
					foreach ($site_data_default as $row) {
						
						$key_value = str_replace('site_', '', $row->site_key);

						if($key_value!='logo' || $key_value!='start_date' || $key_value!='url' || $key_value!='status') {

							if($this->input->post($key_value)){

								$sitedata = array(
									"settings_name"	=> "site",
									"language_id"	=> $this->session->userdata('langid'),
									"site_key"	=>	$row->site_key,
									"site_value"	=>	$this->input->post($key_value)
								);
								
								$update_status = $this->db->insert('site_controls', $sitedata);

							} 
						}

					}
					
				}
				
				
				if(isset($_FILES['logo']['tmp_name'])=='' &&  $_FILES['favicon']['size'] > 0 && $_FILES['logo']['size'] > 0) {

					if($update_status) {
						$this->session->set_flashdata('success_message', $this->lang->line('site_success_message'));
						redirect('admin/sitesettings');
						
					} else {
						$this->session->set_flashdata('error_message', $this->lang->line('site_error_message'));
						redirect('admin/sitesettings');
					}

				} else {
			*/
					$update_status=1;
					
					if($update_status) {
						$this->session->set_flashdata('success_message', $this->lang->line('site_success_message'));
						redirect('admin/sitesettings');
						
					} else {
						$this->session->set_flashdata('error_message', $this->lang->line('site_error_message'));
						redirect('admin/sitesettings');
					}

				// }
				
			}
			
		}
		$this->load->view('admin/settings/site',$this->data);

	}
	
	/* validate custom alpha value */
	function alpha_dash_space($str)
	{
		if(preg_match("/^([-a-z_ ])+$/i", $str)) {
			return true;
		} else {
			$this->form_validation->set_message('alpha_dash_space', '<p><em class="state-error1">The given news header field values are only in character</em></p>');
			return false;
		}
	}

	/* validate image value */
	public function validate_image($str)
	{
		if($str) {		
			$this->load->library('upload');
			$path = './content/site/';
			$type = 'gif|jpg|png|jpeg|ico';
			$max_width = '200';
			$max_height = '200';
			$this->upload->initialize($this->set_upload_options($path, $type, $max_width, $max_height));

			if ( ! $this->upload->do_upload('logo')) {
				$this->form_validation->set_message('validate_image', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
				return false;
			} else {
				unlink('content/favicon/'.$this->upload->data('file_name'));
				return true;
			}
		}
	}

	/* validate whitepaper value */
	public function validate_whiteimage($str)
	{
		if($str) {		
			$this->load->library('upload');
			$path = './content/site/';
			$type = 'pdf';
		/*	$max_width = '200';
			$max_height = '200';*/
			$this->upload->initialize($this->set_upload_options1($path, $type));

			if ( ! $this->upload->do_upload('white')) {
				$this->form_validation->set_message('validate_whiteimage', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
				return false;
			} else {
				unlink('content/site/'.$this->upload->data('file_name'));
				return true;
			}
		}
	}

	/* validate image value */
	public function validate_favimage($str)
	{
		if($str) {
			$this->load->library('upload');
			$path = './content/favicon/';
			$type = 'gif|jpg|png|jpeg|ico';
			$max_width = '32';
			$max_height = '32';

			$this->upload->initialize($this->set_upload_options($path, $type, $max_width, $max_height));

			if ( ! $this->upload->do_upload('favicon')) {
				$this->form_validation->set_message('validate_favimage', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
				return false;
			} else {
				unlink('content/favicon/'.$this->upload->data('file_name'));
				return true;
			}
		}
	}
	private function set_upload_options($path, $type, $max_width, $max_height)
	{   
	    //upload an image options
	    $config = array();
	    $config['upload_path'] = $path;
	    $config['allowed_types'] = $type;
	    $config['max_size'] 	= '0';
	    $config['max_width']    = $max_width;
	    $config['max_height']   = $max_height;
	    $config['encrypt_name'] = TRUE;
	    $config['overwrite']     = FALSE;

	    return $config;
	}

	private function set_upload_options1($path, $type)
	{   
	    //upload an image options
	    $config = array();
	    $config['upload_path'] = $path;
	    $config['allowed_types'] = $type;
	    $config['max_size'] 	= '0';
	    $config['encrypt_name'] = TRUE;
	    $config['overwrite']     = FALSE;

	    return $config;
	}
}

