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

class Sitesettings 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: 02 Aug, 2017
	 * End
	 * 
	 */

	public function __construct() {
         $this->common_model = model('CommonModel');
		helper('site_helper');		
		$session = \Config\Services::session();
		// admin login only
		if($session->get('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 {
				$session->set('last_page', current_url());
				return redirect()->to('admin/login');
			}
		}
	}

	private function isSubadmin() {
$this->router = service('router');
		$session = \Config\Services::session();

		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' => base_url('admin')
		);
		
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_settings')
		);
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/sitesettings';
		//$this->data['action']='';

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

		$languageid = ($session->get('langid')) ? $session->get('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;
		}
		
		if($this->request->getPost()) {

			$validation =  \Config\Services::validation();
            $validation->setRules([
				'name' => ['label' => 'Site name', 'rules' => 'trim|required'],
				'url' => ['label' => 'Site URL', 'rules' => 'trim|required'],
				'start_date' => ['label' => 'Start Date', 'rules' => 'trim|required'],
				'meta_title' => ['label' => 'Meta Title', 'rules' => 'trim|required|min_length[6]'],
				'meta_key' => ['label' => 'Meta Key', 'rules' => 'trim|required|min_length[6]'],
				'meta_description' => ['label' => 'Meta Description', 'rules' => 'trim|required|min_length[5]']
			]);

			// $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]');
			
			$favicon=$_FILES['favicon']['tmp_name'];
			if($favicon!='') {
				$validation->setRules([
				'favicon' => ['label' => lang('language_lang.site_fav_icon_lbl'), 'rules' => 'trim|xss_clean|callback_validate_favimage']]);
			}

			$logo=$_FILES['logo']['tmp_name'];
			if($logo!='') {
				$validation->setRules([
				'logo' => ['label' => 'Site Logo', 'rules' => 'trim|xss_clean|callback_validate_favimage']]);
			}

			$white=$_FILES['white']['tmp_name'];
			if($white!='') {
				$validation->setRules([
				'white' => ['label' => 'whitepaper', 'rules' => 'trim|xss_clean|callback_validate_whiteimage']]);
			}


			$site_coin=$_FILES['sitecoin']['tmp_name'];
			if($site_coin!='') {
				$validation->setRules([
				'sitecoin' => ['label' => 'Sitecoin', 'rules' => 'trim|xss_clean|callback_validate_siteimage']]);
			}

			 $validation->setRules([
				'analytical_code' => ['label' => 'Analytical Code', 'rules' => 'trim|required|min_length[10]'],
				'live_chat_code' => ['label' => 'Live Chat Code', 'rules' => 'trim|required|min_length[10]'],
				'offline_msg' => ['label' => 'Offline Message', 'rules' => 'trim|required|min_length[10]']
			]);

			// check form validate
			if ($validation->withRequest($this->request)->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,$_SERVER['DOCUMENT_ROOT']."$uploads_dir/$name")){
			        	
			        	// delete existing file
			        	if(isset($site_data['site_logo'])){
							unlink('content/site/'.$site_data['site_logo']);
						}

						$sitedata = array(
							"site_value"	=>	$name
						);
				$update_status_logo = $this->db->table('site_controls')->where('settings_name','site')->where('site_key','site_logo')->update($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
						);
				$update_status_logo = $this->db->table('site_controls')->where('settings_name','site')->where('site_key','whitepaper')->update($sitedata);
			        }
			        else{
			        	echo 'error';
			        }
				
				}

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

				    	$uploads_dir = '/content/favicon';
					$tmp_name = $_FILES["favicon"]["tmp_name"];
					        
			        $name = basename($_FILES["favicon"]["name"]);

			        if(move_uploaded_file($tmp_name,$_SERVER['DOCUMENT_ROOT']."$uploads_dir/$name")){
			        	
			        	// delete existing file
			        	if(isset($site_data['site_logo'])){
							unlink('/content/favicon/'.$site_data['site_logo']);
						}

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


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

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

						$sitedata = array(
							"site_value"	=>	$favicon
						);
				$update_status_logo = $this->db->table('site_controls')->where('settings_name','site')->where('site_key','site_coin')->update($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->request->getPost($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->request->getPost($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->request->getPost($key_value)
								);
                                $builder = $this->db->table('site_controls');
								$builder->where('settings_name','site');
								$builder->where('site_key',$row->site_key);
								$builder->where('language_id',$languageid);
								$check_status = $builder->get();
								if($check_status->getNumRows()>0) {
                                    $update_status = $this->db->table('site_controls')->where('settings_name','site')->where('site_key',$row->site_key)->where('language_id',$languageid)->update($sitedata);
									
								} else {
									$sitedata = array(
										"settings_name"	=> "site",
										"language_id"	=> $session->get('langid'),
										"site_key"	=>	$row->site_key,
										"site_value"	=>	$this->request->getPost($key_value)
									);
									$update_status = $this->db->table('site_controls')->insert($sitedata);
								}

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

				}
				
				
			
					
					if($update_status) {
						$session->setFlashData('success_message', lang('language_lang.site_success_message'));
						return redirect()->to('admin/sitesettings');
						
					} else {
						$session->setFlashData('error_message', lang('language_lang.site_error_message'));
						return redirect()->to('admin/sitesettings');
					}

				// }
				
			}
			
		}
		echo 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)
	{
		$this->load->library('upload');
		$path = 'content/site/';
		$type = 'gif|jpg|png|jpeg|ico';
		$max_width = '200';
		$max_height = '200';
		$allowed_mime_type_arr = array('jpeg','jpg','png','gif');
		$mime=pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
		$mime=strtolower($mime);

        if(isset($_FILES['logo']['name']) && $_FILES['logo']['name']!="")
        {
            if(in_array($mime, $allowed_mime_type_arr))
            {
            	$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/site/'.$this->upload->data('file_name'));
             		return true;
             	}
            }
            else
            {
                $this->form_validation->set_message('validate_image', '<p><em class="text-danger">Please select only jpeg/gif/jpg/png file.</em></p>');
                return false;
            }
        }
        else
        {
            $this->form_validation->set_message('validate_image', 'Please choose a file to upload.');
            return false;
        }

	}


	public function validate_siteimage($str)
	{
		$this->load->library('upload');
		$path = './content/site/';
		$type = 'gif|jpg|png|jpeg|ico';
		$allowed_mime_type_arr = array('jpeg','jpg','png','gif');
		$mime=pathinfo($_FILES['sitecoin']['name'], PATHINFO_EXTENSION);
		$mime=strtolower($mime);

        if(isset($_FILES['sitecoin']['name']) && $_FILES['sitecoin']['name']!="")
        {
            if(in_array($mime, $allowed_mime_type_arr))
            {
            	$this->upload->initialize($this->set_upload_optionss($path, $type));
            	if(!$this->upload->do_upload('sitecoin'))
            	{
            		$this->form_validation->set_message('validate_siteimage', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
					return false;            		
             	}
             	else
             	{
             		$imageData=$this->upload->data();
					$file_name=$imageData['file_name'];
             		unlink('content/site/'.$file_name);
             		return true;
             	}
            }
            else
            {
                $this->form_validation->set_message('validate_siteimage', '<p><em class="text-danger">Please select only jpeg/gif/jpg/png file.</em></p>');
                return false;
            }
        }
        else
        {
            $this->form_validation->set_message('validate_siteimage', 'Please choose a file to upload.');
            return false;
        }

	}

	/* validate whitepaper value */
	public function validate_whiteimage($str)
	{
		$this->load->library('upload');
		$path = './content/site/';
		$type = 'pdf';
		$allowed_mime_type_arr = array('pdf');

		$mime=pathinfo($_FILES['white']['name'], PATHINFO_EXTENSION);

		$mime=strtolower($mime);

        if(isset($_FILES['white']['name']) && $_FILES['white']['name']!="")
        {
            if($_FILES['white']['type']=='application/pdf')
            {
            	return true;
            }
            
            else
            {
                $this->form_validation->set_message('validate_whiteimage', '<p><em class="text-danger">Please select only pdf file.</em></p>');
                return false;
            }
        }
        else
        {
            $this->form_validation->set_message('validate_whiteimage', 'Please choose a file to upload.');
            return false;
        }
		
	}

	/* validate image value */
	public function validate_favimage($str)
	{

		$this->load->library('upload');
		$path = './content/favicon/';
		$type = 'gif|jpg|png|jpeg|ico';
		$max_width = '200';
		$max_height = '200';
		$allowed_mime_type_arr = array('jpeg','jpg','png','gif','ico');
		$mime=pathinfo($_FILES['favicon']['name'], PATHINFO_EXTENSION);
		$mime=strtolower($mime);

        if(isset($_FILES['favicon']['name']) && $_FILES['favicon']['name']!="")
        {
            if(in_array($mime, $allowed_mime_type_arr))
            {
            	$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;
             	}
            }
            else
            {
              $this->form_validation->set_message('validate_favimage', '<p><em class="text-danger">Please select only jpeg/gif/jpg/png file.</em></p>');
                return false;
            }
        }
        else
        {
            $this->form_validation->set_message('validate_favimage', 'Please choose a file to upload.');
            return false;
        }

	}
	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_optionss($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;
	}

	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;
	}
}

