<?php
/**
 * Class DateBook_Payment_Gateway_paystack
 *
 * @class DateBook_Payment_Gateway_paystack
 * @package DateBook/Classes
 * @author Pagick Themes
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


define('DATEBOOK_PAYSTACK_TABLE', 'datebook_paystack');

add_action('admin_menu', 'datebook_paystack_register_newpage');
function datebook_paystack_register_newpage(){
	add_menu_page('Paystack', 'paystack', 'administrator', 'datebook-paystack-payments', 'datebook_paystack_accepted_payments');
	remove_menu_page('datebook-paystack-payments');
}


function datebook_paystack_accepted_payments(){

	$exampleListTable = new DateBook_Paystack_Payments_List_Table();
	$data = $exampleListTable->prepare_items();

	?>

	<h1><?php echo esc_html__('Payments (by Paystack payment gateway)', 'datebook'); ?></h1>
	<p class="about-description"><?php echo esc_html__('All payments made by users', 'datebook'); ?></p>
	<div class="wrap"><?php $exampleListTable->display(); ?></div>

	<?php

}



if (! class_exists('WP_List_Table')){
	include_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}


class DateBook_Paystack_Payments_List_Table extends WP_List_Table{


	public function format_data($data){

		$new = json_decode($data);
		$text = '';

		if (array_key_exists("0", $new)){
			foreach ($new as $key => $item){
				if ($item->type == 'text'){
					$text.= '<strong>' . esc_attr($item->display_name) . ': </strong> ' . esc_attr($item->value) . '<br />';
				} else {
					$text.= '<strong>' . esc_attr($item->display_name) . ': </strong> <a target="_blank" href="' . esc_attr($item->value) . '">link</a><br />';
				}
			}
		} else {
			$text = '';
			if (count($new) > 0){
				foreach ($new as $key => $item){
					$text.= '<strong>' . esc_attr($key) . ': </strong> ' . esc_attr($item) . '<br />';
				}
			}
		}
		
		return $text;
	}


	public function prepare_items(){

		global $wpdb, $datebook_currency_titles;
		
		$default_currency = of_get_option('default_currency');
		$currency_code = $datebook_currency_titles[$default_currency][1];

		$table = strtolower($wpdb->prefix).DATEBOOK_PAYSTACK_TABLE;
		$data = array();
		$alldbdata = $wpdb->get_results("SELECT * FROM $table WHERE (paid = '1')");

		foreach ($alldbdata as $key => $dbdata){
			$newkey = $key + 1;
			if ($dbdata->txn_code_2 != ''){
				$txn_code = $dbdata->txn_code_2;
			} else {
				$txn_code = $dbdata->txn_code;
			}
			
			$data[] = array(
				'id' => $newkey,
				'email' => $dbdata->email,
				'amount' => $currency_code . ': ' . number_format($dbdata->amount),
				'txn_code' => $txn_code,
				'metadata' => self::format_data($dbdata->metadata),
				'date' => $dbdata->created_at
			);
		}

		$columns = $this->get_columns();
		$hidden = $this->get_hidden_columns();
		$sortable = $this->get_sortable_columns();
		usort($data, array( &$this, 'sort_data' ));
		$perPage = 20;
		$currentPage = $this->get_pagenum();
		$totalItems = count($data);
		$this->set_pagination_args(
			array(
				'total_items' => $totalItems,
				'per_page'  => $perPage
			)
		);
		
		$data = array_slice($data, (($currentPage-1)*$perPage), $perPage);
		$this->_column_headers = array($columns, $hidden, $sortable);
		$this->items = $data;
		
		$rows = count($alldbdata);
		
		return $rows;
		
	}
	
	
	public function get_columns(){
		
		$columns = array(
			'id' => '#',
			'email' => esc_html__('Email', 'datebook'),
			'amount' => esc_html__('Amount', 'datebook'),
			'txn_code' => esc_html__('Txn Code', 'datebook'),
			'metadata' => esc_html__('Data', 'datebook'),
			'date' => esc_html__('Date', 'datebook')
		);
		
		return $columns;
		
	}
	
	
	/**
	 * Define which columns are hidden
	 *
	 * @return Array
	 */
	public function get_hidden_columns(){
		return array();
	}
	
	public function get_sortable_columns(){
		return array('email' => array('email', false),'date' => array('date', false),'amount' => array('amount', false));
	}
	

	/**
	 * Get the table data
	 *
	 * @return Array
	 */
	private function table_data($data){
		return $data;
	}


	/**
	 * Define what data to show on each column of the table
	 *
	 * @param Array $item    Data
	 * @param String $column_name - Current column name
	 *
	 * @return Mixed
	 */
	public function column_default($item, $column_name){
		
		switch ($column_name){
			case 'id':
			case 'email':
			case 'amount':
			case 'txn_code':
			case 'metadata':
			case 'date':
				return $item[ $column_name ];
			default:
				return print_r($item, true);
		}
	}


	/**
	 * Allows you to sort the data by the variables set in the $_GET
	 *
	 * @return Mixed
	 */
	private function sort_data($a, $b){
		
		$orderby = 'date';
		$order = 'desc';
		
		if (!empty($_GET['orderby'])){
			$orderby = $_GET['orderby'];
		}
		if (!empty($_GET['order'])){
			$order = $_GET['order'];
		}
		
		$result = strcmp($a[$orderby], $b[$orderby]);
		
		if ($order === 'asc'){
			return $result;
		}
		
		return -$result;
		
	}
}




define('DATEBOOK_PAYSTACK_PERCENTAGE', 0.015);
define('DATEBOOK_PAYSTACK_CROSSOVER_TOTAL', 250000);
define('DATEBOOK_PAYSTACK_ADDITIONAL_CHARGE', 10000);
define('DATEBOOK_PAYSTACK_LOCAL_CAP', 200000);

define('DATEBOOK_PAYSTACK_CHARGE_DIVIDER', floatval(1-DATEBOOK_PAYSTACK_PERCENTAGE));
define('DATEBOOK_PAYSTACK_CROSSOVER_AMOUNT', intval((DATEBOOK_PAYSTACK_CROSSOVER_TOTAL*DATEBOOK_PAYSTACK_CHARGE_DIVIDER)-DATEBOOK_PAYSTACK_ADDITIONAL_CHARGE));
define('DATEBOOK_PAYSTACK_FLATLINE_AMOUNT_PLUS_CHARGE', intval((DATEBOOK_PAYSTACK_LOCAL_CAP-DATEBOOK_PAYSTACK_ADDITIONAL_CHARGE)/DATEBOOK_PAYSTACK_PERCENTAGE));
define('DATEBOOK_PAYSTACK_FLATLINE_AMOUNT', DATEBOOK_PAYSTACK_FLATLINE_AMOUNT_PLUS_CHARGE - DATEBOOK_PAYSTACK_LOCAL_CAP);

class DateBook_Paystack_Frontend {

	public function __construct(){

    }

    public static function fetchPublicKey(){

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

		$mode = isset($item['mode']) ? $item['mode'] : '';
		$tpk = isset($item['tpk']) ? $item['tpk'] : '';
		$lpk = isset($item['lpk']) ? $item['lpk'] : '';

        $mode =  esc_attr($mode);
        if ($mode == 'test'){
            $key = esc_attr($tpk);
        } else {
            $key = esc_attr($lpk);
        }

        return $key;

    }

