/**
 * Send HTTP POST Request
 *
 * @param	string	The API method name
 * @param	string	The POST Message fields in &name=value pair format
 * @return	array	Parsed HTTP Response body
 */
function PPHttpPost($methodName_, $nvpStr_)
{
    $adaptive_pay_settings = getAdaptivePayPalSettings();
    if ($adaptive_pay_settings->paypal_mode == "sandbox") {
        $environment = 'sandbox';
    } else {
        $environment = 'live';
    }
    //global $environment;
    // Set up your API credentials, PayPal end point, and API version.
    $API_UserName = urlencode($adaptive_pay_settings->api_username);
    $API_Password = urlencode($adaptive_pay_settings->api_password);
    $API_Signature = urlencode($adaptive_pay_settings->api_signature);
    $API_Endpoint = "https://api-3t.paypal.com/nvp";
    if ("sandbox" === $environment || "beta-sandbox" === $environment) {
        $API_Endpoint = "https://api-3t.{$environment}.paypal.com/nvp";
    }
    $version = urlencode('51.0');
    // Set the curl parameters.
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    // Turn off the server and peer verification (TrustManager Concept).
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    // Set the API operation, version, and API signature in the request.
    $nvpreq = "METHOD={$methodName_}&VERSION={$version}&PWD={$API_Password}&USER={$API_UserName}&SIGNATURE={$API_Signature}{$nvpStr_}";
    // Set the request as a POST FIELD for curl.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
    // Get response from the server.
    $httpResponse = curl_exec($ch);
    if (!$httpResponse) {
        exit("{$methodName_} failed: " . curl_error($ch) . '(' . curl_errno($ch) . ')');
    }
    // Extract the response details.
    $httpResponseAr = explode("&", $httpResponse);
    $httpParsedResponseAr = array();
    foreach ($httpResponseAr as $i => $value) {
        $tmpAr = explode("=", $value);
        if (sizeof($tmpAr) > 1) {
            $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
        }
    }
    if (0 == sizeof($httpParsedResponseAr) || !array_key_exists('ACK', $httpParsedResponseAr)) {
        exit("Invalid HTTP Response for POST request({$nvpreq}) to {$API_Endpoint}.");
    }
    return $httpParsedResponseAr;
}
 function id_purchase_form()
 {
     $project = new ID_Project($this->project_id);
     $the_project = $project->the_project();
     $project_id = $this->project_id;
     $post_id = $project->get_project_postid();
     $project_settings = $project->get_project_settings();
     if (empty($prod_settings)) {
         $defaults = $project->get_project_defaults();
         $project_settings = $defaults;
     }
     $no_levels = get_post_meta($post_id, "ign_product_level_count", true);
     $project_type = get_post_meta($post_id, 'ign_project_type', true);
     $project_desc = get_post_meta($post_id, "ign_product_level_1_desc", true);
     $level_data = $project->get_level_data($post_id, $no_levels);
     // level one stuff
     $level_one_data = new stdClass();
     $is_level_invalid = getLevelLimitReached($this->project_id, $post_id, 1);
     $meta_title = $the_project->ign_product_title;
     $meta_price = get_post_meta($post_id, "ign_product_price", true);
     $meta_desc = $the_project->product_details;
     $meta_order = get_post_meta($post_id, 'ign_projectmeta_level_order', true);
     $level_one_data->is_level_invalid = $is_level_invalid;
     $level_one_data->meta_title = $meta_title;
     $level_one_data->meta_price = $meta_price;
     $level_one_data->meta_desc = $meta_desc;
     $level_one_data->meta_order = $meta_order;
     $level_one_data->id = 1;
     // add level one to object
     array_unshift($level_data, $level_one_data);
     $custom_level_order = get_post_meta($post_id, 'custom_level_order', true);
     if ($custom_level_order) {
         usort($level_data, 'ID_Project::level_sort');
     }
     //GETTING the currency symbols
     $currencyCodeValue = $project_settings->currency_code;
     $cCode = setCurrencyCode($currencyCodeValue);
     //GETTING the form settings
     $form_settings = getProductFormSettings($project_id);
     if (!isset($form_settings)) {
         $form_settings = $project_settings->form_settings;
         $form_settings = unserialize($form_settings);
     } else {
         $form_settings = unserialize($form_settings);
     }
     $form_id = rand(21927391, 92817275);
     // Getting the Payment method first, to load the appropriate URLs if needed and
     // submit button name
     // this is paypal code that could be removed if disabled
     $payment_method = getDefaultPaymentMethod();
     if (isset($payment_method) && $payment_method->payment_gateway == "adaptive_paypal") {
         $adaptive_pay_settings = getAdaptivePayPalSettings();
         if (isset($adaptive_pay_settings)) {
             if ($adaptive_pay_settings->paypal_mode == "sandbox") {
                 $paypal_address = "https://www.sandbox.paypal.com/webapps/adaptivepayment/flow/pay";
             } else {
                 $paypal_address = "https://www.paypal.com/webapps/adaptivepayment/flow/pay";
             }
             if ($adaptive_pay_settings->fund_type == 'fixed') {
                 $submit_btn_name = 'btnSubmitPreapproval';
             } else {
                 $submit_btn_name = "submitPaymentAdaptive";
             }
         }
     } else {
         $submit_btn_name = "submitPaymentPopup";
         //will be caught by standard payments function for Paypal
     }
     $purchase_form = new stdClass();
     $purchase_form->project_id = $project_id;
     $purchase_form->post_id = $post_id;
     $purchase_form->the_project = $the_project;
     $purchase_form->project_settings = $project_settings;
     $purchase_form->no_levels = $no_levels;
     $purchase_form->level_data = $level_data;
     $purchase_form->project_type = $project_type;
     $purchase_form->project_desc = $project_desc;
     $purchase_form->currencyCodeValue = $currencyCodeValue;
     $purchase_form->cCode = $cCode;
     $purchase_form->form_settings = $form_settings;
     $purchase_form->form_id = $form_id;
     if (isset($paypal_address)) {
         $purchase_form->paypal_address = $paypal_address;
     }
     $purchase_form->submit_btn_name = $submit_btn_name;
     if (isset($adaptive_pay_settings)) {
         $purchase_form->adaptive_pay_settings = $adaptive_pay_settings;
     }
     return $purchase_form;
 }
