<?php
/*
* Plugin Name: Dusupay
* Plugin URI: https://dusupay.com
* Description: Dusupay woocommerce payment gateway by dusupay
* Version: 2.0.6
* Author:Dusupay - Hillary Namanya
* Author URI: https://dusupay.com
* License: GPLv2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
* API DOCS: https://dusupay.com/docs
*/

function dusupay_enqueue_stylesheets() { 
    // Load other stylesheets 
    wp_enqueue_style( 'dusupay-bootstrap', plugins_url('/css/bootstrap.min.css', __FILE__) ); 
    wp_enqueue_style( 'dusupay-slimselect', plugins_url('/css/slimselect.min.css', __FILE__) );
    wp_enqueue_style( 'dusupay-pay-widget', plugins_url('/css/pay-widget.css', __FILE__) );

   wp_enqueue_script( 'dpay-bootstrap', plugins_url('/js/bootstrap.min.js', __FILE__) , array(), false, true);
   wp_enqueue_script( 'dpay-slimselect', plugins_url('/js/slimselect.min.js', __FILE__) , array(), false, true);
   wp_enqueue_script( 'dpay', plugins_url('/js/dusupay.js', __FILE__) , array(), false, true);

}
add_action( 'wp_enqueue_scripts', 'dusupay_enqueue_stylesheets' );