    public static function fetchFeeSettings(){
		
		//Get gateway array
		$item = get_option('datebook_gateways');
		$item = isset($item['paystack']) ? $item['paystack'] : '';
		
		$prc = isset($item['prc']) ? $item['prc'] : '';
		$ths = isset($item['ths']) ? $item['ths'] : '';
		$adc = isset($item['adc']) ? $item['adc'] : '';
		$cap = isset($item['cap']) ? $item['cap'] : '';

        $ret = array();
        $ret['prc'] = intval(floatval(esc_attr($prc)) * 100) / 10000;
        $ret['ths'] = intval(floatval(esc_attr($ths)) * 100);
        $ret['adc'] = intval(floatval(esc_attr($adc)) * 100);
        $ret['cap'] = intval(floatval(esc_attr($cap)) * 100);

        return $ret;

    }


}


function datebook_paystack_add_paystack_charge($amount){

    // $amountinkobo = $amount; // * 100;
    $charge = 0;
    $amount = intval($amount);
    if ($amount <= 2500){
        $charge = floatval($amount * DATEBOOK_PAYSTACK_PERCENTAGE);
    } else {
        $charge = floatval($amount * DATEBOOK_PAYSTACK_PERCENTAGE) + 100;
    }
    // echo $charge;
    if ($charge > 2000){
        $charge = 2000;
    }
    $amount += $charge;

    return esc_attr($amount);

    // if ($amountinkobo > DATEBOOK_PAYSTACK_FLATLINE_AMOUNT)
    //     return ($amountinkobo + DATEBOOK_PAYSTACK_LOCAL_CAP)/100;
    // elseif ($amountinkobo > DATEBOOK_PAYSTACK_CROSSOVER_AMOUNT)
    //     return (intval(($amountinkobo + DATEBOOK_PAYSTACK_ADDITIONAL_CHARGE) / DATEBOOK_PAYSTACK_CHARGE_DIVIDER))/100;
    // else
    //     return (intval($amountinkobo / DATEBOOK_PAYSTACK_CHARGE_DIVIDER))/100;

}

add_filter('wp_mail_content_type', 'datebook_paystack_mail_content_type');
function datebook_paystack_mail_content_type(){
    return 'text/html';
}

add_filter('wp_mail_from_name', 'datebook_paystack_mail_from_name');
function datebook_paystack_mail_from_name(){
    $name = get_option('blogname');
    return $name;
}




//include_once plugin_dir_path(dirname(__FILE__)) . 'paystack/class-datebook-paystack-email.php';




function datebook_paystack_fetch_plan($code){

	//Get gateway array
	$item = get_option('datebook_gateways');
	$item = $item['paystack'];
	
	$mode = isset($item['mode']) ? $item['mode'] : '';
	$tsk = isset($item['tsk']) ? $item['tsk'] : '';
	$lsk = isset($item['lsk']) ? $item['lsk'] : '';

    if ($mode == 'test'){
        $key = esc_attr($tsk);
    } else {
        $key = esc_attr($lsk);
    }

    $paystack_url = 'https://api.paystack.co/plan/' . esc_attr($code);

    $headers = array(
    'Authorization' => 'Bearer ' . $key
    );

    $args = array(
    'headers'    => $headers,
    'timeout'    => 60
    );

    $request = wp_remote_get($paystack_url, $args);

    if (! is_wp_error($request)){
        $paystack_response = json_decode(wp_remote_retrieve_body($request));
    }

    return $paystack_response;

}


// Save the Metabox Data
function datebook_paystack_generate_new_code($length = 10){

    $characters = '06EFGHI9KL'.time().'MNOPJRSUVW01YZ923234'.time().'ABCD5678QXT';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++){
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }

    return time() . "_" . $randomString;

}

function datebook_paystack_check_code($code){

    global $wpdb;

    $table = strtolower($wpdb->prefix).DATEBOOK_PAYSTACK_TABLE;

	$o_exist = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE txn_code = '%s'", $code));

    if (count($o_exist) > 0){
        $result = true;
    } else {
        $result = false;
    }

    return $result;
}

function datebook_paystack_generate_code(){

    $code = 0;
    $check = true;

    while ($check){
        $code = datebook_paystack_generate_new_code();
        $check = datebook_paystack_check_code($code);
    }

    return $code;

}

function datebook_paystack_get_the_user_ip(){

    if (! empty($_SERVER['HTTP_CLIENT_IP'])){
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }

    return $ip;

}


function datebook_paystack_meta_as_custom_fields($metadata){

    $custom_fields = array();

    foreach ($metadata as $key => $value){
        if (is_array($value)){
            $value = implode(', ', $value);
        }
        if ($key == 'datebook_paystack_fname'){
            $custom_fields[] =  array(
            'display_name' => 'Full Name',
            'variable_name' => 'Full_Name',
             'type' => 'text',
             'value' => $value
            );
        } elseif ($key == 'datebook_paystack_plancode'){
            $custom_fields[] =  array(
            'display_name' => 'Plan',
            'variable_name' => 'Plan',
             'type' => 'text',
             'value' => $value
            );
        } elseif ($key == 'datebook-paystack-vname'){
            $custom_fields[] =  array(
            'display_name' => 'Payment Option',
            'variable_name' => 'Payment Option',
             'type' => 'text',
             'value' => $value
            );
        } elseif ($key == 'datebook_paystack_interval'){
            $custom_fields[] =  array(
            'display_name' => 'Plan Interval',
            'variable_name' => 'Plan Interval',
             'type' => 'text',
             'value' => $value
            );
        } else {
            $custom_fields[] =  array(
            'display_name' => ucwords(str_replace("_", " ", $key)),
            'variable_name' => $key,
             'type' => 'text',
             'value' => (string)$value
            );
        }
    }
    return $custom_fields;
}


