<?php
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * WRE_SPL_Stripe
 */
class WRE_SPL_Stripe extends WRE_SPL_Gateway {

	public static $api_endpoint = 'https://api.stripe.com/';

	/**
	 * __construct function.
	 */
	public function __construct() {
		$this->current_user_id = get_current_user_id();
		add_action( 'wp_ajax_wre_new_subscriber', array( $this, 'wre_new_subscriber_callback' ) );
		add_action( 'wp_ajax_nopriv_wre_new_subscriber', array( $this, 'wre_new_subscriber_callback' ) );
		add_action( 'wre_enqueue_stripe_scripts', array( $this, 'wre_enqueue_stripe_scripts_callback' ), 10 );
		$payment_gateway = wre_option( 'wre_enable_stripe' );
		if( $payment_gateway ) {
			parent::__construct();
		}

		add_action( 'wp_enqueue_scripts', array( $this, 'frontend_scripts' ), 10 );
	}

	public function wre_new_subscriber_callback() {
		$token_id = $_POST['token_id'];
		$package = $_POST['package'];
		$response = self::wre_subscribe_stripe_package( $token_id, $package );
		echo wp_send_json( $response );
		die();
	}
	
	public static function wre_subscribe_stripe_package( $token_id = '', $package = '', $listing_id = '' ) {
		$flag = false;
		$message = '';
		$response = '';
		$redirect_url = '';
		$current_user_id = get_current_user_id();
		$stripe_package_id = wre_package_meta( 'stripe_id', $package );
		$email = self::recipient_email();
		$stripe_api_key = wre_option( 'wre_stripe_secret_key' );
		$package_amount = wre_package_meta( 'price', $package );
		$subscription_period = wre_package_meta( 'subscription_period', $package );
		$subscription_unit = wre_package_meta( 'subscription_unit', $package );
		$user_agent = __( 'WRE_Listings', 'wp-real-estate' );
		$is_charged = false;
		if( $subscription_period && $subscription_unit && $stripe_package_id != '' ) {
			$response = wp_remote_post( self::$api_endpoint . 'v1/customers', array(
				'method'     => 'POST',
				'headers'    => array(
					'Authorization' => 'Basic ' . base64_encode( $stripe_api_key . ':' ),
				),
				'body'       => array(
					'email' => $email,
					'source'  => $token_id,
					'plan' => $stripe_package_id
				),
				'timeout'    => 60,
				'sslverify'  => false,
				'user-agent' => $user_agent,
			) );
		} else {
			$response = wp_remote_post( self::$api_endpoint . 'v1/charges', array(
				'method'     => 'POST',
				'headers'    => array(
					'Authorization' => 'Basic ' . base64_encode( $stripe_api_key . ':' ),
				),
				'body'       => array(
					'amount'        => $package_amount * 100,
					'currency'      => strtolower( wre_option( 'wre_currency_code' ) ),
					'description'   => __( 'Charge for', 'wp-real-estate' ) . ' "' . $email . '"',
					'capture'       => 'true',
					'card'          => $token_id,
					'expand[]'      => 'balance_transaction',
					'receipt_email' => $email,
				),
				'timeout'    => 60,
				'sslverify'  => false,
				'user-agent' => $user_agent,
			) );
			$is_charged = true;
		}

		if( $response != '' ) {
			if ( is_wp_error( $response ) ) {
				$message = __( 'There was a problem connecting to the gateway.', 'wp-real-estate' );
			}

			if ( empty( $response['body'] ) ) {
				$message = __( 'Empty response.', 'wp-real-estate' );
			}

			if( ! $message ) {
				$parsed_response = json_decode( $response['body'] );

				// Handle response
				if ( ! empty( $parsed_response->error ) ) {
					$message = $parsed_response->error->message;
				} elseif ( empty( $parsed_response->id ) ) {
					$message =  __( 'Invalid response.', 'wp-real-estate' );
				} else {
					if( ! $is_charged ) {
						$payment_status = $parsed_response->subscriptions->data[0]->status;
						if( $payment_status == 'trialing' || $payment_status == 'active' ) {
							$payment_status = 'completed';
						}
						$payment_received = $parsed_response->subscriptions->data[0]->plan->amount/100;
					} else {
						$payment_status = $parsed_response->status;
						$payment_received = $parsed_response->amount/100;
					}
					
					$membership_details = array(
						'package_id'		=> $package,
						'listing_id'		=> $listing_id,
						'transaction_id'	=> $parsed_response->id,
						'payment_date'		=> $parsed_response->created,
						'payment_status'	=> strtolower($payment_status),
						'amount_received'	=> $payment_received,
						'payment_type'		=> 'Stripe'
					);
					WRE_SPL_Gateway::wre_update_membership_details( $membership_details );
					$flag = true;
					$redirect_url = wre_get_account_endpoint_page_link('subscription');
				}
			}
		} else {
			$message =  __( 'Something went wrong. Please check your subscription details.', 'wp-real-estate' );
		}

		return array( 'flag' => $flag, 'message' => $message, 'redirect_url' => $redirect_url );
	}

	/**
	 * frontend_scripts function.
	 *
	 * @access public
	 * @return void
	 */
	public function frontend_scripts() {

		wp_enqueue_script( 'wre-stripe', 'https://js.stripe.com/v2/', '', '1.0', true );
		wp_register_script( 'wre-stripe-payment', WRE_PLUGIN_URL . 'assets/js/wre-stripe-payment.js', array( 'jquery', 'wre-stripe' ), '1.0', false );
		wp_register_script( 'stripe-checkout', 'https://checkout.stripe.com/v2/checkout.js', '', '2.0', true );
		wp_register_script( 'wre-spl-stripe', WRE_PLUGIN_URL . 'assets/js/wre-stripe-checkout.js', array( 'jquery', 'wre-stripe' ), '1.0', true );

		// Get email address
		$email = self::recipient_email();
		wp_localize_script( 'wre-spl-stripe', 'stripe_checkout_params', array(
			'key'		=> wre_option( 'wre_stripe_publishable_key' ),
			'label'		=> __( 'Pay for Listing', 'wp-real-estate' ),
			'amount'	=> wre_option( 'wre_listing_amount' ) * 100,
			'currency'	=> strtolower( wre_option( 'wre_currency_code' ) ),
			'name'		=> get_bloginfo( 'name' ),
			'email'		=> $email,
			'ajax_url'	=> admin_url('admin-ajax.php')
		) );
	}
	
	public function wre_enqueue_stripe_scripts_callback() {
		wp_enqueue_script('wre-stripe-payment');
		wp_enqueue_script('stripe-checkout');
		wp_enqueue_script('wre-spl-stripe');
	}
	
	public static function recipient_email() {
		$current_user = wp_get_current_user();
		return $current_user->user_email;
	}
}

return new WRE_SPL_Stripe();