add_action('plugins_loaded', 'dusupay', 0);
function dusupay(){
	if(!class_exists('WC_Payment_Gateway')) return;

	class WC_Dusupay extends WC_Payment_Gateway{

		public function __construct(){
			$this->id = 'dusupay';
			$this->icon = plugins_url('/img/logo.png', __FILE__);
		  	$this->method_title = 'Dusupay';
		  	$this->has_fields = false;
			  $this->method_description = sprintf( 'Dusupay is the easiest way to collect payments from customers anywhere in the world. <a href="%1$s" target="_blank">Register</a> for a merchant account and get your API key.', 'https://dusupay.com');


			$this->init_protocol();
			$this->defaultWebhookUrl = WC()->api_request_url( 'WC_Dusupay_Webhook' );

			$this->init_form_fields();
			$this->init_settings();		
			$this->title = $this->settings['title'];
		    $this->description = $this->settings['description'];
		    $this->logo = $this->settings['logo'];
			$this->pub_key = $this->settings['pub_key'];
			$this->business_name = $this->settings['business_name'];
			$this->webhook_url = $this->settings['webhook_url'];
			$this->webhook_hash = $this->settings['webhook_hash'];
			$this->payment_options = $this->settings['payment_options'];
		    $this->api_collection_url = $this->settings['api_collection_url'];

		    $this->msg['message'] = "";
		    $this->msg['class'] = "";

		    add_action('init', array(&$this, 'check_dusupay_response'));
		    if (version_compare( WOOCOMMERCE_VERSION, '2.0.0', '>=' )) {
		      add_action('woocommerce_update_options_payment_gateways_'.$this->id, array( &$this, 'process_admin_options' ));
		    } else {
		      add_action( 'woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ) );
		    }

			add_action( 'admin_notices', array( $this, 'admin_notices' ) );
		    add_action('woocommerce_receipt_dusupay', array(&$this, 'receipt_page'));
		    add_action('woocommerce_dusupay_widget', array(&$this, 'widget_page'));
			add_action( 'woocommerce_api_wc_redirectpage', array($this, 'redirectpage' ) );
			add_action( 'woocommerce_api_wc_requestpayment', array($this, 'request_payment' ) );
			add_action( 'woocommerce_api_wc_checkorderstatus', array($this, 'check_order_status' ) );

			add_action( 'woocommerce_api_wc_dusupay_webhook', array( $this, 'dusupayipn' ) );

		}

		/**
		 * Check if Dusupay merchant details is filled
		 */
		public function admin_notices() {

			if ( 'no' === $this->enabled ) {
				return;
			}

			if ( ! ( $this->pub_key ) ) {
				echo '<div class="error"><p>' . sprintf( 'Please enter your dusupay merchant account Pub Key  <a href="%s">here</a> to be able to use the Dusupay WooCommerce plugin.', admin_url( 'admin.php?page=wc-settings&tab=checkout&section=dusupay' ) ) . '</p></div>';
				return;
			}

			if ( ! ( $this->webhook_url ) ) {
				echo '<div class="error"><p>' . sprintf( 'Please enter the dusupay webhook_url generated for your store  <a href="%s">here</a> to be able to use the Dusupay WooCommerce plugin.', admin_url( 'admin.php?page=wc-settings&tab=checkout&section=dusupay' ) ) . '</p></div>';
				return;
			}

			if ( ! ( $this->webhook_hash ) ) {
				echo '<div class="error"><p>' . sprintf( 'Please enter your dusupay merchant account webhook hash  <a href="%s">here</a> to be able to use the Dusupay WooCommerce plugin.', admin_url( 'admin.php?page=wc-settings&tab=checkout&section=dusupay' ) ) . '</p></div>';
				return;
			}

			if ( ! ( $this->api_collection_url ) ) {
				echo '<div class="error"><p>' . sprintf( 'Please enter the dusupay collections api url  <a href="%s">here</a> to be able to use the Dusupay WooCommerce plugin.', admin_url( 'admin.php?page=wc-settings&tab=checkout&section=dusupay' ) ) . '</p></div>';
				return;
			}

			if ( ! ( $this->payment_options ) ) {
				echo '<div class="error"><p>' . sprintf( 'Please enter the dusupay payment options/methods to allow url  <a href="%s">here</a> to be able to use the Dusupay WooCommerce plugin.', admin_url( 'admin.php?page=wc-settings&tab=checkout&section=dusupay' ) ) . '</p></div>';
				return;
			}

			@$paymentOptions = json_decode($this->payment_options);
			if(empty($paymentOptions)){
				echo '<div class="error"><p>' . sprintf( 'Please set at-least one payment option/method in the json config string  <a href="%s">here</a> to be able to use the Dusupay WooCommerce plugin.', admin_url( 'admin.php?page=wc-settings&tab=checkout&section=dusupay' ) ) . '</p></div>';
				return;
			}
		}

		function init_protocol(){
			$this->protocol = 'http';
	    	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') $this->protocol = 'https';

			return $this->protocol;
		}

		function init_form_fields(){
			if(!empty($_GET['dusupay_transactionReference'])){
		        $order_id=sanitize_text_field($_GET['order']);
		        $order = new WC_Order( $order_id );
		        $order -> update_status('completed');
		        echo $return_url;
		        $return_url = $order->get_checkout_order_received_url();
		        wp_redirect($return_url);
		    }

			
			$defaultPaymentOptions = array(
				array(
					'country'=> 'UG',
					'country_name' => 'Uganda',
					'options'=> array(
						array(
							'id'=>'mtn_ug',
							'name'=>'MTN Mobile Money',
							'type'=>'MOBILE_MONEY'
						),
						array(
							'id'=>'airtel_ug',
							'name'=>'Airtel Money',
							'type'=>'MOBILE_MONEY'
						),
						array(
							'id'=>'international_ugx',
							'name'=>'International UGX Card',
							'type'=>'CARD'
						),
					)
				),
				array(
					'country'=> 'KE',
					'country_name' => 'Kenya',
					'options'=> array(
						array(
							'id'=>'mpesa_ke',
							'name'=>'MPesa',
							'type'=>'MOBILE_MONEY'
						),
						array(
							'id'=>'international_kes',
							'name'=>'International KES Card',
							'type'=>'CARD'
						),
					)
				),
				array(
					'country'=> 'CM',
					'country_name' => 'Cameroon',
					'options'=> array(
						array(
							'id'=>'mtn_cm',
							'name'=>'MTN Mobile Money',
							'type'=>'MOBILE_MONEY'
						),
					)
				),
				array(
					'country'=> 'RW',
					'country_name' => 'Rwanda',
					'options'=> array(
						array(
							'id'=>'mtn_rw',
							'name'=>'MTN Mobile Money',
							'type'=>'MOBILE_MONEY'
						),
					)
				),
				array(
					'country'=> 'GH',
					'country_name' => 'Ghana',
					'options'=> array(
						array(
							'id'=>'mtn_gh',
							'name'=>'MTN Mobile Money',
							'type'=>'MOBILE_MONEY'
						),
						array(
							'id'=>'tigo_gh',
							'name'=>'Tigo Mobile Money',
							'type'=>'MOBILE_MONEY'
						),
						array(
							'id'=>'vodafone_gh',
							'name'=>'Vodafone Mobile Money',
							'type'=>'MOBILE_MONEY'
						),
						array(
							'id'=>'international_ghs',
							'name'=>'International GHS Card',
							'type'=>'CARD'
						),
					)
				),
				array(
					'country'=> 'NG',
					'country_name' => 'Nigeria',
					'options'=> array(
						array(
							'id'=>'bank_ng',
							'name'=>'Bank Account',
							'type'=>'BANK'
						),
						array(
							'id'=>'local_ngn',
							'name'=>'Local Mastercard/Verve',
							'type'=>'CARD'
						),
						array(
							'id'=>'international_ngn',
							'name'=>'International NGN Card',
							'type'=>'CARD'
						),
					)
				),
				array(
					'country'=> 'ZA',
					'country_name' => 'South Africa',
					'options'=> array(
						array(
							'id'=>'bank_za',
							'name'=>'Bank Account',
							'type'=>'BANK'
						),
					)
				),
				array(
					'country'=> 'US',
					'country_name' => 'Other',
					'options'=> array(
						array(
							'id'=>'international_usd',
							'name'=>'Visa/Mastercard',
							'type'=>'CARD'
						),
					)
				),
			);

		    $this->form_fields = array(
		        'enabled' => array(
		            'title' => __('Enable/Disable'),
		            'type' => 'checkbox',
		            'label' => __('Enable Dusupay.'),
					'description' => __( 'Enable Dusupay as a payment option on the checkout page.' ),
		            'default' => 'no',
					'desc_tip'    => true,
		        ),
		        'title' => array(
		            'title' => __('Title:'),
		            'type'=> 'text',
		            'description' => __('This controls the payment method title which the user sees during checkout.'),
		            'default' => __('Dusupay'),
					'desc_tip'    => true,
		        ),
		        'description' => array(
		            'title' => __('Description:'),
		            'type' => 'textarea',
		            'description' => __('Pay with Dusupay.com'),
		            'default' => __('Pay with Mobile Money, Cards and Banks'),
					'desc_tip'    => true,
		        ),
		        'business_name' => array(
		            'title' => __('Store Name'),
		            'type' => 'text',
		            'description' => __('This will be displayed for on the payment widget'),
					'desc_tip'    => true,
		        ),
		        'webhook_url' => array(
					'title' => __('Webhook Url'),
					'type' => 'text',
					'description' => __('Set this url as the webhook url under your dusupay merchant account, api settings for transactions to be completed.'),
					'default' => __($this->defaultWebhookUrl),
				),
				'pub_key' => array(
					'title' => __('Public Key'),
					'type' => 'text',
					'description' => __('Get your public key. Get it from your api settings.'),
				),
				'webhook_hash' => array(
					'required' => 'yes',
		            'title' => __('Webhook hash'),
		            'type' => 'text',
					'desc_tip'    => true,
		            'description' => __('Add a random token here, similar to that added to your merchant account api settings to secure payment notifications. Read more about it from the api docs.')
		        ),
				'payment_options' => array(
		            'title' => __('Payment Options'),
		            'type' => 'text',
		            'description' => __('This is a json config. To add more options, use a json editor and make sure the result is a valid json string.'),
					'default' => json_encode($defaultPaymentOptions),
					'desc_tip'    => true,
		        ),
		        'logo' => array(
		            'title' => __('Display logo'),
		            'type' => 'text',
		            'default'=>plugins_url('/img/logo.png', __FILE__),
					'desc_tip'    => true,
		            'description' => __('Full URL of logo to be displayed by dusupay<br>125px X 125px Square Logo Recommended')
		        ),
				'api_collection_url' => array(
		            'title' => __('Collection Api'),
		            'type' => 'text',
		            'description' => __('Live: https://api.dusupay.com/v1/collections <br> Sandbox: https://sandbox.dusupay.com/v1/collections'),
					'default' => ('https://api.dusupay.com/v1/collections'),
		        ),
		    );
		}

		public function admin_options(){
			echo '<div class="notice">';
			echo '<h3>'.__('Dusupay Payment Gateway').'</h3>';
		    echo '<p>'.__('Dusupay is a very popular payment gateway for online shopping in world with multiple payment options. Your customer will have all reason to pay you.').'</p>';
		    echo "</div>";
			?>

			<div class="notice notice-info">
				<h4>Set your webhook URL to the URL below<strong style="color: red"><pre><code><?php echo WC()->api_request_url( 'WC_Dusupay_Webhook' ); ?></code></pre></strong></h4>
				<h5>Set it under your merchant account > Settings > Api Settings</h5>
			</div>

			<?php
			
			echo '<table class="form-table">';
		    $this -> generate_settings_html();
		    echo '</table>';
		}

		function receipt_page($order){

			if(empty($this->webhook_hash)){
				echo "<h4>Dusupay: Webhook Hash should be set</h4>";
				return;
			}
			
			if(empty($this->payment_options)){
				echo "<h4>Dusupay: Webhook Hash should be set</h4>";
				return;
			}

			@$options = json_encode($this->payment_options);
			if(empty($options)){
				echo "<h4>Dusupay: Invalid payment options config!</h4>";
				return;
			}

			if(empty($this->api_collection_url)){
				echo "<h4>Dusupay: Collection api is not set!</h4>";
				return;
			}

			if(empty($this->api_collection_url)){
				echo "<h4>Dusupay: Collection api is not set!</h4>";
				return;
			}
			
			echo $this->get_payment_button($order);
	    }

		function widget_page($order){
			echo $this->get_payment_widget($order);
		}

		function check_order_status(){

			// sleep(5);

			$order_id = sanitize_text_field($_GET['txnid']);
			$order_id = explode('WC', $order_id);
	        $order_id = (int)$order_id[0];
		    $order = wc_get_order( $order_id );

			
			if(empty($order)){
				exit ('Order not found!');
			}
			

			wp_redirect( $this->get_return_url( $order ) );
			// if ( in_array( $order->get_status(), array( 'processing', 'completed', 'on-hold' ) ) ) {
				// wp_redirect( $this->get_return_url( $order ) );
			// }
			exit;
		}

		function request_payment(){

			$order_id = $title = sanitize_text_field($_GET['txnid']);
			$order_id = explode('WC', $order_id);
	        $order_id = (int)$order_id[0];
		    $order = wc_get_order( $order_id );

			if(empty($order)){
				exit(json_encode([
					'status' => false,
					'msg' => "Order not found!"
				]));
			}
			
			if(strtolower($order->get_status()) != 'pending'){
				// global $woocommerce;
				// $woocommerce->cart->empty_cart();
				exit(json_encode([
					'status' => false,
					'msg' => "Order is already " . $order->get_status(),
				]));
			}

			$requestData = [ 
				"api_key" => $this->pub_key, 
				"currency"=> $order->get_currency(), 
				"amount"=> $order->get_total() * 1,
				"method"=> strtoupper(sanitize_text_field($_GET['mth'])), 
				"provider_id"=> sanitize_text_field($_GET['ntk']),
				"account_number"=> sanitize_text_field($_GET['phn']),
				"merchant_reference"=> sanitize_text_field($_GET['txnid']), 
				"narration"=> "Payment for order #" . $order_id,
				"account_name"=> sanitize_text_field($_GET['nam']),
				"account_email"=> sanitize_text_field($_GET['ema'])
			];

			if(!empty($_GET['vch'])){
				$requestData['voucher'] = sanitize_text_field($_GET['vch']);
			}

			$redirect_url = WC()->api_request_url( 'WC_Checkorderstatus' ). '?txnid=' . sanitize_text_field($_GET['txnid']);
			if(in_array($requestData['method'], ['CARD', 'BANK'])){
				$requestData['redirect_url'] = $redirect_url;
			}

			$resp = $this->httpPost($this->api_collection_url, $requestData);

			if(empty($resp) || empty($resp["code"])){
				exit(json_encode(['status' => false, 'msg' => "Gateway Request Failed!"]));
			}

			if(!in_array($resp["code"], [200, 202])){
				exit(json_encode(['status' => false, 'msg' => $resp["message"]]));
			}

			
			$transactionCompleted = false;
			if(in_array($resp["data"]["transaction_status"], ["PENDING"])){
				$transactionCompleted = true;
				$order-> add_order_note("dusupay_reference:" . $resp["data"]["internal_reference"]);
				$order-> add_order_note("dusupay_charge:" . ($resp["data"]['transaction_fee'] . ' ' . $resp["data"]['account_currency']));
			}

			if(!empty($resp["data"]['payment_url'])){
				$redirect_url = $resp["data"]['payment_url'];
			}

			exit(json_encode([
				'status' => $transactionCompleted, 
				'msg' => $resp["message"], 
				'redirect'=> $redirect_url
			]));
		}
		
		function get_payment_status($order_id){

			$order_id = explode('WC', $order_id);
	        $order_id = (int)$order_id[0];
		    $order = wc_get_order( $order_id );

			echo json_encode([
				'status' => $order->status
			]);
		}

		public function get_payment_button($order_id){
			$dusupay_redirectURL = WC()->api_request_url( 'WC_Redirectpage' ) ."?order_id=".$order_id;
			ob_start();
			?>

			<form id='dusupayBtn' method="post" action="<?php echo $dusupay_redirectURL; ?>" target="_self">
				<input type="image" name="submit" src="<?php echo plugins_url('/img/dusupaybtn6.png', __FILE__) ?>" />
			</form>

			<?php
			$dusupay_button = ob_get_clean();
	    	return $dusupay_button;
		}

	    function get_payment_widget($order_id){

	    	$order = wc_get_order( $order_id );
	    	$dusupay_transactionReference = $order_id.'WC'.date("ymds");
	    	$dusupay_amount = $order->get_total();
	    	$dusupay_currency = $order->get_currency();
	    	$dusupay_logo = $this->logo;

	    	ob_start();
	    	?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Dusupay Payment</title>
    <?php wp_head();?>
</head>
<body>
	<div class="loader-widget">       
         <img style="display:inline" src="<?php echo plugins_url('/img/images/ring-alt.svg', __FILE__)?>">
     </div><!-- end loader -->
    <div class="widget-wrap">
        <div class="container">
            <div class="col-md-6 offset-md-3">
                <div class="widgetbox">
					<div class="company-logo payment-logo">
						<img src="<?php echo $this->logo;?>" class="img-responsive" />
					</div><!-- end compnay-logo -->

					<div class="widget-header">
						<div class="merchant col-md-12">
							<span class="widget-merchant-name"><?php echo $this->business_name?></span>
							<span class="widget-item-price" style="padding: 0px 0px 5px 0px;"><b><?php echo $dusupay_amount; ?> <?php echo $dusupay_currency; ?></b></span>
						</div>
					</div><!-- end widget-header -->

                    <div class="widget-form-holder">
						<?php 
							@$paymentOptions = json_decode($this->payment_options);
							if(empty($paymentOptions)) echo 'No Payment Options. Please correct your json format!';
						?>
						<script>
							var paymentOptions = JSON.parse('<?php echo $this->payment_options?>');
							var collectionUrl= "<?php echo (WC()->api_request_url( 'WC_Requestpayment' )."?txnid=" . $dusupay_transactionReference);?>";
						</script>
						<div class="widget-error" style="color: red;font-size: 1rem;"></div>
			
						<form id="form1">
							<select class="selectpicker" id="countrypicker">
								<option value="" selected disabled>select country</option>
							<?php 
								$paymentCountries = [];
								foreach($paymentOptions as $key=>$paymentOption){
							?>
								<option value="<?php echo $key?>"><?php echo $paymentOption->country_name?></option>
							<?php }?>

							</select>
							<button type="submit" class="btn btn-block btn-purple-lg pay-btn clickx">
								next
							</button>
						</form>

						<form id="form2" style="display:none;">
							<div class="widget-note" style="border: none;padding: 10px;">
								<span onclick="$('#form2').hide();$('#form1').fadeIn();" style="display: inline;cursor: pointer;" title="Back"><i class="glyphicon glyphicon-arrow-left"></i></span> 
								<span class="countryDescription" style="display: inline;margin-left:5px;"></span>
							</div>
							<div class="providerpicker-container"></div>
							<button type="submit" class="btn btn-block btn-purple-lg pay-btn clickx">
								next
							</button>
						</form>

						<form id="form3" style="display:none;">
							<div class="widget-note" style="border: none;padding: 10px;">
								<span onclick="$('#form3').hide();$('#form2').fadeIn();" style="display: inline;cursor: pointer;" title="Back"><i class="glyphicon glyphicon-arrow-left"></i></span> 
								<span class="providerDescription" style="display: inline;margin-left:5px;"></span>
							</div>
							<div class="widget-divide row voucher-input" style="display:none;">
								<div style="font-size:1.3rem;padding: 2px 10px;color: #fff;background: #777;margin: 3px 15px;border-radius: 5px;">
									Dial <b>'*110#'</b> to generate transaction voucher
								</div>
								<div class="col-md-12"> 
									<input name="voucher" class="form-control" placeholder="voucher" type="text" id="cust-voucher" required="required" />
									<span class="icon-input"><i class="icon-phone"></i></span>
								</div>
							</div>
							<div class="widget-divide row">
								<div class="col-md-12"> 
									<input name="phone" class="form-control" placeholder="Phone number e.g 256777111777" type="number" id="cust-phone" required="required" />
									<span class="icon-input"><i class="icon-phone"></i></span>
								</div>
							</div><!-- end widget-divide --> 

							<div class="widget-divide row">
								<div class="col-md-12"> 
									<input name="name" class="form-control" placeholder="Your Name" value="<?php echo $order->get_billing_last_name() . ' ' . $order->get_billing_first_name()?>" type="text" id="cust-name" />
									<span class="icon-input"><i class="icon-user"></i></span>
								</div>
							</div><!-- end widget-divide --> 

							<div class="widget-divide row">
								<div class="col-md-12"> 
									<input name="email" class="form-control" placeholder="Your Email" value="<?php echo $order->get_billing_email()?>" type="email" id="cust-email" />
									<span class="icon-input"><i class="icon-mail"></i></span>
								</div>
							</div><!-- end widget-divide --> 


							<div id="payment-btn">
								<button id="btn-submit-payment" type="submit" class="btn btn-block btn-purple-lg">Pay</button>
							</div>

						</form>
                    </div>
                    <!-- end widget-form-holder -->

                    <div class="widget-powered">
                        Powered by DusuPay
                    </div>
                    <!-- widget-power -->
                </div>
            </div>
        </div>
    </div>
<?php wp_footer(); ?>
</body>
</html>
			    
	    	<?php
	    	$dusupay_widget = ob_get_clean();
	    	return $dusupay_widget;
	    }

		function process_payment($order_id){

		    $order = wc_get_order( $order_id );

			return array(
				'result'   => 'success',
				'redirect' => $order->get_checkout_payment_url( true ),
			);
	    }

		function redirectpage(){
			$this->widget_page(sanitize_text_field($_GET['order_id']));
			exit;
		}


		function dusupayipn() {
			if ( ( strtoupper( $_SERVER['REQUEST_METHOD'] ) != 'POST' ) ) {
				header('HTTP/1.1 400 POST Expected!');
				exit;
			}

			$body = @file_get_contents( 'php://input' );

			if ( $this->isJSON( $body ) ) {
				$_POST = (array) json_decode( $body );
			}

			$order_id = null;
		    $dusupay_transactionReference = null;

			if(empty($_SERVER['HTTP_WEBHOOK_HASH'])){
				header('HTTP/1.1 400 Missing Webhook hash!');
				exit();
			}

			if($_SERVER['HTTP_WEBHOOK_HASH'] != $this->webhook_hash){
				header('HTTP/1.1 403 Invalid Webhook hash!');
				exit();
			}

			$ipn = file_get_contents('php://input');
			@$ipn = json_decode($ipn);

			if(empty($ipn)){
				header('HTTP/1.1 400 IPN is invalid');
				exit();
			}
			

			$order_id = $ipn->merchant_reference;
			if (empty($order_id)) {
				header('HTTP/1.1 403 Invalid Request');
				exit();
			}

			$order_id = explode('WC', $order_id);
	        $order_id = (int)$order_id[0];
			$order = wc_get_order( $order_id );
			$order_total = $order->order_total;
			// $order_currency = strtoupper(trim(get_woocommerce_currency()));
			$order_currency = $order->get_currency();

			if(in_array(strtoupper($ipn->transaction_status), ['COMPLETED'])){
				if ( in_array( $order->get_status(), array( 'processing', 'completed', 'on-hold' ) ) ) {
					exit();
				}

				// check if the amount paid is equal to the order amount.
				if ( $ipn->request_amount < $order_total ) {
					$order->update_status( 'on-hold', '' );
					update_post_meta( $order_id, '_dusupay_id', $ipn->id );
					update_post_meta( $order_id, '_dusupay_reference', $ipn->internal_reference );

					$notice      = 'Thank you for shopping with us.<br />Your payment was successful, but the amount paid is not the same as the total order amount.<br />Your order is currently on-hold.<br />Kindly contact us for more information regarding your order and payment status.';
					$notice_type = 'notice';

					// Add Customer Order Note
					$order->add_order_note( $notice, 1 );

					// Add Admin Order Note
					$order->add_order_note( '<strong>Look into this order</strong><br />This order is currently on hold.<br />Reason: Amount paid is less than the total order amount.<br />Amount Paid was <strong>' . $ipn->request_currency . ' ' . $ipn->request_amount . '</strong> while the total order amount is <strong>' . $order_currency . ' ' . $order_total . '</strong><br /><strong>Transaction ID:</strong> ' . $ipn->id . ' | <strong>Payment Reference:</strong> ' . $ipn->internal_reference );

					wc_reduce_stock_levels( $order_id );

					wc_add_notice( $notice, $notice_type );

					exit();
				}

				// check if the currency paid is equal to the order currency.
				if ( $ipn->request_currency !== $order_currency ) {

					$order->update_status( 'on-hold', '' );

					update_post_meta( $order_id, '_dusupay_id', $ipn->id );
					update_post_meta( $order_id, '_dusupay_reference', $ipn->internal_reference );

					$notice      = 'Thank you for shopping with us.<br />Your payment was successful, but the payment currency is different from the order currency.<br />Your order is currently on-hold.<br />Kindly contact us for more information regarding your order and payment status.';
					$notice_type = 'notice';

					// Add Customer Order Note
					$order->add_order_note( $notice, 1 );

					// Add Admin Order Note
					$order->add_order_note( '<strong>Look into this order</strong><br />This order is currently on hold.<br />Reason: Order currency is different from the payment currency.<br /> Order Currency is <strong>' . $order_currency . ' </strong> while the payment currency is <strong>' . $ipn->request_currency . ' </strong><br /><strong>Transaction ID:</strong> ' . $ipn->id . ' | <strong>Payment Reference:</strong> ' . $ipn->internal_reference );

					wc_reduce_stock_levels( $order_id );

					wc_add_notice( $notice, $notice_type );

					exit();
				}
				
				$order->payment_complete();
				$order->add_order_note( sprintf( 'Payment via Dusupay successful (<strong>Transaction ID:</strong> %s | <strong>Payment Reference:</strong> %s)', $ipn->id, $ipn->internal_reference ) );
				
			}elseif(in_array(strtoupper($ipn->transaction_status), ['FAILED', 'CANCELLED', 'CANCELED'])){
				$order->update_status( 'failed', $ipn->message);
			}else{
				$order->add_order_note($ipn->transaction_status);
				$order->add_order_note($ipn->message);
			}

			header('HTTP/1.1 200 OK');

	    	exit();
		}

		function httpPost($url, $data){

			$response = wp_remote_post($url, array(
				'headers'     => array('Content-Type' => 'application/json; charset=utf-8'),
				'body'        => json_encode($data),
				'method'      => 'POST',
				'data_format' => 'body',
			));
			
			$body = wp_remote_retrieve_body( $response );
			return $responceData = ( ! is_wp_error( $response ) ) ? json_decode( $body, true ) : null;
			@$resp = json_decode($data, true);

			return $resp;
		}

	    function showMessage($content){
	      return '<div class="box '.$this->msg['class'].'-box">'.$this->msg['message'].'</div>'.$content;
	    }

	    function get_pages($title = false, $indent = true) {
	        $wp_pages = get_pages('sort_column=menu_order');
	        $page_list = array();
	        if ($title) $page_list[] = $title;
	        foreach ($wp_pages as $page) {
	            $prefix = '';
	            if ($indent) {
	                $has_parent = $page->post_parent;
	                while($has_parent) {
	                    $prefix .=  ' - ';
	                    $next_page = get_page($has_parent);
	                    $has_parent = $next_page->post_parent;
	                }
	            }
	            $page_list[$page->ID] = $prefix . $page->post_title;
	        }
	        return $page_list;
	    }

		/**
		 * @param $string
		 *
		 * @return bool
		 */
		public function isJSON( $string ) {
			return is_string( $string ) && is_array( json_decode( $string, true ) ) ? true : false;
		}

		/**
		 * Checks if WC version is less than passed in version.
		 *
		 * @since 2.1.0
		 * @param string $version Version to check against.
		 * @return bool
		 */
		public function is_wc_lt( $version ) {
			return version_compare( WC_VERSION, $version, '<' );
		}
	}

	function woocommerce_add_dusupay($methods) {
    	$methods[] = 'WC_Dusupay';
    	return $methods;
  	}
  	add_filter('woocommerce_payment_gateways', 'woocommerce_add_dusupay' );
}

include_once dirname( __FILE__ ) . '/dusupay_js_css.php';
add_filter( 'plugin_action_links', 'dusupay_get_plugin_action_links', 10, 5 );
function dusupay_get_plugin_action_links( $action_links, $plugin_file ){
	static $plugin;
	if(!isset($plugin)) $plugin = plugin_basename(__FILE__);
	if ($plugin == $plugin_file) {
	    $otherLinks = array(
	        'Register' => '<a href="https://dusupay.com/register" target="_blank">Register</a>',
			'Blog' => '<a href="http://dusupay.com/blog" target="_blank">Blog</a>',
	    );
    	$action_links = array_merge($otherLinks, $action_links);
	}
	return $action_links;
}
?>