function datebook_paystack_display_form($subscriptionplan_price_count, $subscription_arg, $pay_gate){

	$layout = '';

	//Get gateway array
	$item = get_option('datebook_gateways');
	$item = $item['paystack'];

	$pk = DateBook_Paystack_Frontend::fetchPublicKey();

	if (!$pk){

		$layout .= '<h5>' . esc_html__('You must set your Paystack API keys first', 'datebook') . '</h5>';

	} else if (!empty($item) && is_array($item)){

		if ($item['slug'] == 'paystack'){

			global $datebook_currency_titles;
			
			if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
				$current_user_id = DATEBOOK_CURRENT_USER_ID;
			} else {
				global $current_user;
				wp_get_current_user();
				$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
			}

			if ($current_user_id > 0){

				$profile_id = get_user_meta( $current_user_id, 'profile_postid', true );
				$profile = get_post($profile_id);
				$profile_name = isset($profile->post_title) ? $profile->post_title : '';
				
				$current_user = get_userdata($current_user_id);
				$email = $current_user->user_email;

				$amount = isset($subscription_arg['subscriptionplan_price']) ? $subscription_arg['subscriptionplan_price'] : '';
				$txncharge = isset($item['_txncharge']) ? $item['_txncharge'] : '';
				
				$default_currency = of_get_option('default_currency');
				$currency_code = $datebook_currency_titles[$default_currency][1];
				
				$currency = isset($currency_code) ? $currency_code : 'NGN';
				$recur = isset($item['_recur']) ? $item['_recur'] : 'no';
				$recurplan = isset($item['_recurplan']) ? $item['_recurplan'] : '';

				$showbtn = true;
				$planerrorcode = esc_html__('Input Correct Recurring Plan Code', 'datebook');

				if ($recur == 'plan'){

					if ($recurplan == '' || $recurplan == null){
						$showbtn = false;
					} else {
						$plan = datebook_paystack_fetch_plan($recurplan);
						if (isset($plan->data->amount)){
							$planamount = $plan->data->amount/100;
						} else {
							$showbtn = false;
						}
					}
				}

				$layout .= '<form enctype="multipart/form-data" action="' . esc_url(get_permalink(of_get_option('my_upgrade_page'))) . '" url="' . esc_url(get_permalink(of_get_option('my_upgrade_page'))) . '" method="post" class="datebook-paystack-form j-forms" novalidate>';
				
				$layout .= wp_nonce_field( 'datebook_new_subscription_form_nonce', 'datebooktkn', true, false );

				$layout .= '<input type="hidden" name="action" value="payment_page">';
				$layout .= '<input type="hidden" name="payment_page" value="3">';
				$layout .= '<input name="subscriptionplan" type="hidden" value="' . esc_attr($subscription_arg['subscription_id']) . '" />';
				$layout .= '<input name="subscriptionplan_period_key" type="hidden" value="' . esc_attr($subscription_arg['subscriptionplan_period_key']) . '" />';
				$layout .= '<input type="hidden" name="pay_gate" value="' . esc_attr( $pay_gate ) . '" />';
				$layout .= '<input type="hidden" type="email" name="email" value="' . sanitize_email($email) . '" />';

				// Show the ocurring checkbox option
				if (isset($subscription_arg['subscriptionplan_recurring']) && ($subscription_arg['subscriptionplan_recurring'] == 1 || $subscription_arg['subscriptionplan_recurring'] == 2) && isset($subscription_arg['subscriptionplan_price']) && $subscription_arg['subscriptionplan_price'] > 0) {
					
					$random_ocurring = rand(20,10000);
			
					$layout .= '<hr/>';

					$layout .= '<div class="custom-control custom-checkbox">';

					if ($subscription_arg['subscriptionplan_recurring'] == 2) {
						$layout .= '<input id="datebookOcurring' . $pay_gate. $random_ocurring . '" class="custom-control-input" type="checkbox" name="recurring" value="1" checked disabled>';
					} else {
						$layout .= '<input id="datebookOcurring' . $pay_gate. $random_ocurring . '" class="custom-control-input" type="checkbox" name="recurring" value="1" ' . checked( '1', $subscription_arg['subscriptionplan_recurring'], false ) . ' />';
					}

					$layout .= '<label class="custom-control-label" for="datebookOcurring' . $pay_gate. $random_ocurring . '">' . esc_html__('Auto-renew', 'datebook') . '</label>';
					$layout .= '</div>';

				}


				/*$layout .= '<span id="datebook-paystack-min-val-warn" style="color: red; font-size: 13px;"></span>';
				if ($recur == 'plan'){

					if ($showbtn){

						$layout .= '<input id="datebook-paystack-amount" type="hidden" name="datebook_paystack_amount" value="' . esc_attr($planamount) . '" readonly required />';

						$layout .= '<input type="hidden" name="datebook_paystack_plancode" value="' . esc_attr($recurplan). '" />';
						$layout .= '<label>' . esc_attr($plan->data->name) . ' ' . esc_attr($plan->data->interval) . ' recuring payment - ' . esc_attr($plan->data->currency) . ' ' . esc_attr(number_format($planamount)) . '</label>';

					} else {
						$layout .= '<label>' . esc_attr($planerrorcode) . '</label>';
					}

				} elseif ($recur == 'optional'){
					
					$layout .= '<input id="datebook-paystack-amount" class="datebook-paystack-number" type="hidden" name="datebook_paystack_amount" value="' . esc_attr($amount) . '" required />';

					$layout .= '<label>' . esc_html__('Recurring Payment', 'datebook') . '</label>
			 					 <select class="form-control" name="datebook_paystack_interval" >
			 						 <option value="no">' . esc_html__('None', 'datebook') . '</option>
			 						 <option value="daily">' . esc_html__('Daily', 'datebook') . '</option>
			 						 <option value="weekly">' . esc_html__('Weekly', 'datebook') . '</option>
                                     <option value="monthly">' . esc_html__('Monthly', 'datebook') . '</option>
                                     <option value="biannually">' . esc_html__('Biannually', 'datebook') . '</option>
			 						 <option value="annually">' . esc_html__('Annually', 'datebook') . '</option>
			 					 </select>';

				} else {
					
					if ($amount == 0){
						$layout .= '<input id="datebook-paystack-amount" class="form-control" type="text" name="datebook_paystack_amount" class="datebook-paystack-number" value="0" required />';
					} else {
						$layout .= '<input id="datebook-paystack-amount" type="text" name="datebook_paystack_amount" value="' . esc_attr($amount) . '" readonly required />';
					}

				}*/



                if ($txncharge != 'merchant' && $recur != 'plan'){
                    echo '<small>' . esc_html__('Transaction Charge', 'datebook') . ': <b class="datebook-paystack-txncharge"></b>, ' . esc_html__('Total', 'datebook') . ':<strong  class="datebook-paystack-txntotal"></b></small>';
                }

				$layout .= '<div class="datebook-clear15"></div>';
				$layout .= '<button class="btn btn-primary" name="submit" value="paystack" type="submit">' . esc_html__( 'Subscribe', 'datebook' ) . '</button>';
				if (is_super_admin()) {
					$layout .= '<button class="btn btn-success btn-sm" name="admin_activated" value="1" type="submit">' . esc_html__( 'Activate for free', 'datebook' ) . '<br>(' . esc_html__( 'You are logged in as Administrator', 'datebook' ) . ')</button>';
				}
				
				$layout .= '</form>';

			} else {

				$layout .= '<h5>' . esc_html__('You must be logged in to make payment', 'datebook') . '</h5>';

			}
		}
	}

	return $layout;

}




/**
 * Extends the payment gateway base class for Paystack
 *
 */
class DateBook_Payment_Gateway_paystack extends DateBook_Payment_Gateway {

    /**
     * Constructor
     *
     */
    public function __construct( $data = array() ) {
		
		self::activate();
		self::datebook_save_settings();

		add_action('admin_menu', array( $this, 'datebook_paystack_add_settings_page'));

		add_action('datebook_paystack_confirm_payment', array( $this, 'datebook_paystack_confirm_payment'));

	}
	

