<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;


// PayPal listener
if( file_exists( DATEBOOK_DIR . 'includes/payment/gateways/paypal/class-datebook-paypal-ipn-verify.php' ) ){
	include_once DATEBOOK_DIR . 'includes/payment/gateways/paypal/class-datebook-paypal-ipn-verify.php';
}


/**
 * Class DateBook_PayPal_IPN
 *
 * @class DateBook_PayPal_IPN
 * @package DateBook/Classes
 * @author Pagick Themes
 */


/**
 * Extends the payment gateway base class for PayPal Standard
 *
 */
class DateBook_Payment_Gateway_paypal_standard extends DateBook_Payment_Gateway {

    /**
     * The features supported by the payment gateway
     *
     * @access public
     * @var array
     *
     */
    public $supports;


    /**
     * Constructor
     *
     */
    public function __construct( $data = array() ) {

		$this->supports = array('change_subscription_payment_method_admin');

	}


	public function datebook_save_settings(){

		if(isset($_POST['datebook_gateway_slug']) && $_POST['datebook_gateway_slug'] == 'paypal_standard'){

			$gateway_settings = array();

			$gateway_settings['slug'] = 'paypal_standard';
			$gateway_settings['enabled'] = isset($_POST['enabled']) && $_POST['enabled'] == 1 ? 1 : 0;
			$gateway_settings['mode'] = isset($_POST['mode']) ? sanitize_text_field($_POST['mode']) : '';
			$gateway_settings['method'] = isset($_POST['method']) ? sanitize_text_field($_POST['method']) : '';
			$gateway_settings['email'] = isset($_POST['email']) ? sanitize_text_field($_POST['email']) : '';
			$gateway_settings['logo_url'] = isset($_POST['logo_url']) ? sanitize_text_field($_POST['logo_url']) : '';
			$gateway_settings['logo_description'] = isset($_POST['logo_description']) ? sanitize_textarea_field($_POST['logo_description']) : '';

			return $gateway_settings;

		}

	}


	private function datebook_item_selected($name, $txncharge){

		if ($name == $txncharge){
			$result = 'selected';
		} else {
			$result = '';
		}

		return $result;

	}


	public function display_setting_page(){

		if (isset($_REQUEST['slug'])) {
				
			//Get entire array
			$item = get_option('datebook_gateways');
			$item = isset($item['paypal_standard']) ? $item['paypal_standard'] : '';

			// Get the location data if its already been entered
			$enabled = isset($item['enabled']) && $item['enabled'] == 1 ? 1 : 0;
			$mode = isset($item['mode']) ? $item['mode'] : 'live';
			$email = isset($item['email']) ? $item['email'] : '';
			$method = isset($item['method']) ? $item['method'] : 'subscription';
			$logo_url = isset($item['logo_url']) ? $item['logo_url'] : DATEBOOK_URL . 'assets/images/gateways/paypal.png';

			$logo_description = isset($item['logo_description']) ? $item['logo_description'] : esc_html__('Pay via PayPal; you can pay with your credit card if you do not have a PayPal account.', 'datebook');

		?>

		<h1><?php echo esc_html__( 'PayPal Standard Settings', 'datebook' ); ?></h1>

		<input type="hidden" name="datebook_gateway_slug" value="paypal_standard" />
		
		<?php echo esc_html__( 'Notice: This payment gateway may not allow adult payments to be made', 'datebook' ); ?>

		<table class="form-table">
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Enable', 'datebook' ); ?></th>
				<td><label><input name="enabled" type="checkbox" value="1"<?php if ($enabled == 1){ echo ' checked'; } ?>><?php echo esc_html__( 'Yes', 'datebook' ); ?></label></td>
			</tr>
		</table>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th scope="row">
					<?php echo esc_html__( 'Mode', 'datebook' ); ?>
				</th>
				<td>
					<select class="form-control" name="mode" id="parent_id">
						<option value="test" <?php echo esc_attr(self::datebook_item_selected('test', $mode)); ?>><?php echo esc_html__( 'Test Mode', 'datebook' ); ?></option>
						<option value="live" <?php echo esc_attr(self::datebook_item_selected('live', $mode)); ?>><?php echo esc_html__( 'Live Mode', 'datebook' ); ?></option>
					</select>
				</td>
			</tr>
		</table>

		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Email', 'datebook' ); ?></th>
				<td><input type="text" name="email" value="<?php echo esc_attr($email); ?>" class="regular-text" /></td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Payment method', 'datebook' ); ?></th>
				<td>
				<select class="form-control" name="method" id="parent_id">
					<option value="subscription" <?php echo esc_attr(self::datebook_item_selected('subscription', $method)); ?>><?php echo esc_html__( 'Subscription', 'datebook' ); ?></option>
					<option value="regular" <?php echo esc_attr(self::datebook_item_selected('regular', $method)); ?>><?php echo esc_html__( 'Regular', 'datebook' ); ?></option>
				</select>
				</td>
			</tr>
		</table>

		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th colspan="2" scope="row"><?php echo esc_html__( 'PayPal logo and description', 'datebook' ); ?></th>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Url to logo', 'datebook' ); ?></th>
				<td><input type="text" name="logo_url" value="<?php echo esc_url($logo_url); ?>" class="widefat" /><br>
				<?php echo esc_url(DATEBOOK_URL . 'assets/images/gateways/paypal.png'); ?></td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Description about PayPal payment gateway', 'datebook' ); ?></th>
				<td><textarea rows="6" name="logo_description" class="widefat"><?php echo esc_attr($logo_description); ?></textarea></td>
			</tr>
		</table>


		<?php
	
		}

	}


