/**
 * Action called when a transaction is completed from iT Exchange
 */
function iditexch_complete_order($transaction, $old_status, $old_status_cleared, $status)
{
    $transaction_id = $transaction->ID;
    // Getting ID orders belonging to the that iT Exchange transaction
    $orders = maybe_unserialize(get_post_meta($transaction_id, '_itexch_order_pairing', true));
    if (!empty($orders)) {
        foreach ($orders as $order) {
            if (!empty($order)) {
                // If transaction is set to clear for delivery
                if ($status == 'Completed') {
                    $update = setOrderStatus('C', $order);
                } else {
                    $update = setOrderStatus('P', $order);
                }
            }
        }
    }
}
function IPNHandler($wp)
{
    //if (isset($_GET['ipn_handler'])) {
    global $wpdb;
    $tz = get_option('timezone_string');
    if (empty($tz)) {
        $tz = 'UTC';
    }
    date_default_timezone_set($tz);
    //unlink("log.txt");
    //================================================================================================================
    //		Adaptive Payment IPN for PayPal code
    //================================================================================================================
    //$filetest_handler = fopen("log.txt", 'a+');
    ini_set('post_max_size', '12M');
    //fwrite($filetest_handler, "ini is set so we are increasing post size \n");
    $data_array = array();
    $payment_complete = false;
    $approved = false;
    $status = null;
    $vars = array();
    foreach ($_POST as $key => $val) {
        //fwrite($filetest_handler, $key."=".$val."\n");
        $data1 = explode("=", $key);
        $data2 = explode("=", $val);
        $key = $data1[0];
        $val = $data2[0];
        $vars[$key] = $val;
        if ($data1[0] == "payment_status" && strtoupper($data2[0]) == "COMPLETED") {
            $payment_complete = true;
            //fwrite($filetest_handler, $payment_complete);
        } else {
            if ($data1[0] == "payment_status" && strtoupper($data2[0]) == "PENDING") {
                $payment_complete = true;
                $payment_pending = true;
                //fwrite($filetest_handler, $payment_complete);
            } else {
                if ($data1[0] == "status") {
                    //fwrite($filetest_handler, 'it does equal status');
                    if (strtoupper($data2[0]) == "COMPLETED") {
                        if (isset($vars['preapproval_key'])) {
                            $preauth_key = esc_attr($vars['preapproval_key']);
                            $sender_email = esc_attr($vars['sender_email']);
                            $status = 'C';
                            $txn_id = esc_attr($vars['pay_key']);
                            $sql = $wpdb->prepare('UPDATE ' . $wpdb->prefix . 'ign_pay_info SET status=%s, transaction_id=%s WHERE email = %s AND preapproval_key = %s', $status, $txn_id, $sender_email, $preauth_key);
                            //fwrite($filetest_handler, $sql);
                            $res = $wpdb->query($sql);
                        } else {
                            $payment_complete = true;
                            //fwrite($filetest_handler, $payment_complete);
                        }
                    } else {
                        if (strtoupper($data2[0]) == "ACTIVE") {
                            //fwrite($filetest_handler, 'it should equal active');
                            $status = 'active';
                            //fwrite($filetest_handler, $status);
                        }
                    }
                }
            }
        }
        if ($data1[0] == "approved" && strtoupper($data2[0]) == "TRUE") {
            //fwrite($filetest_handler, 'it should equal true');
            $approved = true;
            //fwrite($filetest_handler, $approved);
        }
        if ($approved == true && $status == 'active') {
            $preauth_complete = true;
            //fwrite($filetest_handler, 'preauthcomplete '. $preauth_complete);
        }
    }
    foreach ($vars as $key => $val) {
        //fwrite($filetest_handler, 'key->'.$key.'='.'val->'.$val);
    }
    if ($payment_complete) {
        //fwrite($filetest_handler, 'payment is complete'."\n");
        if (isset($vars['txn_id'])) {
            $txn_id = esc_attr($vars['txn_id']);
        } else {
            $txn_id = esc_attr($vars['pay_key']);
        }
        $check = $wpdb->prepare('SELECT id FROM ' . $wpdb->prefix . 'ign_pay_info WHERE transaction_id = %s', $txn_id);
        //fwrite($filetest_handler, $check);
        $checkres = $wpdb->get_row($check);
        if (empty($checkres)) {
            $query = "INSERT INTO " . $wpdb->prefix . "ign_pay_info (\r\n\t\t\t\t\t\t\tprod_price,\r\n\t\t\t\t\t\t\tfirst_name,\r\n\t\t\t\t\t\t\tlast_name,\r\n\t\t\t\t\t\t\temail,\r\n\t\t\t\t\t\t\taddress,\r\n\t\t\t\t\t\t\tcountry,\r\n\t\t\t\t\t\t\tstate,\r\n\t\t\t\t\t\t\tcity,\r\n\t\t\t\t\t\t\tzip,\r\n\t\t\t\t\t\t\tproduct_id,\r\n\t\t\t\t\t\t\ttransaction_id,\r\n\t\t\t\t\t\t\tproduct_level,\r\n\t\t\t\t\t\t\tcreated_at\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tvalues (\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['prod_price']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['fname']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['lname']) . "',\r\n\t\t\t\t\t\t\t'" . $_GET['email'] . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['address']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['country']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['state']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['city']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['zip']) . "',\r\n\t\t\t\t\t\t\t'" . absint($_GET['product_id']) . "',\r\n\t\t\t\t\t\t\t'" . $txn_id . "',\r\n\t\t\t\t\t\t\t'" . absint($_GET['level']) . "',\r\n\t\t\t\t\t\t\t'" . date('Y-m-d H:i:s') . "'\r\n\t\t\t\t\t\t)";
            //fwrite($filetest_handler, $query);
            //echo $query;exit;
            $res = $wpdb->query($query);
            $pay_info_id = $wpdb->insert_id;
            do_action('id_payment_success', $pay_info_id);
            //fwrite($filetest_handler, "\n".$pay_info_id);
            $_SESSION['ig_payinfo_id_latest'] = $pay_info_id;
            $_SESSION['ig_product_id_latest'] = esc_attr($_GET['product_id']);
            //$product = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix ."ign_products WHERE id = '".absint(esc_attr($_GET['product_id']))."'");
            // set order status
            if (isset($payment_pending) && $payment_pending == true) {
                setOrderStatus('P', $pay_info_id);
            } else {
                setOrderStatus('C', $pay_info_id);
            }
            //store transaction info in session
            $_SESSION['id_order'] = array('id' => $GLOBALS['transactionId'], 'product_id' => esc_attr($_GET['product_id']), 'shared-on-twitter' => false, 'shared-on-facebook' => false);
        } else {
            //fwrite($filetest_handler, $checkres);
        }
    } else {
        if (isset($preauth_complete)) {
            //fwrite($filetest_handler, 'preauth is complete \n');
            $num_payments = absint(esc_attr($_POST['current_number_of_payments']));
            $preauth_key = esc_attr($_POST['preapproval_key']);
            $current_attempts = absint(esc_attr($_POST['current_period_attempts']));
            $check = $wpdb->prepare('SELECT id FROM ' . $wpdb->prefix . 'ign_pay_info WHERE transaction_id = %s', $vars['preapproval_key']);
            $checkres = $wpdb->get_row($check);
            if (empty($checkres)) {
                $query = "INSERT INTO " . $wpdb->prefix . "ign_pay_info (\r\n\t\t\t\t\t\t\tprod_price,\r\n\t\t\t\t\t\t\tfirst_name,\r\n\t\t\t\t\t\t\tlast_name,\r\n\t\t\t\t\t\t\temail,\r\n\t\t\t\t\t\t\taddress,\r\n\t\t\t\t\t\t\tcountry,\r\n\t\t\t\t\t\t\tstate,\r\n\t\t\t\t\t\t\tcity,\r\n\t\t\t\t\t\t\tzip,\r\n\t\t\t\t\t\t\tproduct_id,\r\n\t\t\t\t\t\t\tpreapproval_key,\r\n\t\t\t\t\t\t\tproduct_level,\r\n\t\t\t\t\t\t\tstatus,\r\n\t\t\t\t\t\t\tcreated_at\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\tvalues (\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['prod_price']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['fname']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['lname']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['email']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['address']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['country']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['state']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['city']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['zip']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['product_id']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($vars['preapproval_key']) . "',\r\n\t\t\t\t\t\t\t'" . esc_attr($_GET['level']) . "',\r\n\t\t\t\t\t\t\t'W',\r\n\t\t\t\t\t\t\t'" . date('Y-m-d H:i:s') . "'\r\n\t\t\t\t\t\t)";
                //fwrite($filetest, $query);
                //echo $query;exit;
                $res = $wpdb->query($query);
                $pay_info_id = $wpdb->insert_id;
                do_action('id_payment_success', $pay_info_id);
            }
        } else {
            // read the post from PayPal system and add 'cmd'
            $req = 'cmd=_notify-validate';
            foreach ($_POST as $key => $value) {
                $value = urlencode(stripslashes($value));
                $req .= "&{$key}={$value}";
            }
            // post back to PayPal system to validate
            $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
            $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
            $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
            $fp = fsockopen('ssl://www.paypal.com', 443, $errno, $errstr, 30);
            if (!$fp) {
                //fwrite($filetest_handler, 'Paypal errored out');
            } else {
                fputs($fp, $header . $req);
                //fwrite($filetest_handler, 'Paypal was successful');
                while (!feof($fp)) {
                    $res = fgets($fp, 1024);
                    if (strcmp($res, "VERIFIED") == 0) {
                        // check the payment_status is Completed
                        // check that txn_id has not been previously processed
                        // check that receiver_email is your Primary PayPal email
                        // check that payment_amount/payment_currency are correct
                        // process payment
                        //fwrite($filetest_handler, $res."\n");
                        global $wpdb;
                        // Check if a new payment is made using the session variable set before making that payment
                        if (1) {
                            // Deserialize the payment variables and get them to work
                            //$payment_variables = urldecode($_GET['payment_vars']);
                            //$payment_variables = str_replace("\\","",$payment_variables);
                            //fwrite($filetest_handler, "Payment variables: ".$payment_variables."\n");
                            //$payment_variables = unserialize($payment_variables);
                            //fwrite($filetest_handler, "Payment variables array: ".$payment_variables."\n");
                            $query = "INSERT INTO " . $wpdb->prefix . "ign_pay_info (\r\n\t\t\t\t\t\t\t\t\t\tprod_price,\r\n\t\t\t\t\t\t\t\t\t\tfirst_name,\r\n\t\t\t\t\t\t\t\t\t\tlast_name,\r\n\t\t\t\t\t\t\t\t\t\temail,\r\n\t\t\t\t\t\t\t\t\t\taddress,\r\n\t\t\t\t\t\t\t\t\t\tcountry,\r\n\t\t\t\t\t\t\t\t\t\tstate,\r\n\t\t\t\t\t\t\t\t\t\tcity,\r\n\t\t\t\t\t\t\t\t\t\tzip,\r\n\t\t\t\t\t\t\t\t\t\tproduct_id,\r\n\t\t\t\t\t\t\t\t\t\ttransaction_id,\r\n\t\t\t\t\t\t\t\t\t\tproduct_level,\r\n\t\t\t\t\t\t\t\t\t\tcreated_at\r\n\t\t\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t\t\t\tvalues (\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['prod_price']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['fname']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['lname']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['email']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['address']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['country']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['state']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['city']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['zip']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['product_id']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['tx']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . esc_attr($_GET['level']) . "',\r\n\t\t\t\t\t\t\t\t\t\t'" . date('Y-m-d H:i:s') . "'\r\n\t\t\t\t\t\t\t\t\t)";
                            //echo $query;exit;
                            $res = $wpdb->query($query);
                            $pay_info_id = $wpdb->insert_id;
                            $_SESSION['ig_payinfo_id_latest'] = $pay_info_id;
                            $_SESSION['ig_product_id_latest'] = esc_attr($_GET['product_id']);
                            $product = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "ign_products WHERE id = '" . $_GET['product_id'] . "'");
                            // set order status
                            setOrderStatus('C', $pay_info_id);
                            // subscribe user to mailchimp
                            $order = getOrderById($pay_info_id);
                            $mailchip_settings = getMailchimpSettings();
                            $aweber_settings = getAweberSettings();
                            $product_settings = getProductSettings($product->id);
                            if ($product_settings != -1 && $product_settings->active_mailtype == "mailchimp") {
                                subscribeToMailchimp($order->email, array('first_name' => $order->first_name, 'last_name' => $order->last_name), $product->id);
                            } else {
                                if ($mailchip_settings->is_active) {
                                    subscribeToMailchimp($order->email, array('first_name' => $order->first_name, 'last_name' => $order->last_name), $product->id);
                                }
                            }
                            if ($product_settings != -1 && $product_settings->active_mailtype == "aweber") {
                                subscribeToAweber($order->email, array('first_name' => $order->first_name, 'last_name' => $order->last_name), $product->id);
                            } else {
                                if ($aweber_settings->is_active) {
                                    subscribeToAweber($order->email, array('first_name' => $order->first_name, 'last_name' => $order->last_name), $product->id);
                                }
                            }
                            //store transaction info in session
                            $_SESSION['id_order'] = array('id' => $GLOBALS['transactionId'], 'product_id' => esc_attr($_GET['product_id']), 'shared-on-twitter' => false, 'shared-on-facebook' => false);
                        }
                    } else {
                        if (strcmp($res, "INVALID") == 0) {
                            // log for manual investigation
                            //fwrite($filetest_handler, $res);
                        }
                    }
                }
                fclose($fp);
            }
        }
    }
    //fclose($filetest_handler);
    return;
    //======================================== code ends here ========================================================
    //}
}