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

class Payments extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
		$this->login_model->authenticate();
		$this->load->library('form_validation');
		$this->load->model('payments_model');
		
		date_default_timezone_set("Africa/Nairobi");
	}
		

	
	public function process_payment()
	{
		$user_id = $this->login_model->user_id();
	  	$corp_id = $this->login_model->corp_id();
		$data['members'] = $this->main_model->fetch_relevant_members($corp_id);
		$data['sess_data'] =  $this->session->flashdata('POST_DATA');
		$data['receipt_name'] =  $this->session->flashdata('POST_DATA');
		
		$topbar_data['profile_photo'] = $this->main_model->create_thumbnail(160,160,$user_id);
		$topbar_data['additional_css'] = array('plugins/select2/select2.min.css"',
											   'plugins/datepicker/datepicker3.css"'
												);
		$sidebar_data['menu'] = $this->menu_control->get_menu($user_id);
		
		$jquery_data['additional_jquery'] = array('plugins/select2/select2.full.min.js"',
												  'plugins/datepicker/bootstrap-datepicker.js"'
												  );
		
		$jquery_data['functions'] = array(' <script type="text/javascript">
												  $("#select2").select2({
												   placeholder: "Select a Member"
												   });
												   
												   $.fn.datepicker.defaults.format = "M-dd-yyyy";
												  	$("#date_time").datepicker({
														autoclose: "true"
													  });
													//$("#date_time").datepicker("setDate", new Date(2016, 0, 15));
										 	 </script>
		   								');
					
		$this->load->view('sections/topbar',$topbar_data);
		$this->load->view('sections/sidebar',$sidebar_data);
		//for server copy diversity is corp_id 2
		if($corp_id == 2)
		{
			$this->load->view('payments/diversity/process_payment',$data);
		}
		else
		{
			$this->load->view('payments/process_payment',$data);
		}
		$this->load->view('sections/footer',$jquery_data);
	}
	
	//this function inserts the payment's value into database
	public function insert_payment()
	{
		
		$transaction_id = $this->main_model->get_next_id('payments','transaction_id');
		$user_id = $this->login_model->user_id();
		
		$this->form_validation->set_rules('member_name', 'Member Name - NO.', 'required');
		$this->form_validation->set_rules('reg_fee', 'Registration Fee', 'is_numeric');
		$this->form_validation->set_rules('share_capital', 'Share Capital', 'is_numeric');
		$this->form_validation->set_rules('service_charge', 'Service charge', 'is_numeric');
		$this->form_validation->set_rules('loan_repay', 'Loan repayment', 'is_numeric');
		$this->form_validation->set_rules('interest', 'Interest', 'is_numeric');
		$this->form_validation->set_rules('loan_penalty', 'Loan Penalty', 'is_numeric');
		$this->form_validation->set_rules('default_penalty', 'Default Penalty', 'is_numeric');
		$this->form_validation->set_rules('withdrawal_fee', 'Withdrawal fee', 'is_numeric');
		$this->form_validation->set_rules('total', 'Total', 'required|is_natural_no_zero');	
		
		$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
	  
		  if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		  {		  
			  $this->process_payment();		  
		  }
		  else // passed validation proceed to post success logic
		  {
			 // build array for the model	
			  $form_data = array(
			  				  'transaction_id' => $transaction_id,
							  'user_id' => $this->input->post('subject_id'),
							  'reg_fee' => $this->input->post('reg_fee'),
							  'share_capital' => $this->input->post('share_capital'),
							  'service_charge' => $this->input->post('service_charge'),
							  'loan_repay' => $this->input->post('loan_repay'),
							  'interest' => $this->input->post('interest'),
							  'loan_penalty' =>$this->input->post('loan_penalty'),
							  'default_penalty' => $this->input->post('default_penalty'),
							  'withdrawal_fee' => $this->input->post('withdrawal_fee'),
							  'total' => $this->input->post('total'),
							  'date_time' => time(),
							  'authorisor' => $user_id							  
						  );
			 			  
			  //insert the data into several tables using transaction - needs validation
			  // to capture error in case of failure
			  $insert_id = $this->payments_model->process_payment_trans($form_data);
			  
			  $this->load->library('../controllers/pdf/payments_receipt');
			  $receipt = $this->payments_receipt->return_receipt($insert_id);
			  //$receipt = pdf/payments_receipt/return_receipt/'.$insert_id
			  
			  $data = array('JSFunction' => '
							<script type="text/javascript">	
								window.onload = function(){
								var getMyFrame = document.getElementById(\'iFramePdf\');
								getMyFrame.focus();
								getMyFrame.contentWindow.print();								
								};
							</script>',
							'receiptName' => $receipt					
							);
			//pass this data to prompt browser to print receipt- working in chrome 
			//but needs to be cross-browser compatible
			  $this->session->set_flashdata('POST_DATA', $data);
			 // redirect('pdf/payments_receipt/return_receipt/'.$insert_id);					 				  
			  redirect('payments/process_payment');
			  
		  }
		
	}
	
	function insert_diversity_payment()
	{
		//payments_tbl: transaction_id(Auto), user_id, share_capital, total, date_time, time_recorded, authorisor
		/*$transaction_id = $this->main_model->get_next_id('payments','transaction_id');
		$user_id = $this->input->post();
		$share_capital = $total = $this->input->post('monthly_contribution');
		$date_time = $this->input->post('date_time');
		$time_recorded = time();
		$authorisor = $this->login_model->user_id();*/
		
		$this->form_validation->set_rules('date_time', 'Date', 'required');
		$this->form_validation->set_rules('member_name', 'Member Name', 'required');
		$this->form_validation->set_rules('monthly_contribution', 'Monthly Contribution', 'is_numeric');
		
		$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
	  
		  if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		  {		  
			  $this->process_payment();		  
		  }
		  else // passed validation proceed to post success logic
		  {
			  // build array for the model	
			  $form_data = array(			  				  
									'transaction_id' => $this->main_model->get_next_id('payments','transaction_id'),
									'user_id' => $this->input->post('subject_id'),
									'share_capital' => $this->input->post('monthly_contribution'),
									'total' => $this->input->post('monthly_contribution'),
									'date_time' => strtotime($this->input->post('date_time')),
									'time_recorded' => time(),
									'authorisor' => $this->login_model->user_id()
							  );
			$this->payments_model->process_diversity_payment($form_data);
			$data = array('JSFunction' => '
							<script type="text/javascript">	
							$(document).ready(function() {
								$("#displayMsg").html("Payments details submitted successfully.");
							});
							</script>'					
							);
			//pass this data to notify the user that the record was saved successfully
			$this->session->set_flashdata('POST_DATA', $data);
			redirect('payments/process_payment');
		  }
		
	}
	
	//loads a dataTable with a member's contributions
	public function financial_statement()
	{
		$user_id = $this->login_model->user_id();
		$corp_id = $this->login_model->corp_id();
		$data['payments'] = $this->payments_model->fetch_member_payments($user_id);
		
		$topbar_data['profile_photo'] = $this->main_model->create_thumbnail(160,160,$user_id);
		$topbar_data['additional_css'] = array('plugins/datatables/dataTables.bootstrap.css"');
		$sidebar_data['menu'] = $this->menu_control->get_menu($user_id);				
		
		$jquery_data['additional_jquery'] = array('plugins/datatables/jquery.dataTables.min.js"',			
												'plugins/datatables/dataTables.bootstrap.min.js"');
		
		$jquery_data['functions'] = array('<script type="text/javascript">
											  $(function () {
												$("#financial_statement").DataTable();
											  });
											</script>'					
										);
		
		$this->load->view('sections/topbar',$topbar_data);
		$this->load->view('sections/sidebar',$sidebar_data);
		$this->load->view('payments/diversity/financial_statement',$data);
		$this->load->view('sections/footer',$jquery_data);
	
	}

	
	//Lipisha Integration
	
	function triggerLipishaAPI()
	{
		include "Lipisha.php";
	
	$lipisha = new Lipisha();

	// API Environment
	$lipisha->api_environment = "test"; // Can either be "test" for sandbox/testing/developer or "live" for production environment 
	
	// API Keys (Note that each environment ("test" or "live") has a different set of api keys and signature (Can be found on the Developer (http://developer.lipisha.com) or Live (http://lipisha.com) dashboards))
	$lipisha->api_key = "7c487439a94da7437bcc0122735efbc8"; // Login to Lipisha Go to Setting -> API generate if not available and copy you api key
	$lipisha->api_signature = "1h2v9z0VNF0Ku/cc6rjUJe41OgcsrFXBrELw/yeebT56+LNB+yGgYPKnk+zytyI1zrLvCpPf4SOi/M8wcqnF+a8m0T7Sfs4U5RodXykp5CNozKZrMPK3iephwKg6XOShMR/h24O4U3fx+JoIUxugdmVs1cW+dFVXfvc4oKRqF2g="; // copy your api signature
	
	$lipisha->get_balance();
	echo $lipisha->json;
		
		
	}
	
	function simulate_payment()
	{
		$endpoint = "http://developer.lipisha.com/index.php/v2/api/make_mobile_payment";
		//Method - POST 
		//Content Type - Form (application/x-www-form-urlencoded)
		//header('Content-type: application/x-www-form-urlencode');
		
		//Parameters 
		$api_key = "7c487439a94da7437bcc0122735efbc8";
		$api_signature = "1h2v9z0VNF0Ku/cc6rjUJe41OgcsrFXBrELw/yeebT56+LNB+yGgYPKnk+zytyI1zrLvCpPf4SOi/M8wcqnF+a8m0T7Sfs4U5RodXykp5CNozKZrMPK3iephwKg6XOShMR/h24O4U3fx+JoIUxugdmVs1cW+dFVXfvc4oKRqF2g=";
		$mobile_number = "0713384482";
		$payment_type = "M-PESA";
		$business_number = "961700";
		$account_number = "00614";
		$amount ="2350";
		 
			
		$api_parameters = 'api_key=' . urlencode($api_key) . '&api_signature=' . urlencode($api_signature) .'&mobile_number=' . urlencode($mobile_number). '&payment_type=' . urlencode($payment_type). '&business_number=' . urlencode($business_number). '&account_number=' . urlencode($account_number). '&amount=' . urlencode($amount);	
		
		// execute post
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $endpoint);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $api_parameters); 
		curl_setopt($ch, CURLOPT_TIMEOUT, 180);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
		$results = curl_exec($ch);
		curl_close($ch);
					
		// process json
		$results = trim($results);
		$response = json_decode($results, TRUE);
		
		$status = urldecode($response["status"]["status"]);
		$status_code = urldecode($response["status"]["status_code"]);
		$status_description = urldecode($response["status"]["status_description"]);
		$content =$response["content"];
		$json = urldecode($results);
		
		print_r($json);
		echo "<hr>";
		print_r($results);
		echo "<hr>";
		print_r($response);
		
	
		
	}

 
}
?>