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

/**
* 	PAYMENT GATEWAY
* 	AA
* 	24032017
**/

class Payment extends CI_Controller 
{
	/* ************** DEVELOPMENT ENVIRONMENT ************** */


	// private $api_key 	= 'bf7c6276-b923-4979-84e3-6e03dcfe3fa9:'; // ':' is added so that no password is needed
	// private $endpoint 	= 'https://billplz-staging.herokuapp.com/api/v3/'; // Sandbox API endpoint


	/* ************** PRODUCTION ENVIRONMENT ************** */


	private $api_key 	= '94ded0ea-b8c4-4b03-ac3f-4322554d1281:';
	private $endpoint 	= 'https://www.billplz.com/api/v3/'; // Production API endpoint


	/* ************** COLLECTION ************** */


	function createNewCollection()
	/* Billplz API supports creation of collection with split payment feature, the response will contain the collection’s ID that is needed in Bill API, split payment info and fields */
	{
		$api_url = $this->endpoint.'collections/';

		$reqType = 'POST';

		// REQUIRED PARAMS
		$data = array(
			'title' => $this->input->post('collectionName') // The collection title. Will be displayed on bill template. String format.
		);

		// OPTIONAL PARAMS
		$optData = array(
			'logo'							=> $this->input->post('logo'), // This image will be resized to avatar (40x40) and thumb (180x180) dimensions. Whitelisted formats are jpg, jpeg, gif and png.
			'split_payment[email]'			=> $this->input->post('split_email'), // The email address of the split payment’s recipient. (The account must be a verified account.)
			'split_payment[fixed_cut]'		=> $this->input->post('split_fixed'), // A positive integer in the smallest currency unit that is going in your account (e.g 100 cents to charge RM 1.00). This field is required if split_payment[variable_cut] is not present.
			'split_payment[variable_cut]'	=> $this->input->post('split_var') // Percentage in positive integer format that is going in your account. This field is required if split_payment[fixed_cut] is not present.
		);

		$this->runCurl($api_url, $reqType, $data);
	}

	function getCollectionData()
	/* Use this API to query your collection record. */
	{
		// REQUIRED PARAMS 
		$collection_id = $this->input->post('itemID'); // The collection ID. A string.
 
		$api_url = $this->endpoint.'collections/'.$collection_id;
		
		$reqType = 'GET';

		$this->runCurl($api_url, $reqType);
	}

	function getAllCollectionData()
	/* Use this API to retrieve your collections list. */
	{
		$api_url = $this->endpoint.'collections/';

		// OPTIONAL PARAMS
		$page = ($this->input->post('page')) ? $this->input->post('page') : null; // Up to 15 collections will be returned in a single API call per specified page. Default to 1 if not present.
		$optData['status'] = ($this->input->post('status')) ? $this->input->post('status') : null; // Parameter to filter collection's status, valid value are active and inactive.

		if ($page != null) $api_url = $api_url."?page=".$page;

		$reqType = 'GET';

		$this->runCurl($api_url, $reqType, null, $optData);
	}

	function createNewOpenCollection()
	/* Billplz API supports creation of open collections (Payment Form) with split payment feature, the response will contain the collection’s attributes, including the payment form URL. */
	{
		$api_url = $this->endpoint.'open_collections/';

		$reqType = 'POST';

		// REQUIRED PARAMS
		$data = array(
			'title' => ($this->input->post('name')) ? $this->input->post('name') : null, // The collection title. Will be displayed on payment form. String format. (Max of 50 characters)
			'description' => ($this->input->post('desc')) ? $this->input->post('desc') : null, // The collection description. Will be displayed on payment form. String format. (Max of 200 characters)
			'amount' => ($this->input->post('amount')) ? $this->input->post('amount') : null // A positive integer in the smallest currency unit.
		);

		// OPTIONAL PARAMS
		$optData = array(
			'fixed_amount'					=> $this->input->post('fixed_amount'),
			'fixed_quantity'				=> $this->input->post('fixed_quantity'),
			'payment_button'				=> $this->input->post('payment_button'),
			'reference_1_label'				=> $this->input->post('reference_1_label'),
			'reference_2_label'				=> $this->input->post('reference_2_label'),
			'email_link'					=> $this->input->post('email_link'),
			'tax'							=> $this->input->post('tax'),
			'photo'							=> $this->input->post('photo'),
			'split_payment[email]'			=> $this->input->post('split_email'),
			'split_payment[fixed_cut]'		=> $this->input->post('split_fixed'),
			'split_payment[variable_cut]'	=> $this->input->post('split_var')
		);
		
		$this->runCurl($api_url, $reqType, $data);
	}

	function getAllOpenCollectionData()
	/* Use this API to retrieve your open collections list. */
	{
		$api_url = $this->endpoint.'open_collections/';

		// OPTIONAL PARAMS
		$page = ($this->input->post('page')) ? $this->input->post('page') : null; // Up to 15 collections will be returned in a single API call per specified page. Default to 1 if not present.
		$optData['status'] = ($this->input->post('status')) ? $this->input->post('status') : null; // Parameter to filter collection's status, valid value are active and inactive.

		if ($page != null) $api_url = $api_url."?page=".$page;

		$reqType = 'GET';

		$this->runCurl($api_url, $reqType, null, $optData);
	}

	function activateCollection()
	/*  It will return "message: {COLLECTION_ID} cannot be activated." if you trying to activate an active collection. */
	{
		// REQUIRED PARAMS
		$collection_id = $this->input->post('itemID'); // The collection ID. A string.

		$api_url = $this->endpoint."collections/".$collection_id."/activate";

		$reqType = 'POST';

		$this->runCurl($api_url, $reqType);
	}

