<?php
/**
 * Plugin Name: Aman Payment Gateway for WooCommerce
 * Plugin URI: https://amanaccept.com
 * Description: WooCommerce payment gateway for Aman
 * Version: 2.5.5
 * Author: Aman
 * Author URI: https://amanaccept.com/
 */

if (!defined('ABSPATH')) {
	exit;
}

if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
	exit;
}

define('AMGFW_WC_AMAN_URL', plugins_url('', __FILE__));
define('AMGFW_TEST_URL', 'http://aman-checkout-backend.mimocodes.com/api/v1/create-payment-order');
define('AMGFW_URL', 'http://aman-checkout-backend.mimocodes.com/api/v1/create-payment-order');

function add_aman_gateway_class ( $methods ) {
	$methods[] = 'WC_Gateway_Aman_Bank_Card';
	$methods[] = 'WC_Gateway_Aman_RC_Code';
	return $methods;
}

add_filter('woocommerce_payment_gateways', 'add_aman_gateway_class');

function init_aman_gateway_class () {
	include_once 'gateways/aman_card.php';
	include_once 'gateways/aman_rc_code.php';
}
add_action('plugins_loaded', 'init_aman_gateway_class');

//添加hook钩子，设置回调函数
add_action('woocommerce_api_wc_gateway_aman', 'aman_notify');
function aman_notify() {
	$logger = new WC_Logger();
		$logger->add('aman_payment', 'new log start：hereeeeeeee');
	$str = file_get_contents('php://input');
	$data = json_decode($str, true);
	
	$txt = sprintf("{Amount:\"%s\",Currency:\"%s\",TransactionReference:\"%s\",TransactionFees:\"%s\",TransactionType:\"%s\",OrderReference:\"%s\",PaymentMethod:\"%s\",Status:\"%s\",CreatedAt:\"%s\",UpdatedAt:\"%s\",MerchantReference:\"%s\",customerName:\"%s\",customerPhoneNumber:\"%s\",customerEmail:\"%s\",customerAddress:\"%s\"}",
            $data['amount'], $data['currency'], $data['transactionReference'], $data['transactionFees'], $data['transactionType'], $data['orderReference'], $data['paymentMethod'], $data['status'], $data['createdAt'], $data['updatedAt'], $data['merchantReference'], $data['customerName'], $data['customerPhoneNumber'], $data['customerEmail'], $data['customerAddress']
        );
	$aman_rc_obj = new WC_Gateway_Aman_RC_Code();
	$txt_hash = hash_hmac('sha3-512', ($txt), $aman_rc_obj->get_option('secretkey'));
	
	$logger->add('aman_payment', 'data:'. $str . ',,,,, hash:' . $txt_hash);
	//获取header信息
	if (!isset($txt_hash) || !isset($data['hmac'])) {
		throw new Exception('Unauthenticated');
	}
	
	if (!isset($data['transactionReference'])||!isset($data['orderReference'])) {
		return;
	}
	if ($txt_hash == $data['hmac']) {
    $reference_arr = explode('-',$data['orderReference']);
    $reference = $reference_arr[2];
		$order = new WC_Order($reference);
		try {
			if (!$order) {
				throw new Exception('Unknow Order id:' . $reference);
			}
			if ('success' == strtolower($data['status'])) {
				if ($order->needs_payment()) {
 					$order->update_status('completed');
												$logger->add('aman_payment', 'order：' . $order);

				}
					
			} elseif ('cancelled' == strtolower($data['status']) || 'canceled' == strtolower($data['status'])) {
				if ($order->needs_payment()) {
					$order->update_status('cancelled');
				}
			} elseif ('failed' == strtolower($data['status'])) {
				if ($order->needs_payment()) {
					$order->update_status('failed');
				}
			} elseif ('pending' == strtolower($data['status'])) {
				if ($order->needs_payment()) {
						$order->update_status('pending');
						$logger->add('aman_payment', 'order：' . $order);
				}
			} elseif ('expired' == strtolower($data['status'])) {
				if ($order->needs_payment()) {
					$order->update_status('expired');
				}
			}
		} catch (Exception $e) {
			$params = array(
				'action'=>'fail',
				'errcode'=>$e->getCode(),
				'errmsg'=>$e->getMessage()
			);
			ob_clean();
			print json_encode($params);
			exit;
		}
		$params = array(
			'action'=>'success',
		);
		ob_clean();
		print json_encode($params);
		exit;
	} else {
		$logger->add('aman_payment', 'wrong hmac');
	}
}