	public function activate(){

		global $wpdb;

		$table_name = strtolower($wpdb->prefix) . DATEBOOK_PAYSTACK_TABLE;
		$check_paystack = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_name));

		if($check_paystack != $table_name){

			$collate = '';

			if ( $wpdb->has_cap( 'collation' ) ){
				if ( ! empty($wpdb->charset ) ){
					$collate .= "DEFAULT CHARACTER SET $wpdb->charset";
				}
				if ( ! empty($wpdb->collate ) ){
					$collate .= " COLLATE $wpdb->collate";
				}
			}

			$sql = "CREATE TABLE `".$table_name."` (
				id int(11) NOT NULL AUTO_INCREMENT,
				profile_id int(11) NOT NULL,
				user_id int(11) NOT NULL,
				email varchar(255) DEFAULT '' NOT NULL,
				metadata text,
				plan varchar(255) DEFAULT '' NOT NULL,
				txn_code varchar(255) DEFAULT '' NOT NULL,
				txn_code_2 varchar(255) DEFAULT '' NOT NULL,
				amount varchar(255) DEFAULT '' NOT NULL,
				deleted_at varchar(255) DEFAULT '' NULL,
				created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
				modified timestamp DEFAULT '0000-00-00 00:00:00' NOT NULL,
				paid int(1) NOT NULL DEFAULT '0',
				paid_at timestamp,
				ip varchar(255) NOT NULL,
				PRIMARY KEY id (id)
			) " . $collate . ";";

			include_once ABSPATH . 'wp-admin/includes/upgrade.php';

			dbDelta($sql);
		
			// Paystack gateway database table is now created so we don't need to run this again
			update_option('datebook_paystack_installed', 'yes');
			
		}
	}


	public function datebook_paystack_add_settings_page(){

		add_submenu_page(admin_url('admin.php?page=datebook-paystack-payments'), 'Payments', 'Payments', 'datebook-paystack-payments', basename(__FILE__), 'datebook_paystack_accepted_payments');

	}


	public function datebook_save_settings(){

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

			$gateway_settings = array();

			$gateway_settings['slug'] = 'paystack';
			$gateway_settings['enabled'] = isset($_POST['enabled']) && $_POST['enabled'] == 1 ? 1 : 0;
			$gateway_settings['mode'] = isset($_POST['mode']) ? sanitize_text_field($_POST['mode']) : '';
			$gateway_settings['tsk'] = isset($_POST['tsk']) ? sanitize_text_field($_POST['tsk']) : '';
			$gateway_settings['tpk'] = isset($_POST['tpk']) ? sanitize_text_field($_POST['tpk']) : '';
			$gateway_settings['lsk'] = isset($_POST['lsk']) ? sanitize_text_field($_POST['lsk']) : '';
			$gateway_settings['lpk'] = isset($_POST['lpk']) ? sanitize_text_field($_POST['lpk']) : '';
			$gateway_settings['prc'] = isset($_POST['prc']) ? sanitize_text_field($_POST['prc']) : '';
			$gateway_settings['ths'] = isset($_POST['ths']) ? sanitize_text_field($_POST['ths']) : '';
			$gateway_settings['adc'] = isset($_POST['adc']) ? sanitize_text_field($_POST['adc']) : '';
			$gateway_settings['cap'] = isset($_POST['cap']) ? sanitize_text_field($_POST['cap']) : '';
			$gateway_settings['_txncharge'] = isset($_POST['_txncharge']) ? sanitize_text_field($_POST['_txncharge']) : '';
			$gateway_settings['_recur'] = isset($_POST['_recur']) ? sanitize_text_field($_POST['_recur']) : '';
			$gateway_settings['_recurplan'] = isset($_POST['_recurplan']) ? sanitize_text_field($_POST['_recurplan']) : '';
			$gateway_settings['_subaccount'] = isset($_POST['_subaccount']) ? sanitize_text_field($_POST['_subaccount']) : '';
			$gateway_settings['_txnbearer'] = isset($_POST['_txnbearer']) ? sanitize_text_field($_POST['_txnbearer']) : '';
			$gateway_settings['_merchantamount'] = isset($_POST['_merchantamount']) ? sanitize_text_field($_POST['_merchantamount']) : '';
			$gateway_settings['_startdate_days'] = isset($_POST['_startdate_days']) ? sanitize_text_field($_POST['_startdate_days']) : '';
			$gateway_settings['_startdate_plan_code'] = isset($_POST['_startdate_plan_code']) ? sanitize_text_field($_POST['_startdate_plan_code']) : '';
			$gateway_settings['_startdate_enabled'] = isset($_POST['_startdate_enabled']) ? sanitize_text_field($_POST['_startdate_enabled']) : '';
			$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']) : '';
			$gateway_settings['_sendinvoice'] = isset($_POST['_sendinvoice']) ? sanitize_text_field($_POST['_sendinvoice']) : '';
			$gateway_settings['_sendreceipt'] = isset($_POST['_sendreceipt']) ? sanitize_text_field($_POST['_sendreceipt']) : '';
			$gateway_settings['_subject'] = isset($_POST['_subject']) ? sanitize_text_field($_POST['_subject']) : '';
			$gateway_settings['_heading'] = isset($_POST['_heading']) ? sanitize_text_field($_POST['_heading']) : '';
			$gateway_settings['_message'] = isset($_POST['_message']) ? sanitize_textarea_field($_POST['_message']) : '';

			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['paystack']) ? $item['paystack'] : '' ;

			// Get the location data if its already been entered

			$enabled = isset($item['enabled']) && $item['enabled'] == 1 ? 1 : 0;
			$mode = isset($item['mode']) ? $item['mode'] : '';
			$tsk = isset($item['tsk']) ? $item['tsk'] : '';
			$tpk = isset($item['tpk']) ? $item['tpk'] : '';
			$lsk = isset($item['lsk']) ? $item['lsk'] : '';
			$lpk = isset($item['lpk']) ? $item['lpk'] : '';
			$prc = isset($item['prc']) ? $item['prc'] : '';
			$ths = isset($item['ths']) ? $item['ths'] : '';
			$adc = isset($item['adc']) ? $item['adc'] : '';
			$cap = isset($item['cap']) ? $item['cap'] : '';
			$txncharge = isset($item['_txncharge']) ? $item['_txncharge'] : 'merchant';
			$recur = isset($item['_recur']) ? $item['_recur'] : 'no';
			$recurplan = isset($item['_recurplan']) ? $item['_recurplan'] : '';
			$subaccount = isset($item['_subaccount']) ? $item['_subaccount'] : '';
			$txnbearer = isset($item['_txnbearer']) ? $item['_txnbearer'] : '';
			$merchantamount = isset($item['_merchantamount']) ? $item['_merchantamount'] : '';
			$days = isset($item['_startdate_days']) ? $item['_startdate_days'] : '';
			$plan = isset($item['_startdate_plan_code']) ? $item['_startdate_plan_code'] : '';
			$startdate_enabled = isset($item['_startdate_enabled']) ? $item['_startdate_enabled'] : 0;

			$logo_url = isset($item['logo_url']) ? $item['logo_url'] : DATEBOOK_URL . 'assets/images/gateways/paystack.png';
			$logo_description = isset($item['logo_description']) ? $item['logo_description'] : esc_html__('Paystack is the fastest, simplest way to make online payments. Paystack is the payment processor for modern, frictionless, painless payments.', 'datebook');

			$sendinvoice = isset($item['_sendinvoice']) ? $item['_sendinvoice'] : 'yes';
			$sendreceipt = isset($item['_sendreceipt']) ? $item['_sendreceipt'] : 'yes';
			$subject = isset($item['_subject']) ? $item['_subject'] : esc_html__('Thank you for your payment', 'datebook');
			$heading = isset($item['_heading']) ? $item['_heading'] : esc_html__('We have received your payment', 'datebook');
			$message = isset($item['_message']) ? $item['_message'] : esc_html__('Your payment was received and we appreciate it', 'datebook');

	?>

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

	<?php /*?><h3><?php echo sprintf('<a href="%s">%s</a>', admin_url('admin.php?page=datebook-paystack-payments'), esc_html__('View payments', 'datebook')); ?></h3><?php */?>

		<input type="hidden" name="datebook_gateway_slug" value="paystack" />

		<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>

			<tr valign="top">
				<th scope="row"></th>
				<td><?php echo sprintf('<a href="https://dashboard.paystack.co/#/settings/developer" target="_blank">%s</a>', esc_html__('Get your API Keys', 'datebook')); ?></td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Test Secret Key', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="tsk" value="<?php echo esc_attr($tsk); ?>" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Test Public Key', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="tpk" value="<?php echo esc_attr($tpk); ?>" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Live Secret Key', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="lsk" value="<?php echo esc_attr($lsk); ?>" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Live Public Key', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="lpk" value="<?php echo esc_attr($lpk); ?>" /></td>
			</tr>
		</table>
		
		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Currency', 'datebook' ); ?></th>
				<td><?php echo esc_html__( 'Currency must be set here: DateBook -> Dashboard -> Payments tab -> Default currency', 'datebook' ); ?><br>
				<?php echo esc_html__( 'Notice: Paystack accepts only these currencies', 'datebook' ); ?>: NGN - <?php echo esc_html__('Nigerian Naira', 'datebook'); ?>, GHS - <?php echo esc_html__('Ghanaian Cedis', 'datebook'); ?>, USD - <?php echo esc_html__('US Dollars', 'datebook'); ?>. <br>
				<?php echo sprintf('%s <a href="%s" target="_blank">%s</a>', esc_html__('Ensure you are activated for the currency you are selecting', 'datebook'), esc_url('https://paystack.helpscoutdocs.com/article/38-can-paystack-process-payments-in-usd-international-currencies'), esc_html__('Check here for more information', 'datebook')); ?>
				 </td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Add Convenience Fee', 'datebook' ); ?></th>
				<td>
				<select class="form-control" name="_txncharge" id="parent_id">
					<option value="merchant" <?php echo esc_attr(self::datebook_item_selected('merchant', $txncharge)); ?>><?php echo esc_html__( 'No', 'datebook' ); ?></option>
					<option value="customer" <?php echo esc_attr(self::datebook_item_selected('customer', $txncharge)); ?>><?php echo esc_html__( 'Yes', 'datebook' ); ?></option>
				</select>
				<small><?php echo esc_html__( 'This adds an estimate of Paystack transaction local fee to the transaction amount. This cushions the effect of the fees on the merchant', 'datebook' ); ?></small>
				</td>
			</tr>
		</table>
		
		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Recurring Payment', 'datebook' ); ?></th>
				<td>
				<select class="form-control" name="_recur">
					<option value="no" <?php echo esc_attr(self::datebook_item_selected('no', $recur)); ?>><?php echo esc_html__( 'No', 'datebook' ); ?></option>
					<option value="optional" <?php echo esc_attr(self::datebook_item_selected('optional', $recur)); ?>><?php echo esc_html__( 'Optional recurring', 'datebook' ); ?></option>
					<option value="plan" <?php echo esc_attr(self::datebook_item_selected('plan', $recur)); ?>><?php echo esc_html__( 'Paystack plan', 'datebook' ); ?></option>
				</select>
				 </td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Paystack Recur Plan code', 'datebook' ); ?></th>
				<td><input type="text" name="_recurplan" value="<?php echo esc_attr($recurplan); ?>" class="regular-text" /><br>
				<small><?php echo esc_html__( 'Plan amount must match amount on extra form description', 'datebook' ); ?></small></td>
			</tr>
		</table>
		
		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Sub Account code', 'datebook' ); ?></th>
				<td><input type="text" name="_subaccount" value="<?php echo esc_attr($subaccount); ?>" class="regular-text" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Transaction Charge bearer', 'datebook' ); ?></th>
				<td>
				<select class="form-control" name="_txnbearer" id="parent_id">
					<option value="account" <?php echo esc_attr(self::datebook_item_selected('account', $txnbearer)); ?>><?php echo esc_html__( 'Merchant (default)', 'datebook' ); ?></option>
					<option value="subaccount" <?php echo esc_attr(self::datebook_item_selected('subaccount', $txnbearer)); ?>><?php echo esc_html__( 'Sub Account', 'datebook' ); ?></option>
				</select>
				</td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Merchant Amount', 'datebook' ); ?></th>
				<td><input type="text" name="_merchantamount" value="<?php echo esc_attr($merchantamount); ?>" class="regular-text" /></td>
			</tr>
		</table>
		
		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'User subscribes to plan after number of days', 'datebook' ); ?></th>
				<td><label><input name="_startdate_enabled" type="checkbox" value="1"<?php if ($startdate_enabled == 1){ echo ' checked'; } ?>><?php echo esc_html__( 'Yes', 'datebook' ); ?></label></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Number of days', 'datebook' ); ?></th>
				<td><input type="number" name="_startdate_days" value="<?php echo esc_attr($days); ?>" class="regular-text datebook-paystack-number" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Plan', 'datebook' ); ?></th>
				<td><input type="text" name="_startdate_plan_code" value="<?php echo esc_attr($plan); ?>" class="regular-text" /></td>
			</tr>
		</table>
		
		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th colspan="2" scope="row"><?php echo esc_html__( 'Paystack 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/paystack.png'); ?></td>
			</tr>

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

		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th colspan="2" scope="row"><strong><?php echo esc_html__( 'Fees Settings', 'datebook' ); ?></strong></th>
			</tr>

			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Percentage', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="prc" value="<?php echo esc_attr($prc); ?>" placeholder="1.5" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Threshold (amount above which Paystack adds the fixed amount below)', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="ths" value="<?php echo esc_attr($ths); ?>" placeholder="2500" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Additional Charge (amount added to percentage fee when transaction amount is above threshold)', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="adc" value="<?php echo esc_attr($adc); ?>" placeholder="100" /></td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Cap (maximum charge paystack can charge on your transactions)', 'datebook' ); ?></th>
				<td><input class="regular-text" type="text" name="cap" value="<?php echo esc_attr($cap); ?>" placeholder="2000" /></td>
			</tr>
		</table>
		
		<hr>

		<table class="form-table paystack_setting_page">
			<tr valign="top">
				<th colspan="2" scope="row"><?php echo esc_html__( 'Email settings', 'datebook' ); ?></th>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Send an invoices when a payment is attempted', 'datebook' ); ?></th>
				<td>
				<select class="form-control" name="_sendinvoice" id="parent_id">
					<option value="no" <?php echo esc_attr(self::datebook_item_selected('no', $sendinvoice)); ?>><?php echo esc_html__( 'No', 'datebook' ); ?></option>
					<option value="yes" <?php echo esc_attr(self::datebook_item_selected('yes', $sendinvoice)); ?>><?php echo esc_html__( 'Yes', 'datebook' ); ?></option>
				</select>
				</td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Send Email Receipt', 'datebook' ); ?></th>
				<td>
				<select class="form-control" name="_sendreceipt" id="parent_id">
					<option value="no" <?php echo esc_attr(self::datebook_item_selected('no', $sendreceipt)); ?>><?php echo esc_html__( 'No', 'datebook' ); ?></option>
					<option value="yes" <?php echo esc_attr(self::datebook_item_selected('yes', $sendreceipt)); ?>><?php echo esc_html__( 'Yes', 'datebook' ); ?></option>
				</select>
				</td>
			</tr>
			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Email Subject', 'datebook' ); ?></th>
				<td><input type="text" name="_subject" value="<?php echo esc_attr($subject); ?>" class="widefat" /></td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Email Heading', 'datebook' ); ?></th>
				<td><input type="text" name="_heading" value="<?php echo esc_attr($heading); ?>" class="widefat" /></td>
			</tr>

			<tr valign="top">
				<th scope="row"><?php echo esc_html__( 'Email Body/Message', 'datebook' ); ?></th>
				<td><textarea rows="6" name="_message" class="widefat"><?php echo esc_attr($message); ?></textarea></td>
			</tr>
		</table>
		

		<?php
	
		}

	}








	public function process_redirect_to_payment_gateway($payment_data){

		if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {

			// Hookable location. Allows other plugins use a fresh submission before it is saved to the database.

			global $wpdb, $datebook_currency_titles;

			if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
				$current_user_id = DATEBOOK_CURRENT_USER_ID;
			} else {
				global $current_user;
				wp_get_current_user();
				$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
			}

			$profile_id = get_user_meta( $current_user_id, 'profile_postid', true);
			$get_profile = get_post($profile_id);
			$fullname = $get_profile->post_title;

			$metadata = $_POST;

			unset($metadata['datebook_paystack_amount']);
			unset($metadata['datebook_paystack_interval']);
			unset($metadata['datebooktkn']);
			unset($metadata['_wp_http_referer']);
			unset($metadata['action']);
			unset($metadata['payment_page']);
			unset($metadata['subscriptionplan']);
			unset($metadata['subscriptionplan_period_key']);
			unset($metadata['pay_gate']);
			unset($metadata['whatisit']);

			$untouchedmetadata = datebook_paystack_meta_as_custom_fields($metadata);
			$fixedmetadata = [];
			
			//Get gateway array
			$item = get_option('datebook_gateways');
			$item = $item['paystack'];

			$default_currency = of_get_option('default_currency');
			$currency_code = $datebook_currency_titles[$default_currency][1];

			$currency = !empty($currency_code) ? $currency_code : 'NGN';
			$formamount = !empty($payment_data['amount']) ? $payment_data['amount'] : '';
			$recur = !empty($item['_recur']) ? $item['_recur'] : '';
			$subaccount = !empty($item['_subaccount']) ? $item['_subaccount'] : '';
			$txnbearer = !empty($item['_txnbearer']) ? $item['_txnbearer'] : '';
			$transaction_charge = !empty($item['_merchantamount']) ? $item['_merchantamount'] : 0;
			$transaction_charge = $transaction_charge * 100;

			$txncharge = isset($item['_txncharge']) ? $item['_txncharge'] : '';
			
			$amount = (int)str_replace(' ', '', $formamount);
			$originalamount = $amount;


			if (($recur == 'no') && ($formamount != 0)){
				$amount = (int)str_replace(' ', '', $formamount);
			}

			$fixedmetadata[] =  array(
				'display_name' => 'Unit Price',
				'variable_name' => 'Unit_Price',
				'type' => 'text',
				'value' => $currency . number_format($amount)
			);
			
			if (!($recur === 'optional' || $recur === 'plan')){
				$unitamount = (int)str_replace(' ', '', $amount);
				$amount = $unitamount;
			}

			if ($txncharge == 'customer'){
				$amount = datebook_paystack_add_paystack_charge($amount);
			}

			$plancode = 'none';

			if ($recur != 'no'){

				if ($recur == 'optional'){

					$interval = $_POST['datebook_paystack_interval'];

					if ($interval != 'no'){

						unset($metadata['datebook_paystack_interval']);

						$mode =  isset($item['mode']) ? $item['mode'] : '';

						if ($mode == 'test'){
							$key = isset($item['tsk']) ? $item['tsk'] : '';
						} else {
							$key = isset($item['lsk']) ? $item['lsk'] : '';
						}

						$koboamount = $amount * 100;
						
						//Create Plan
						$paystack_url = 'https://api.paystack.co/plan';
						$check_url = 'https://api.paystack.co/plan?amount=' . $koboamount . '&interval=' . $interval;
						$headers = array(
							'Content-Type'    => 'application/json',
							'Authorization' => 'Bearer ' . $key
						);

						$checkargs = array(
							'headers'    => $headers,
							'timeout'    => 60
						);

						// Check if plan exist
						$checkrequest = wp_remote_get(esc_url($check_url), $checkargs);

						if (!is_wp_error($checkrequest)){
							
							$response = json_decode(wp_remote_retrieve_body($checkrequest));

							if ($response->meta->total >= 1){

								$plan = $response->data[0];
								$plancode = $plan->plan_code;
								$fixedmetadata[] =  array(
									'display_name' => 'Plan Interval',
									'variable_name' => 'Plan Interval',
									'type' => 'text',
									'value' => $plan->interval
								);

							} else {

								//Create Plan
								$body = array(
									'name'     => $currency . number_format($originalamount).' ['.$currency.number_format($amount).'] - '.$interval,
									'amount'   => $koboamount,
									'interval' => $interval
								);
								$args = array(
									'body'     => json_encode($body),
									'headers'  => $headers,
									'timeout'  => 60
								);

								$request = wp_remote_post(esc_url($paystack_url), $args);

								if (! is_wp_error($request)){

									$paystack_response = json_decode(wp_remote_retrieve_body($request));
									$plancode    = $paystack_response->data->plan_code;
									$fixedmetadata[] =  array(
										'display_name' => 'Plan Interval',
										'variable_name' => 'Plan Interval',
										'type' => 'text',
										'value' => $paystack_response->data->interval
									);

								}
							}
						}
					}

				} else {

					//Use Plan Code
					$plancode = $_POST['datebook_paystack_plancode'];
					unset($metadata['datebook_paystack_plancode']);
				}
			}

			if ($plancode != 'none'){
				$fixedmetadata[] =  array(
					'display_name' => 'Plan',
					'variable_name' => 'Plan',
					'type' => 'text',
					'value' => $plancode
				);
			}

			$fixedmetadata = json_decode(json_encode($fixedmetadata, JSON_NUMERIC_CHECK), true);
			$fixedmetadata = array_merge($untouchedmetadata, $fixedmetadata);

			$code = datebook_paystack_generate_code();
			
			$table = strtolower($wpdb->prefix).DATEBOOK_PAYSTACK_TABLE;

			$insert =  array(
    		    'profile_id' => $profile_id,
        		'email' => $payment_data['user_email'],
	        	'user_id' => $current_user_id,
	    	    'amount' => $amount,
    	    	'plan' => $plancode,
				'ip' => datebook_paystack_get_the_user_ip(),
    	    	'txn_code' => $code,
	        	'metadata' => json_encode($fixedmetadata)
			);

			$exist = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE (profile_id = '%d'
				AND email = '%s'
				AND user_id = '%d'
				AND amount = '%s'
				AND plan = '%s'
				AND ip = '%s'
				AND paid = '0'
				AND metadata = '%s')", 

				$insert['profile_id'],
				$insert['email'],
				$insert['user_id'],
				$insert['amount'],
				$insert['plan'],
				$insert['ip'],
				$insert['metadata']

			));


			if (count($exist) > 0){

		        // $insert['txn_code'] = $code;
    		    // $insert['plan'] = $exist[0]->plan;
				$wpdb->update($table, array( 'txn_code' => $code, 'plan' => $insert['plan']), array('id' => $exist[0]->id));

			} else {

				$wpdb->insert($table, $insert);

				/*$sendinvoice = isset($item['_sendinvoice']) ? $item['_sendinvoice'] : 'no';
				if($sendinvoice == "yes"){
					datebook_paystack_send_invoice($currency, $insert['amount'], $fullname, $insert['email'], $code);
				}*/

		    }

		    if ($subaccount == "" || !isset($subaccount)){
		        $subaccount = null;
    		    $txnbearer = null;
        		$transaction_charge = null;
		    }

		    if ($transaction_charge == "" || $transaction_charge == 0 || $transaction_charge == null){
    		    $transaction_charge = null;
	    	}

		    $amount = floatval($insert['amount']) * 100;

		    $response = array(
				'paystack_id' => $payment_data['payment_id'],
    		    'result' => 'success',
        		'code' => $insert['txn_code'],
	        	'plan' => $insert['plan'],
	    	    'email' => $insert['email'],
    	    	'name' => $fullname,
	    	    'total' => round($amount),
    	    	'currency' => $currency,
	        	'custom_fields' => $fixedmetadata,
		        'subaccount' => $subaccount,
    		    'txnbearer' => $txnbearer,
        		'transaction_charge' => $transaction_charge
		    );

			wp_send_json($response);

		    die();
		
		}

	}


	public function datebook_paystack_confirm_payment(){

		$code = !empty($_POST['code']) ? trim($_POST['code']) : '';
		
		if ($code == ''){
    	    $response['error'] = true;
        	$response['error_message'] = 'Did you make a payment?';

			wp_send_json($response);

	        exit();
    	}

	    global $wpdb, $datebook_currency_titles;

		if (defined('DATEBOOK_CURRENT_USER_ID') && is_numeric(DATEBOOK_CURRENT_USER_ID)) {
			$current_user_id = DATEBOOK_CURRENT_USER_ID;
		} else {
			global $current_user;
			wp_get_current_user();
			$current_user_id = DateBook_Utilities::datebook_replace_user_by_admin($current_user->ID, 1);
		}

	    $table = strtolower($wpdb->prefix).DATEBOOK_PAYSTACK_TABLE;

		//Get gateway array
		$item = get_option('datebook_gateways');
		$item = $item['paystack'];

		$mode = isset($item['mode']) ? $item['mode'] : '';
		$tsk = isset($item['tsk']) ? $item['tsk'] : '';
		$lsk = isset($item['lsk']) ? $item['lsk'] : '';
	
		$record = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table WHERE (txn_code = '%s')", $code));

		if (array_key_exists('0', $record)){

			$payment_array = $record[0];
			
			$profile_id = isset($payment_array->profile_id) ? $payment_array->profile_id : 0;
			
			$amount = isset($payment_array->amount) ? $payment_array->amount : '';
			$recur = isset($item['_recur']) ? $item['_recur'] : '';
			
			$default_currency = of_get_option('default_currency');
			$currency_code = $datebook_currency_titles[$default_currency][1];
			
			$currency = isset($currency_code) ? $currency_code : 'NGN';
			$txncharge = isset($item['_txncharge']) ? $item['_txncharge'] : '';

	        $oamount = $amount;


			$mode =  esc_attr($mode);
    	    if ($mode == 'test'){
        	    $key = esc_attr($tsk);
	        } else {
    	        $key = esc_attr($lsk);
        	}

	        $paystack_url = 'https://api.paystack.co/transaction/verify/' . $code;
    	    $headers = array(
        		'Authorization' => 'Bearer ' . $key
	        );
    	    $args = array(
        		'headers'    => $headers,
		        'timeout'    => 60
        	);

	        $request = wp_remote_get($paystack_url, $args);

	        if (! is_wp_error($request) && 200 == wp_remote_retrieve_response_code($request)){

	            $paystack_response = json_decode(wp_remote_retrieve_body($request));

	            if ($paystack_response->data->status == 'success'){

	                $customer_code = $paystack_response->data->customer->customer_code;
    	            $amount_paid = $paystack_response->data->amount / 100;
        	        $paystack_ref = $paystack_response->data->reference;
            	    $paid_at = $paystack_response->data->transaction_date;

	                if ($recur == 'optional' || $recur == 'plan'){
						
	                    $wpdb->update($table, array( 'paid' => 1, 'amount' => $amount_paid, 'paid_at' => $paid_at), array('txn_code' => $paystack_ref));
    	                $message = esc_html__('Thank you for paying!', 'datebook');
        	            $result = 'success';

	                } else {
						
						// Goes here

	                    if ($amount == 0){

	                        $wpdb->update($table, array( 'paid' => 1,'amount' => $amount_paid, 'paid_at' => $paid_at), array('txn_code' => $paystack_ref));
	                        $message = esc_html__('Thank you for paying!', 'datebook');
    	                    $result = 'success';

	                    } else {

							$unitamount = (int)str_replace(' ', '', $amount);
							$oamount = $unitamount;
							
							if ($txncharge == 'customer'){
								if ($amount != 0){
									$oamount = datebook_paystack_add_paystack_charge($oamount);
								}
							}


							if ($txncharge == 'customer'){
								$amount = datebook_paystack_add_paystack_charge($amount);
							}
							if ($oamount !=  $amount_paid){
								$message = esc_html__('Invalid amount Paid. Amount required is', 'datebook') . ' ' . $currency . ' <strong>' . number_format($oamount) . '</strong>';
								$result = 'failed';
							} else {
								$wpdb->update($table, array( 'paid' => 1, 'paid_at' => $paid_at), array('txn_code'=>$paystack_ref));
								$message = esc_html__('Thank you for paying!', 'datebook');
								$result = 'success';
							}
						}
					}
				} else {
					$message = esc_html__('Transaction Failed/Invalid Code', 'datebook');
					$result = 'failed';
	            }
    	    } else {
        	    $message = esc_html__('Payment Verifiction Failed', 'datebook');
            	$result = 'failed';
	        }

	    } else {

	        $message = esc_html__('Payment Verifiction Failed', 'datebook');
    	    $result = 'failed';

	    }

	    if ($result == 'success'){

	        //Create Plan
    	    $enabled_custom_plan = isset($item['_startdate_enabled']) ? $item['_startdate_enabled'] : '';

	        if ($enabled_custom_plan == 1){

				$mode =  esc_attr($mode);
    		    if ($mode == 'test'){
        		    $key = esc_attr($tsk);
	        	} else {
    	        	$key = esc_attr($lsk);
	        	}

	            //Create Plan
    	        $paystack_url = 'https://api.paystack.co/subscription';
        	    $headers = array(
            		'Content-Type'    => 'application/json',
		            'Authorization' => 'Bearer ' . $key
    	        );

	            $custom_plan = isset($item['_startdate_plan_code']) ? $item['_startdate_plan_code'] : '';
    	        $days = isset($item['_startdate_days']) ? $item['_startdate_days'] : '';

	            $start_date = date("c", strtotime("+" . $days . " days"));

	            $body = array(
    		        'start_date'    => $start_date,
            		'plan'            => $custom_plan,
		            'customer'        => $customer_code
       		    );

	            $args = array(
    		        'body'        => json_encode($body),
            		'headers'    => $headers,
		            'timeout'    => 60
        	    );

				$request = wp_remote_post(esc_url($paystack_url), $args);

				if (! is_wp_error($request)){

					$paystack_response = json_decode(wp_remote_retrieve_body($request));
					$plancode = $paystack_response->data->subscription_code;
					// $message.= $message.'Subscribed<br>'.$plancode.'sssss';

	            }
    	    }
			
			//////////////////////////////////////////
			// Get payment id
			$payment_id = isset( $_POST['paystack_id'] ) ? $_POST['paystack_id'] : 0;

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

			// 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 = isset($payment->subscription_id) ? $payment->subscription_id : 0;
				$subscription_plan_price_period = isset($payment->plan_price_period) ? $payment->plan_price_period : 0;
				$subscription_plan_user_id = isset($payment->user_id) ? $payment->user_id : 0;
				$subscription_plan_amount = isset($payment->amount) ? $payment->amount : 0;
				
				$subscription_plan_start_date = isset($payment->start_date) ? $payment->start_date : date('Y-m-d H:i:s');
				$subscription_plan_expiration_date = isset($payment->expiration_date) ? $payment->expiration_date : date('Y-m-d H:i:s');
				
				$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $current_user_id ) );
				$member_start_date = isset($member_subscriptions[0]->start_date) ? $member_subscriptions[0]->start_date : date( 'Y:m:d H:i:s' );
				$member_expiration_date = isset($member_subscriptions[0]->expiration_date) ? $member_subscriptions[0]->expiration_date : date( 'Y:m:d H:i:s' );
				
				$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'	=> '',

					'status'			=> 'active',

					'price'				=> $subscription_plan_amount,
					'recurring'			=> 0,
					'starts'			=> $member_start_date,
					'ends'				=> $member_expiration_date
				);

				$payment_data['payment_gateway'] = 'paystack';
				
				// 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);

			}

	    }

	    $response = array(
			'result' => $result,
			'message' => $message
		);

		wp_send_json($response);

	    die();

	}

}