function idpp_process_handler()
{
    global $wpdb;
    $product_id = $_POST['Project'];
    $sql = $wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'ign_pay_info WHERE product_id = %s AND status=%s', $product_id, 'W');
    //echo $sql;
    $res = $wpdb->get_results($sql);
    //print_r($res);
    $adaptive_pay_settings = getAdaptivePayPalSettings();
    // GETTING product default settings
    $default_prod_settings = getProductDefaultSettings();
    // Getting product settings and if they are not present, set the default settings as product settings
    $prod_settings = getProductSettings($product_id);
    if (empty($prod_settings)) {
        $prod_settings = $default_prod_settings;
    }
    require_once 'paypal/lib/AdaptivePayments.php';
    # Endpoint: this is the server URL which you have to connect for submitting your API request.
    //Chanege to https://svcs.paypal.com/  to go live */
    if ($adaptive_pay_settings->paypal_mode == "sandbox") {
        define('API_BASE_ENDPOINT', 'https://svcs.sandbox.paypal.com/');
        define('PAYPAL_REDIRECT_URL', 'https://www.sandbox.paypal.com/webscr&cmd=');
        $app_id = "APP-80W284485P519543T";
    } else {
        define('API_BASE_ENDPOINT', 'https://svcs.paypal.com/');
        define('PAYPAL_REDIRECT_URL', 'https://www.paypal.com/webscr&cmd=');
        $app_id = $adaptive_pay_setings->app_id;
    }
    /***** 3token API credentials *****************/
    define('API_AUTHENTICATION_MODE', '3token');
    define('API_USERNAME', $adaptive_pay_settings->api_username);
    define('API_PASSWORD', $adaptive_pay_settings->api_password);
    define('API_SIGNATURE', $adaptive_pay_settings->api_signature);
    require_once 'paypal/lib/Config/paypal_sdk_clientproperties.php';
    $no_success = array();
    $no_failures = array();
    foreach ($res as $payment) {
        if ($payment->preapproval_key !== '') {
            // Setting the necessary variables for the payment
            $returnURL = site_url('/');
            $cancelURL = site_url('/');
            $notifyURL = site_url('/') . '?ipn_handler=1';
            $currencyCode = $prod_settings->currency_code;
            $email = $payment->email;
            $preapprovalKey = $payment->preapproval_key;
            $requested = '';
            $payRequest = new PayRequest();
            $payRequest->actionType = "PAY";
            $payRequest->cancelUrl = $cancelURL;
            $payRequest->returnUrl = $returnURL;
            $payRequest->ipnNotificationUrl = $notifyURL;
            $payRequest->clientDetails = new ClientDetailsType();
            $payRequest->clientDetails->applicationId = $app_id;
            //"APP-1JE4291016473214C";
            //$payRequest->clientDetails->deviceId = DEVICE_ID;
            $payRequest->clientDetails->ipAddress = $_SERVER['REMOTE_ADDR'];
            $payRequest->currencyCode = $currencyCode;
            $payRequest->senderEmail = html_entity_decode($email);
            $payRequest->requestEnvelope = new RequestEnvelope();
            $payRequest->requestEnvelope->errorLanguage = "en_US";
            //$payRequest->preapprovalKey = "PA-16707604HP296522Y";
            //print_r($payRequest);
            if ($preapprovalKey !== "") {
                $payRequest->preapprovalKey = $preapprovalKey;
                //echo $preapprovalKey."keyhere";
            }
            $receiver1 = new receiver();
            $receiver1->email = $adaptive_pay_settings->paypal_email;
            $receiver1->amount = $payment->prod_price;
            $payRequest->receiverList = new ReceiverList();
            $payRequest->receiverList = array($receiver1);
            /* 	Make the call to PayPal to get the Pay token
             *	If the API call succeded, then redirect the buyer to PayPal
             *	to begin to authorize payment.  If an error occured, show the
             *	resulting errors
             */
            $ap = new AdaptivePayments();
            $response = $ap->Pay($payRequest);
            //echo "end of line<br/>";
            if (strtoupper($ap->isSuccess) == 'SUCCESS') {
                $no_success[] = 'success';
            } else {
                if (strtoupper($ap->isSuccess) == 'FAILURE') {
                    $no_failures[] = 'failure';
                    //echo "inside failure<br/>";
                    $fault = $ap->getLastError();
                    $errors_content = $fault->error->message;
                    //echo $errors_content;
                    // For error handling
                    /*if (is_object($fault->error))
                    				{ 
                    
                    					//$errors_content = '<table width =\"450px\" align=\"center\">';
                    					$errors_content;
                    					$errors_content = '';
                    					foreach($fault->error as $err) {
                    
                    						//$errors_content .= '<tr>';
                    						//$errors_content .= '<td>';
                    						//$errors_content .= 'Error ID: ' . $err->errorId . '<br />';
                    						//$errors_content .= 'Domain: ' . $err->domain . '<br />';
                    						//$errors_content .= 'Severity: ' . $err->severity . '<br />';
                    						//$errors_content .= 'Category: ' . $err->category . '<br />';
                    						$errors_content .= $err . "<br />";
                    
                    						if(empty($err->parameter)) {
                    							//$errors_content .= '<br />';
                    						}
                    						else {
                    							//$errors_content .= 'Parameter: ' . $err->parameter . '<br /><br />';
                    						}
                    							
                    						//$errors_content .= '</td>';
                    						//$errors_content .= '</tr>';
                    					}
                    					//$errors_content .= '</table>';
                    				}
                    				else
                    				{
                    
                    					$errors_content = "";
                    					//$errors_content .= 'Error ID: ' . $fault->error->errorId . '<br />';
                    					//$errors_content .= 'Domain: ' . $fault->error->domain . '<br />';
                    					//$errors_content .= 'Severity: ' . $fault->error->severity . '<br />';
                    					//$errors_content .= 'Category: ' . $fault->error->category . '<br />';
                    					$errors_content .= $fault->error->message . '<br />';
                    					if(empty($fault->error->parameter)) {
                    						//$errors_content .= '</br>';
                    					}
                    					else {
                    						//$errors_content .= 'Parameter: ' . $fault->error->parameter . '<br /><br />';
                    					}
                    				}*/
                }
            }
        }
    }
    $response_array['counts'] = array('success' => count($no_success), 'failures' => count($no_failures));
    print_r(json_encode($response_array));
    exit;
}
function adaptivePreapproval()
{
    if (isset($_POST['btnSubmitPreapproval'])) {
        global $wpdb;
        $tz = get_option('timezone_string');
        if (empty($tz)) {
            $tz = 'UTC';
        }
        date_default_timezone_set($tz);
        //print_r($_POST);
        session_start();
        $payment_variables = array("fname" => $_POST['first_name'], "lname" => $_POST['last_name'], "email" => $_POST['email'], "address" => $_POST['address'], "country" => $_POST['country'], "state" => $_POST['state'], "city" => $_POST['city'], "zip" => $_POST['zip'], "product_id" => absint($_POST['project_id']), "level" => absint($_POST['level']), "prod_price" => str_replace(',', '', $_POST['price']));
        $preapproval_key = "";
        $project = new ID_Project($variables['product_id']);
        $post_id = $project->get_project_postid();
        $product_name = get_the_title($post_id);
        $_SESSION['ig_payment_variables'] = http_build_query($payment_variables);
        // Getting the Adaptive payment settings
        $adaptive_pay_settings = getAdaptivePayPalSettings();
        require_once 'paypal/lib/AdaptivePayments.php';
        // GETTING product default settings
        $default_prod_settings = getProductDefaultSettings();
        // Getting product settings and if they are not present, set the default settings as product settings
        $prod_settings = getProductSettings(absint(esc_attr($_POST['project_id'])));
        if (empty($prod_settings)) {
            $prod_settings = $default_prod_settings;
        }
        # Endpoint: this is the server URL which you have to connect for submitting your API request.
        //Chanege to https://svcs.paypal.com/  to go live */
        if ($adaptive_pay_settings->paypal_mode == "sandbox") {
            define('API_BASE_ENDPOINT', 'https://svcs.sandbox.paypal.com/AdaptivePayments/Preapproval/');
            define('PAYPAL_REDIRECT_URL', 'https://www.sandbox.paypal.com/webscr&cmd=_ap-preapproval&preapprovalkey=' . $preapproval_key);
            $app_id = "APP-80W284485P519543T";
        } else {
            define('API_BASE_ENDPOINT', 'https://svcs.paypal.com/AdaptivePayments/Preapproval/');
            define('PAYPAL_REDIRECT_URL', 'https://www.paypal.com/webscr&cmd=_ap-preapproval&preapprovalkey=' . $preapproval_key);
            $app_id = $adaptive_pay_settings->app_id;
        }
        /***** 3token API credentials *****************/
        define('API_AUTHENTICATION_MODE', '3token');
        define('API_USERNAME', $adaptive_pay_settings->api_username);
        define('API_PASSWORD', $adaptive_pay_settings->api_password);
        define('API_SIGNATURE', $adaptive_pay_settings->api_signature);
        define('X_PAYPAL_APPLICATION_ID', $app_id);
        require_once 'paypal/lib/Config/paypal_sdk_clientproperties.php';
        $returnURL = site_url() . "/?payment_success=1&product_id=" . absint(esc_attr($_POST['project_id']));
        $cancelURL = site_url() . "/?payment_cancel=1";
        $notifyURL = esc_url(site_url()) . "/?ipn_handler=1&type=paypal_preauth&" . $_SESSION['ig_payment_variables'];
        $currencyCode = $prod_settings->currency_code;
        $senderEmail = esc_attr($_POST['email']);
        $preauth = new PreapprovalRequest();
        $preauth->cancelUrl = $cancelURL;
        $preauth->ipnNotificationUrl = $notifyURL;
        $preauth->returnUrl = $returnURL;
        $preauth->currencyCode = $currencyCode;
        $preauth->maxNumberOfPayments = "1";
        $preauth->maxNumberofPaymentsPerPeriod = 1;
        $preauth->endingDate = date("Y-m-d\\Z", strtotime("+ 364 day"));
        $preauth->startingDate = date('Y-m-d\\Z');
        $preauth->maxTotalAmountOfAllPayments = esc_attr(str_replace(',', '', $_POST['price']));
        $preauth->memo = $product_name . ' pledge of ' . number_format($_POST['price'], 2, '.', ',') . ' ' . $currencyCode;
        $preauth->clientDetails = new ClientDetailsType();
        $preauth->clientDetails->applicationId = $app_id;
        //$preauth->clientDetails->deviceId = DEVICE_ID;
        //$preauth->clientDetails->ipAddress = "127.0.0.1";
        //$preapprovalRequest->maxNumberOfPayments = $maxNumberOfPayments;
        //$preapprovalRequest->maxTotalAmountOfAllPayments = $maxTotalAmountOfAllPayments;
        $preauth->requestEnvelope = new RequestEnvelope();
        $preauth->requestEnvelope->errorLanguage = "en_US";
        $preauth->senderEmail = $senderEmail;
        $ap = new AdaptivePayments();
        $response = $ap->Preapproval($preauth);
        //print_r($preauth);
        //print_r($response);
        //print_r($ap);
        if (strtoupper($ap->isSuccess) == 'FAILURE') {
            $fault = $ap->getLastError();
            // For error handling
            if (is_array($fault->error)) {
                $errors_content = '<table width =\\"450px\\" align=\\"center\\">';
                foreach ($fault->error as $err) {
                    $errors_content .= '<tr>';
                    $errors_content .= '<td>';
                    $errors_content .= 'Error ID: ' . $err->errorId . '<br />';
                    $errors_content .= 'Domain: ' . $err->domain . '<br />';
                    $errors_content .= 'Severity: ' . $err->severity . '<br />';
                    $errors_content .= 'Category: ' . $err->category . '<br />';
                    $errors_content .= 'Message: ' . $err->message . '<br />';
                    if (empty($err->parameter)) {
                        $errors_content .= '<br />';
                    } else {
                        $errors_content .= 'Parameter: ' . $err->parameter . '<br /><br />';
                    }
                    $errors_content .= '</td>';
                    $errors_content .= '</tr>';
                }
                $errors_content .= '</table>';
            } else {
                $errors_content = 'Error ID: ' . $fault->error->errorId . '<br />';
                $errors_content .= 'Domain: ' . $fault->error->domain . '<br />';
                $errors_content .= 'Severity: ' . $fault->error->severity . '<br />';
                $errors_content .= 'Category: ' . $fault->error->category . '<br />';
                $errors_content .= 'Message: ' . $fault->error->message . '<br />';
                if (empty($fault->error->parameter)) {
                    $errors_content .= '</br>';
                } else {
                    $errors_content .= 'Parameter: ' . $fault->error->parameter . '<br /><br />';
                }
            }
            $_SESSION['paypal_errors_content'] = $errors_content;
        } else {
            // Redirect to paypal.com here
            $_SESSION['preapprovalKey'] = $response->preapprovalKey;
            $token = $response->preapprovalKey;
            $payPalURL = PAYPAL_REDIRECT_URL . '_ap-preapproval&preapprovalkey=' . $token;
            echo '<script type="text/javascript">window.location="' . $payPalURL . '";</script>';
        }
    }
}
//define('API_SIGNATURE', 'Abg0gYcQyxQvnf2HDJkKtA-p6pqhA1k-KTYE0Gcy1diujFio4io5Vqjf');
/**
 * specifies the Log file path.
 * 
 */
define('LOGFILENAME', 'logs/paypal_platform.log');
/**
 * Use the following setting (false) if you are testing or using SDK against live PayPal's production server
 * 
 */
define('TRUST_ALL_CONNECTION', false);
/**
 * 
 * Defines the SDK Version, Request and Response message formats.
 */
define('SDK_VERSION', 'PHP_SOAP_SDK_V1.4');
$adaptive_pay_settings = getAdaptivePayPalSettings();
if ($adaptive_pay_settings->paypal_mode == "sandbox") {
    $app_id = "APP-80W284485P519543T";
} else {
    $app_id = $adaptive_pay_settings->app_id;
}
define('X_PAYPAL_APPLICATION_ID', $app_id);
//define('X_PAYPAL_APPLICATION_ID','APP-80W284485P519543T');
//Binding options -> SOAP11,XML,JSON
define('X_PAYPAL_REQUEST_DATA_FORMAT', 'SOAP11');
define('X_PAYPAL_RESPONSE_DATA_FORMAT', 'SOAP11');
/*
 * IP Address of the device
 */
define('X_PAYPAL_DEVICE_IPADDRESS', '127.0.0.1');