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

/**
 * WRE_SPL_PayPal
 */
class WRE_SPL_PayPal extends WRE_SPL_Gateway {

	/**
	 * __construct function.
	 */
	public function __construct() {
		$this->current_user_id = get_current_user_id();
		add_action( 'wre_payment_action', array( $this, 'wre_submit_handler' ) );
		parent::__construct();
	}

	/**
	 * Validate a PDT transaction to ensure its authentic.
	 * @param  string $transaction
	 * @return bool|array False or result array
	 */
	protected function wre_validate_transaction( $transaction ) {
		$pdt = array(
			'body'	=> array(
				'cmd' => '_notify-synch',
				'tx'  => $transaction,
				'at'  => wre_option('wre_paypal_pdt_token'),
			),
			'timeout'	=> 60,
		);

		// Post back to get a response.
		$response = wp_safe_remote_post( $this->paypal_link, $pdt );

		if ( is_wp_error( $response ) || ! strpos( $response['body'], "SUCCESS" ) === 0 ) {
			return false;
		}

		// Parse transaction result data
		$transaction_result  = array_map( 'wre_clean', array_map( 'urldecode', explode( "\n", $response['body'] ) ) );
		$transaction_results = array();

		foreach ( $transaction_result as $line ) {
			$line = explode( "=", $line );
			$transaction_results[ $line[0] ] = isset( $line[1] ) ? $line[1] : '';
		}

		if ( ! empty( $transaction_results['charset'] ) && function_exists( 'iconv' ) ) {
			foreach ( $transaction_results as $key => $value ) {
				$transaction_results[ $key ] = iconv( $transaction_results['charset'], 'utf-8', $value );
			}
		}

		return $transaction_results;
	}

	/**
	 * Submit handler
	 *
	 * Alternative to IPN
	 */
	public function wre_submit_handler() {
		if ( empty( $_REQUEST['cm'] ) || empty( $_REQUEST['tx'] ) || empty( $_REQUEST['st'] ) ) {
			return;
		}
		$status = wre_clean( strtolower( stripslashes( $_REQUEST['st'] ) ) );
		$amount = wre_clean( stripslashes( $_REQUEST['amt'] ) );
		$transaction = wre_clean( stripslashes( $_REQUEST['tx'] ) );
		$posted = $this->wre_validate_transaction( $transaction );
		if( $posted ) {

			if( isset( $_REQUEST['user_id'] ) && $_REQUEST['user_id'] != '' ) {
				$package_id = '';
				if( isset( $posted['item_number'] ) ) {
					$package_id = absint($posted['item_number']);
				} else if( isset( $posted['item_name1'] ) ) {
					$package_id = absint($posted['item_name1']);
				}
				$transaction_id = wre_get_membership_details( $this->current_user_id, 'transaction_id' );
				if( $package_id && isset( $posted['custom'] ) && $posted['custom'] == $this->current_user_id && $posted['txn_id'] != $transaction_id && $status == 'completed' ) {

					$package_amount = wre_package_meta( 'price', $package_id );
					$membership_details = array(
						'package_id' => $package_id,
						'transaction_id' => $posted['txn_id'],
						'payment_date'	=> $posted['payment_date'],
						'payment_status' => strtolower($posted['payment_status']),
						'amount_received' => $posted['payment_gross'],
						'payment_type'	=> 'PayPal'
					);
					if( isset( $_REQUEST['listing_id'] ) && $_REQUEST['listing_id'] != '' ) {
						$membership_details['listing_id'] = $_REQUEST['listing_id'];
					}
					WRE_SPL_Gateway::wre_update_membership_details( $membership_details );
				}
			}
		}
	}
}

return new WRE_SPL_PayPal();