<?php
/**
 * REST API Payment controller
 *
 * Handles requests to the /payment endpoint.
 *
 * @author   QWQ
 * @category API
 * @package  WooCommerce/API
 * @since    2.6.0
 */

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

/**
 * REST API Payment controller class.
 *
 * @package WooCommerce/API
 * @extends WC_REST_Posts_Controller
 */
class W2W_REST_Payment_Controller extends W2W_REST_Posts_Controller {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'w2w/v1';

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'payment';

	
	/**
	 * Initialize payment actions.
	 */
	public function __construct() {
		
	}

	/**
	 * Register the routes for payment.
	 */
	public function register_routes() {
		
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/', array(
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_payment_params' ),
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
				'args'                => $this->get_collection_params(),
			)
		) );

		register_rest_route( $this->namespace, '/' . $this->rest_base . '/notify', array(
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'notify' ),
				'permission_callback' => array( $this, 'get_items_permissions_check' ),
				'args'                => $this->get_collection_params(),
			)
		) );
	}
	
	/**
	 * Check whether a given request has permission to read order notes.
	 *
	 * @param  WP_REST_Request $request Full details about the request.
	 * @return WP_Error|boolean
	 */
	public function get_items_permissions_check( $request ) {
		return true;
	}
	
	// 获取支付参数
	public function get_payment_params( $request ) {
		
		$session = W2W_Util::get_session( $request['w2w_session'] );
		if( ! $session ) return array( 'success' => false, 'msg' => 'Session过期' );
		
		$wc_order = wc_get_order( $request['id'] );
		if( ! $wc_order ) return;
		
		$settings = get_option( 'w2w-settings' );
		$payment_gateway = new W2W_WC_Gateway_HantePay();
		$token = $payment_gateway->get_option( 'token' );
		$description = $payment_gateway->get_option( 'body' );
		
		if( empty( $settings['appid'] ) || empty( $token ) || empty( $description ) ) {
			
			return array( 'success' => false, 'msg' => '请填写AppID和Token' );
		}

		$openid = $session['openid'];
		$url = 'https://api.hantepay.cn/v1.3/transactions/micropay';
		
		$body = array(
			'amount' => intval( strval( floatval( $wc_order->get_total() ) * 100 ) ),
			'currency' => 'USD',
			'reference' => get_post_meta( $wc_order->get_id(), 'w2w_order_number', true ),
			'ipn_url' => get_rest_url( null, $this->namespace . '/' . $this->rest_base . '/notify' ),
			'client_ip' => $this->get_client_ip(),
			'open_id' => $openid,
			'description' => $description
		);

		$response = wp_remote_post( $url, array(
			'method' => 'POST',
			'headers' => array(
				'Content-Type' => 'application/json',
				'Authorization' => 'Bearer ' . $token
			),
			'body' => json_encode( $body )
		) );
		
		if( is_wp_error( $response ) ) {
			return $response;
		}
		
		$response_body = json_decode( $response['body'], true );
		
		$js_api_params = array(
			'success' => true,
			'nonceStr' => $response_body['nonceStr'],
			'paySign' => $response_body['paySign'],
			'timeStamp' => $response_body['timeStamp'],
			'package' => $response_body['wechatPackage'],
		);
		
		// 存储prepay_id
		update_post_meta( $request['id'], 'w2w_prepay_id', str_replace( 'prepay_id=', '', $js_api_params['package'] ) );
		
		return $js_api_params;
	}
	
	// 支付通知
	public function notify( $request ) {
		
		W2W()->log( 'info', '支付通知: ' . json_encode( $_POST ) );
		
		// 更改订单状态
		if( $_POST['status'] == 'success' ) {
			
			$orders = wc_get_orders( array( 'w2w_order_number' => $_POST['reference'] ) );
			
			if( count( $orders ) > 0 ) {
				
				$order = $orders[0];
				
				if( $order->get_status() == 'pending' && $_POST['amount'] == intval( strval( floatval( $wc_order->get_total() ) * 100 ) ) ) {
					$order->payment_complete( $data['id'] );
					do_action( 'w2w_order_paid', $order->get_id() );
				}
				
				echo 'ok';
			}
		}
	}
	
	// 获取客户端IP
	private function get_client_ip() {
		
		$cip = 'unknown';
		if( $_SERVER['REMOTE_ADDR'] ) {
			$cip = $_SERVER['REMOTE_ADDR'];
		}
		elseif( getenv( 'REMOTE_ADDR' ) ) {
			$cip = getenv( 'REMOTE_ADDR' );
		}
		return $cip;
	}
}