    /*
     * Process for all register payments that are not free
     *
	 * Third step of processing Subscription data
	 *
     */
    public function process_redirect_to_payment_gateway($payment_data) {
		
		// Period variables
		global $datebook_paymentperiod_titles;
		
        // Do nothing if the payment id wasn't sent
        if( ! $payment_data['payment_id'] )
            return;

        // Set the notify URL
        $notify_url = home_url() . '/?datebook_paypal_listener=paypal_ipn';


		$payment_data['amount'] = isset($payment_data['amount']) ? $payment_data['amount'] : 0;
		$payment_data['p3'] = isset($payment_data['period_number_key']) ? $payment_data['period_number_key'] : '0';
		$payment_data['t3'] = isset($payment_data['period_key']) ? $datebook_paymentperiod_titles[$payment_data['period_key']][1] : 'D';
		$payment_data['recurring'] = isset($payment_data['recurring']) ? $payment_data['recurring'] : 0;

		//Get entire array
		$item = get_option('datebook_gateways');
		$item = isset($item['paypal_standard']) ? $item['paypal_standard'] : '' ;

		$paypal_method = isset($item['method']) ? $item['method'] : 'regular';
		if ($paypal_method == 'subscription') {
			$cmd_type = '_xclick-subscriptions';
			$amount_type = 'a3';
		} else {
			$cmd_type = '_xclick';
			$amount_type = 'amount';
		}

		$paypal_mode = isset($item['mode']) ? $item['mode'] : 'live';
		if ($paypal_mode == 'test') {
			$paypal_link = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
		} else {
			$paypal_link = 'https://www.paypal.com/cgi-bin/webscr';
		}
		
		$paypal_email = isset($item['email']) ? $item['email'] : '';

		$query_page_link = add_query_arg( array(
            'cmd'           => $cmd_type,
            'business'      => sanitize_email($paypal_email),
            'email'         => $payment_data['user_email'],
            'item_number'   => $payment_data['subscription_plan_id'],
            'item_name'     => $payment_data['subscription_plan_name'],
            'currency_code' => $payment_data['currency'],
            $amount_type	=> $payment_data['amount'],
			'p3'			=> $payment_data['p3'],
			't3'			=> $payment_data['t3'],
			'src'		    => $payment_data['recurring'],
			'sra'		    => '1',
			'modify'		=> '0',	// 0 – allows subscribers only to sign up for new subscriptions; 1 – allows subscribers to sign up for new subscriptions and modify their current subscriptions; 2 – allows subscribers to modify only their current subscriptions
            'tax'           => '0',
			'no_note'		=> '1',
			'no_shipping'	=> '1',
            'custom'        => $payment_data['payment_id'],
            'notify_url'    => $notify_url,
			'return'        => $payment_data['redirect_url']
			
		), $paypal_link );
		
		// Generated sample link sent to PayPal Sandbox: 10 USD per 1 month, Subscription type,
		//https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick-subscriptions&business=payments@pagickthemes.com&email=info@pagickthemes.com&item_number=34741548210096&item_name=VIP&currency_code=USD&a3=10&p3=1&t3=M&src=0&sra=1&modify=0&tax=0&no_note=1&no_shipping=1&custom=226&notify_url=https://www.pagickthemes.com/?datebook_paypal_listener=paypal_ipn&return=https://www.pagickthemes.com:443/mypage/upgrade/

		// Redirect only if tkn is set
		if( isset( $payment_data['datebooktkn'] ) ) {
			wp_redirect($query_page_link);
			exit;
		}
		
    }