class DateBook_Paystack_Class {


	/**
	 * The loader that's responsible for maintaining and registering all hooks that power the plugin.
	 *
	 * @access protected
	 * @var  Paystack_Forms_Loader  $loader  Maintains and registers all hooks for the plugin.
	 */
	protected $loader;


	/**
	 * Define the core functionality of the plugin.
	 *
	 * Set the plugin name and the plugin version that can be used throughout the plugin.
	 * Load the dependencies, define the locale, and set the hooks for the admin area and
	 * the public-facing side of the site.
	 */
	public function __construct(){

		add_action( 'admin_enqueue_scripts', array( $this, 'define_admin_hooks' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'define_public_hooks' ) );

	}


	/**
	 * Register all of the hooks related to the admin area functionality.
	 *
	 * @access private
	 */
	public function define_admin_hooks(){

		wp_enqueue_script('datebook-paystack', plugin_dir_url(__FILE__) . 'js/paystack-admin.js', array( 'jquery' ), '', false);

	}
	
	

	/**
	 * Register all of the hooks related to the public-facing functionality.
	 *
	 * @access private
	 */
	public function define_public_hooks(){

		if(get_the_ID() == of_get_option('my_upgrade_page')){

			wp_enqueue_script('blockUI', plugin_dir_url(__FILE__) . 'js/jquery.blockUI.min.js', array( 'jquery' ), '', true, true);
			wp_enqueue_script('jQuery_UI', plugin_dir_url(__FILE__) . 'js/jquery.ui.min.js', array( 'jquery' ), '', true, true);
			wp_register_script('Paystack', 'https://js.paystack.co/v1/inline.js', false, '1');
			wp_enqueue_script('Paystack');

			wp_enqueue_script('paystack-frontend', plugin_dir_url(__FILE__) . 'js/paystack-frontend.js', array( 'jquery' ), '', true, true);

			$page_my_upgrade_ajax = esc_url(get_permalink(of_get_option('my_upgrade_page')));

			wp_localize_script('paystack-frontend', 'datebookpaystacksettings', array(
				'key'=> DateBook_Paystack_Frontend::fetchPublicKey(), 
				'fee'=>DateBook_Paystack_Frontend::fetchFeeSettings(),
				'ajax_paystack_url' => $page_my_upgrade_ajax,
				), 
				'', 
				true, 
				true
			);
		
		}

	}


}

