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

class Paymentsettings extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 29 Jun, 2016
	 * This controller to manage admin and user payment details page.
	 * Created saravana kumar.
	 * @see http://ihyip.com/admin/sitesettings/
	 * Last Updated: 30 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');
		}
		// admin login only
		if($session->get('admin_login')) {
			// form validation library
			// $this->load->library('form_validation');
			$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 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');
		}
	}
	private function isSubadmin() {
	$this->router = service('router');
	$session = 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');
	}
	}
	}
	public function index()
	{
		$session = session();
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$myencrypt = new MyEncrypt;
		$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';
		 // $condition = "payment_key in('logo','status') and payment_id in('1','2','3','4','5','6','7','8')";
		$condition = "payment_key in('address') and payment_id in('17','18')";
		// $this->data['payment_data_list'] = $this->common_model->GetPaymentsName($condition);
		$payment_data_list = $this->common_model->GetPaymentsName($condition);


		// echo $this->db->getLastQuery();
		// exit();

		// echo $this->db->last_query();
		// exit();

		//print_r($payment_data_list);

		// pr($payment_data_list);
		$pay_array = array();
		$pay_array1['payment_name'] = '';
		foreach ($payment_data_list as $row) {

			
			if($row->payment_name!=$pay_array1['payment_name'])
			{
				
				$pay_array1['payment_name'] = $row->payment_name;	
				$pay_array1['payment_id'] = $row->payment_id;
				$pay_array[]= $pay_array1;	
				
			} 
			else 
			{
				$pay_array1['payment_status'] = $row->payment_value;
				$pay_array1['payment_id'] = $row->payment_id;
				$pay_array[]= $pay_array1;
			}
	
		}

		$this->data['payment_data_list'] = $pay_array;
		$this->data['myencrypt'] = $myencrypt;
		echo view('admin/settings/payments',$this->data);

	}

	public function uploadFile($path, $image) {
		if ($image->isValid() && ! $image->hasMoved()) {
			$newName = $image->getRandomName();
			$image->move('./'.$path, $newName);
			return $image->getName();
		}
		return "";
	}

	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');
		}
			$id = ($uri->getSegment(4)) ? $uri->getSegment(4) : '';
			$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_payment'),
				'href' => base_url().'admin/paymentsettings'
			);
			
			$this->data['module_name'] = 'settings';
			$this->data['action'] = 'admin/paymentsettings/add';

		
		if($id) {
			$myencrypt = new MyEncrypt(true);
			$payment_id = $myencrypt->decode($id);

			$payment_data = $this->common_model->GetPayment($payment_id);
			// $form_data['payment_name'] = $payment_name;
			foreach ($payment_data as $row) {
				$form_data[$row->payment_key] = $row->payment_value;
				$form_data['payment_id'] = $row->payment_id;
				$form_data['payment_name'] = $row->payment_name;
			}

			$this->data['gateway_name'] = $form_data['payment_name'];
			$this->data['forms'] = $form_data;
			$this->data['myencrypt'] = $myencrypt;
			// echo view('admin/settings/addpayment',$this->data);

		} 
		else 
		{
			if($this->request->getPost()) 
			{
			
				$myencrypt = new MyEncrypt(true);

				$payment_id = $myencrypt->decode($this->request->getPost('payment_id'));
				
				$payment_data = $this->common_model->GetPayment($payment_id);
				
				
				foreach ($payment_data as $row) 
				{
					$form_data[$row->payment_key] = $row->payment_value;
				}				
	
				foreach ($form_data as $key => $value) 
				{
					if($key!='status' && $key!='logo' && $key!='instant_payout')
					{
						if($key=='email')
						{
							if($payment_id!='9')
							{
								$validation->setRules([
									'$key' => [ 'label' => lang('language_lang.'.$key) , 'rules' => 'trim|required|valid_email']
								]);
								// $this->form_validation->set_rules($key, lang('language_lang'.$key), 'trim|required|valid_email');
							}
							else
							{
								$validation->setRules([
									'$key' => [ 'label' => lang('language_lang.'.$key) , 'rules' => 'trim|required']
								]);
							}
						} 
						else 
						{
							$validation->setRules([
								'$key' => [ 'label' => lang('language_lang.'.$key) , 'rules' => 'trim|required']
							]);
						}
					}
				}
				/*$logo=$_FILES['logo']['tmp_name'];
				if($logo!='') 
				{
					$validation->setRules([
						'logo' => [ 'label' => 'Logo' , 'rules' => 'trim|ext_in[logo,jpg,png,gif,jpeg]|is_image[logo]']
						]);
				}*/
				// check form validate
				if ($validation->withRequest($this->request)->run() == TRUE || 1) 
				{                 
					/*if($logo!='') 
					{					
						    // $config['upload_path'] = './content/payment/';
							// $config['allowed_types'] = 'gif|jpg|png|jpeg';
							// $config['encrypt_name'] = TRUE;
							// $this->load->library('upload', $config);
							// $this->upload->do_upload('logo');
							// $payment_logo_file = $this->upload->data();

						$path 				= 'content/payment/';
					    $file 			    = $this->request->getFile('logo');
					    $upload_file 	    = $this->uploadFile($path, $file);
						$paymentdata = array(
							"payment_value"	=>	$upload_file
						);
						
						$update_status_logo = $this->db->table('payment_controls')->where('payment_id',$payment_id)->where('payment_key','logo')->update($paymentdata);
					
					}
					if(trim($payment_data[2]->payment_value) != trim($this->request->getPost('private_key')) || trim($paymentdata[3]->payment_value) != trim($this->request->getPost('public_key'))){
                            $this->db->table('uusers_address')->truncate();
					}*/

					
					foreach ($payment_data as $row) 
					{						
						$payment_key = $row->payment_key;
						if($payment_key!='logo') 
						{

							if($this->request->getPost($payment_key))
							{

								$paymentdata = array(
									"payment_value"	=>	$this->request->getPost($payment_key)
								);
								$update_status = $this->db->table('payment_controls')->where('payment_id',$payment_id)->where('payment_key',$payment_key)->update($paymentdata);

							} 
							else 
							{

								$paymentdata = array(
									"payment_value"	=>	'Off',
								);
								$update_status = $this->db->table('payment_controls')->where('payment_id',$payment_id)->where('payment_key',$payment_key)->update($paymentdata);

							}
							
						}

					}					
					//$logo=$_FILES['logo']['tmp_name'];
					$logo='';
					if($logo=='') 
					{
						if($update_status) 
						{
							$session->setFlashData('success_message', lang('language_lang.pay_success_message'));
							return redirect()->to('admin/paymentsettings');
							
						} 
						else 
						{
							$session->setFlashData('error_message', lang('language_lang.pay_error_message'));
							return redirect()->to('admin/paymentsettings');
						}

					} 
					else 
					{

						if($update_status && $update_status_logo) 
						{
							$session->setFlashData('success_message', lang('language_lang.pay_success_message'));
							return redirect()->to('admin/paymentsettings');
							
						} 
						else 
						{
							$session->setFlashData('error_message', lang('language_lang.pay_error_message'));
								//$session->setFlashData('error_message', lang('language_lang.demo_version_error'));
							return redirect()->to('admin/paymentsettings');
						}

					}
					
				}

				$payment_data = $this->common_model->GetPayment($payment_id);
				$payment_name = $payment_data[0]->payment_name;
				$this->data['gateway_name'] = $payment_name;
				$form_data['payment_name'] = $payment_name;
				foreach ($payment_data as $row) 
				{
					$form_data[$row->payment_key] = $row->payment_value;
				}
				
				$this->data['forms'] = $form_data;
				// echo view('admin/settings/addpayment',$this->data);
				
			}
			else 
			{
				return redirect()->to('admin/paymentsettings');
			}
		}
		

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

	

	/* validate image value */
	public function validate_image($str)
	{
		
		$config['upload_path'] = './content/payment/';
		$config['allowed_types'] = 'gif|jpg|png|jpeg';
		$config['encrypt_name'] = TRUE;
		$this->load->library('upload', $config);

		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 {

			$imageData=$this->upload->data();
				$file_name=$imageData['file_name'];
         		unlink('content/payment/'.$file_name);
			return true;
		}
		
	}

	// install payment gateway
	public function install() {

		if($this->request->getPost()) {
			$myencrypt = new MyEncrypt;
			//$payment_name = $myencrypt->decode($this->request->getPost('id'));
			$payment_name =$this->request->getPost('id');

			$paymentdata = array(
				"payment_value"	=>	'On',
			);
			$update_status = $this->db->table('payment_controls')->where('payment_id',$payment_name)->where('payment_key','status')->update($paymentdata);

			if($update_status){
				$session->setFlashData('success_message', lang('language_lang.pay_success_message_install'));
				echo 1;
			} else {
				$session->setFlashData('error_message', lang('language_lang.pay_error_message_install'));
				echo 0;
			}

		}
	}

	// uninstall payment gateway
	public function uninstall() {

		if($this->request->getPost()) {
			$myencrypt = new MyEncrypt;
			//$payment_name = $myencrypt->decode($this->request->getPost('id'));
			$payment_name =$this->request->getPost('id');

			$paymentdata = array(
				"payment_value"	=>	'Off',
			);

			$update_status = $this->db->table('payment_controls')->where('payment_id',$payment_name)->where('payment_key','status')->update($paymentdata);

			if($update_status){
				$session->setFlashData('success_message', lang('language_lang.pay_success_message_uninstall'));
				echo 1;
			} else {
				$session->setFlashData('error_message', lang('language_lang.pay_error_message_uninstall'));
				echo 0;
			}

		}
	}
	

}