	function deactivateCollection()
	/*  It will return "message: {COLLECTION_ID} cannot be deactivated." if you trying to deactivate an inactive collection. */
	{
		// REQUIRED PARAMS
		$collection_id = $this->input->post('itemID'); // The collection ID. A string.

		$api_url = $this->endpoint."collections/".$collection_id."/deactivate";

		$reqType = 'POST';
		
		$this->runCurl($api_url, $reqType);
	}


	/* ******************************************************** BILL ******************************************************** */


	function createNewBill()
	/* To create a bill, you would need the collection’s ID. Each bill must be created within a collection. To get your collection ID, visit the collection page on your Billplz account. */
	{	
		$api_url = $this->endpoint.'bills/';

		$reqType = 'POST';

		// REQUIRED PARAMS
		$data = array(
			'collection_id' => $this->input->post('itemID'), // The collection ID. A string.
			'email' 		=> $this->input->post('email'), // The email address of the bill’s recipient. (Email is required if mobile is not present.)
			'mobile' 		=> $this->input->post('mobile'), // Recipient’s mobile number. Format is +601XXXXXXXX OR 601XXXXXXXX (Mobile is required if email is not present).
			'name' 			=> $this->input->post('name'), // Bill’s recipient name. Useful for identification on recipient part.
			'amount' 		=> $this->input->post('amount'), // A positive integer in the smallest currency unit (e.g 100 cents to charge RM 1.00)
			'description' 	=> $this->input->post('desc'), // The bill's description. Will be displayed on bill template. String format. (Max of 200 characters)
			'redirect_url'	=> $this->input->post('redirect_url'), // URL to redirect the customer after payment completed. It will do a GET to redirect_url together with bill’s status and ID.
			'callback_url' 	=> $this->input->post('callback_url') // Web hook URL to be called after payment’s transaction completed. It will POST a Bill object.
		);

		//OPTIONAL PARAMS
		$optData = array(
			//'due_at'			=> ($this->input->post('due_at')) ? $this->input->post('due_at') : null, // Due date for the bill. The format YYYY-MM-DD, default value is today.
			'deliver'			=> ($this->input->post('deliver')) ? $this->input->post('deliver') : null, // Boolean value to set email and SMS (if mobile is present) delivery. Default value is false.
			'reference_1_label'	=> ($this->input->post('reference_1_label')) ? $this->input->post('reference_1_label') : null, // Label #1 to reconcile payments (Max of 20 characters). Default value is Reference 1.
			'reference_1'		=> ($this->input->post('reference_1')) ? $this->input->post('reference_1') : null, // Value for reference_1_label (Max of 120 characters)
			'reference_2_label'	=> ($this->input->post('reference_2_label')) ? $this->input->post('reference_2_label') : null, // Label #2 to reconcile payments (Max of 20 characters). Default value is Reference 2.
			'reference_2'		=> ($this->input->post('reference_2')) ? $this->input->post('reference_2') : null // Value for reference_2_label (Max of 120 characters)
		);

		$this->runCurl($api_url, $reqType, $data, $optData);
	}

	function getBillData()
	/* At any given time, you can request a bill to check on the status. It will return the bill object. */
	{
		// REQUIRED PARAMS
		$bill_id = $this->input->post('billID'); // Bill ID returned in Bill object

		$api_url = $this->endpoint.'bills/'.$bill_id;

		$reqType = 'GET';

		$this->runCurl($api_url, $reqType);
	}

	function deleteBill()
	/* Only due or overdue bill can be deleted. Paid bill can’t be deleted. Deleting a bill is useful in a scenario where there’s a time limitation to payment. */
	{
		// REQUIRED PARAMS
		$bill_id = $this->input->post('billID'); // Bill ID returned in Bill object

		$api_url = $this->endpoint.'bills/'.$bill_id;

		$reqType = 'DELETE';

		$this->runCurl($api_url, $reqType);
	}


	// ************** BANK ACCOUNT VERIFICATION **************


	function verifyBankAcc()
	/* At any given time, you can request to check on a registration status by bank account number. Possible states of response are verified, unverified and not found.*/
	{
		// REQUIRED PARAMS
		$bank_acc_num = $this->input->post('bankAccNo');

		$api_url = $this->endpoint.'check/bank_account_number/'.$bank_acc_num;

		$reqType = 'GET';

		$this->runCurl($api_url, $reqType);
	}


	/* ************** CURL FUNCTION ************** */


	private function runCurl($api_url, $reqType, $data=null, $optData=null)
	{
		$required = null;
		$optional = null;
		
		if ($data != null)    { foreach ($data as $key => $value) 	 { $required .= $key."=".$value.'&'; } }
		if ($optData != null) { foreach ($optData as $key => $value) { $optional .= $key."=".$value.'&'; } }

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $api_url);
		curl_setopt($ch, CURLOPT_USERPWD, $this->api_key);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

		if 		(strtolower($reqType) == 'get')		{ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); } 
		elseif 	(strtolower($reqType) == 'delete')	{ curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); } 
		else 										{ curl_setopt($ch, CURLOPT_POST, 1); }

		if($required != null || $optData != null){
			$fields = ($optional) ? rtrim($required.$optional, '&') : rtrim($required, '&');
			
			curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
		}

		$result = curl_exec($ch);

		if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); }

		curl_close($ch);

		print_r($result);

		$return = json_decode($result, true);
	}
}