$DateBook_Paystack_Class = new DateBook_Paystack_Class();


/*
WooCommerce

<link rel='dns-prefetch' href='//js.paystack.co' />
<script type='text/javascript' src='https://js.paystack.co/v1/inline.js?ver=1' id='Paystack-js'></script>

<form name="checkout" method="post" class="checkout woocommerce-checkout" action="https://pagickthemes1.com/mypage-2/checkout/" enctype="multipart/form-data" novalidate="novalidate">
<input type="hidden" class="input-text form-control" name="billing_email" id="billing_email" placeholder="" value="avemaria2004@yandex.ru" autocomplete="email username">
<input id="payment_method_bacs" type="radio" class="input-radio" name="payment_method" value="bacs" data-order_button_text="">

<input id="payment_method_paystack" type="radio" class="input-radio" name="payment_method" value="paystack" checked="checked" data-order_button_text="">
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="terms" id="terms">
<input type="hidden" name="terms-field" value="1">
<button type="submit" class="button alt btn btn-lg btn-primary text-white" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>

<input type="hidden" id="woocommerce-process-checkout-nonce" name="woocommerce-process-checkout-nonce" value="c12c147162">
<input type="hidden" name="_wp_http_referer" value="/?wc-ajax=update_order_review">
				
</form>
*/

/*
DateBook
<link rel='dns-prefetch' href='//js.paystack.co' />
<script type='text/javascript' src='https://js.paystack.co/v1/inline.js?ver=1' id='Paystack-js'></script>

<form enctype="multipart/form-data" action="https://pagickthemes1.com/mypage-2/upgrade/" url="https://pagickthemes1.com/mypage-2/upgrade/" method="post" class="datebook-paystack-form j-forms" novalidate="">
<input type="hidden" id="datebooktkn" name="datebooktkn" value="a3ba474fcc">
<input type="hidden" name="_wp_http_referer" value="/mypage-2/upgrade/">
<input type="hidden" name="action" value="payment_page">
<input type="hidden" name="payment_page" value="3">
<input name="subscriptionplan" type="hidden" value="28821538858010">
<input name="subscriptionplan_period_key" type="hidden" value="0">
<input type="hidden" name="pay_gate" value="paystack">
<input type="hidden" name="email" value="aaaa@aaaaa.com22">
<button class="btn btn-primary waves-effect waves-light" name="submit" value="paystack" type="submit">Subscribe</button>
</form>
*/