	/**
	 * Get response from PayPal IPN and process it
	 * 
	 * Fourth step of processing Subscription data
	 *
	 * @access public
	 */
	public static function datebook_process_payment_response() {
		
		if (isset($_GET['datebook_paypal_listener']) && $_GET['datebook_paypal_listener'] == 'paypal_ipn') {
			
			// Init IPN Verifier
			$ipn_verifier = new DateBook_IPN_Verifier();

			$verified = false;

			// Process the IPN
			try {
				if( $ipn_verifier->checkRequestPost() ){
					$verified = $ipn_verifier->validate();
				}
			} catch ( Exception $e ) {}


			// If response from PayPal IPN verified then start process
			$item = get_option('datebook_gateways');

			if (isset($item['paypal_standard']['enabled']) && $item['paypal_standard']['enabled'] == 1 && $verified) {

				$post_data = $_POST;

				// If the status is completed update the payment and also activate the member subscriptions
				/*
				 * txn_type variable in the message to trigger the kind of processing 
				 *
				 * subscr_cancel	= Subscription canceled
				 * subscr_eot		= Subscription expired
				 * subscr_failed	= Subscription payment failed
				 * subscr_modify	= Subscription modified
				 * subscr_payment	= Subscription payment received
				 * subscr_signup	= Subscription started
				 */
				 
				 // $post_data['txn_type'] == 'web_accept'

				if( isset($post_data['payment_status']) && $post_data['payment_status'] == 'Completed' || (isset($post_data['txn_type']) && ($post_data['txn_type'] == 'subscr_signup' || $post_data['txn_type'] == 'subscr_payment'))) {

					// Get payment id from custom variable sent by IPN
					$payment_id = isset( $post_data['custom'] ) ? $post_data['custom'] : 0;

					// Get the payment
					$payment = datebook_get_payment( $payment_id );

					//[txn_type] => subscr_payment
					//[txn_id] => 8D395827FB397590G
					//[subscr_id] => I-L32TTE3HLWSL
					//[item_number] => 28821538858010
					//[payment_status] => Completed
					//[payment_gross] => 1.00

					// If the status is completed update the payment and also activate the member subscriptions
					if($payment->id == $payment_id){

						$profile_id = $payment->profile_id ? $payment->profile_id : 0;

						$subscription_plan_id = $payment->subscription_id ? $payment->subscription_id : 0;
						$subscription_plan_price_period = $payment->plan_price_period ? $payment->plan_price_period : 0;
						$subscription_plan_user_id = $payment->user_id ? $payment->user_id : 0;

						$subscription_plan_start_date = $payment->start_date ? $payment->start_date : date('Y-m-d H:i:s');
						$subscription_plan_expiration_date = $payment->expiration_date ? $payment->expiration_date : date('Y-m-d H:i:s');

						$subscription_plan_amount = $payment->amount ? $payment->amount : 0;
						$subscription_plan_currency = $payment->currency ? $payment->currency : 'USD';
						$subscription_plan_type = $payment->type ? $payment->type : 'subscription_initial_payment';

						$subscription_plan_transaction_id = $payment->transaction_id ? $payment->transaction_id : 0;

						$transaction_id = isset($post_data['subscr_id']) ? $post_data['subscr_id'] : (isset($post_data['txn_id']) ? $post_data['txn_id'] : '');

						if( $subscription_plan_transaction_id == $transaction_id ){

							// Period variables
							global $period_list_array;

							// Get all plans
							$all_splans = get_option('datebook_subscription_plans');
							if(!isset($all_splans[$subscription_plan_id]) && $all_splans[$subscription_plan_id] <= 0) return;

							// Calculate the Subscription plan period time
							$subscription_period_number_key = $all_splans[$subscription_plan_id]['register_period_number'][$subscription_plan_price_period];

							$subscription_period_key = $all_splans[$subscription_plan_id]['register_period'][$subscription_plan_price_period];

							if ($subscription_period_number_key > 0) {

								$subscription_period_expiration = date('Y-m-d H:i:s', strtotime("+" . $subscription_period_number_key . " " . $period_list_array[$subscription_period_key]));

							} else {

								$subscription_period_expiration = '0000-00-00 00:00:00';

							}

							// Payment data
							$payment_data = array(
								'user_id'					=> $subscription_plan_user_id,
								'subscription_plan_id'		=> $subscription_plan_id,
								'plan_price_period'			=> $subscription_plan_price_period,

								'date'						=> date('Y-m-d H:i:s', time()),
								'start_date'				=> date('Y-m-d H:i:s', time()),
								'expiration_date'			=> $subscription_period_expiration,

								'amount'					=> $subscription_plan_amount,
								'payment_gateway'			=> 'paypal_standard',
								'type'						=> $subscription_plan_type,
								'currency'					=> $subscription_plan_currency,
								'status'					=> (isset($payment->status) ? $payment->status : 'pending'),//'pending'
								'profile_id'				=> $profile_id
							);

							$payment = new DateBook_Payment_Class();
							$payment->insert( $payment_data );

							// Insert payment id for WooCommerce
							$payment_id = $payment->id;

							update_post_meta($profile_id, 'payment_id', $payment_id);

							update_post_meta($profile_id, 'recurring', $all_splans[$subscription_plan_id]['recurring']);

						} else {

							// If the payment has already been completed do nothing
							if( $payment->status == 'completed' )
								return;

						}

						$payment_data = array(
							'subscription_plan_id'	=> $subscription_plan_id,
							'payment_id'		=> $payment_id,
							'plan_price_period' => $subscription_plan_price_period,
							'profile_id'		=> $profile_id,
							'user_id'			=> $subscription_plan_user_id,
							'start_date'		=> $subscription_plan_start_date,
							'expiration_date'	=> $subscription_plan_expiration_date,
							'transaction_id'	=> $transaction_id
						);

						$payment_data['payment_gateway'] = 'paypal_standard';

						// Let's activate Subscription for member after payment is made. Place this action at the end of payment process
						do_action('datebook_activate_subscription_after_payment', $payment_data);

					}

				} else {

					// If payment status is not complete, something happened, so log it in the payment
					$log_data = array(
						'date'           => $post_data['subscr_date'],
						'payer_id'       => $post_data['payer_id'],
						'payer_email'    => $post_data['payer_email'],
						'payer_status'   => $post_data['payer_status']
					);

					$payment->add_log_entry( 'failure', esc_html__( 'The payment could not be completed successfully', 'datebook' ), $log_data );

				}
			}
		}
	}


}