<?php
/*
Copyright 2012 Neil Harvey - wordpressLAB
*/

/**
 * Handles requests from paypals IPN service
 */

require_once('../../../../wp-config.php');
require_once('../../../../wp-admin/includes/admin.php');
require_once('../../../../wp-includes/functions.php');
require_once('wp-sa-products.php');

global $wpdb;

ob_start("rt_log");
print_r($_POST);
ob_end_flush();
/*
 * use this function to log the data as and when needed
 */
function rt_log($str) {
    file_put_contents("log2.txt", "\n\n", FILE_APPEND);
    file_put_contents("log2.txt", "---".date("F j, Y, g:i a")."---\n", FILE_APPEND);
    file_put_contents("log2.txt", $str, FILE_APPEND);
}

/**
 * This function validates the the request from paypal ipn
 *
 * @return string
 */
function salesautomator_ipn_validate() {
//check paypal ENVIRONMENT
//salesautomator_test indicates sandbox
    $wp_sa_setting = get_option('wp_sa_setting');
    
    if ($wp_sa_setting['wp_sa_test'] == "checked")
        $paypal_action = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
    else
        $paypal_action = 'https://www.paypal.com/cgi-bin/webscr';

    // read the POST variables from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';

    foreach ($_POST as $key => $value) {
        $value = urlencode(stripslashes($value));
        $req .= "&$key=$value";
    }

    //start CURL
    $ch = curl_init($paypal_action);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
    $result = curl_exec($ch);

    //handle and log curl error if required

    //close curl
    curl_close($ch);
    if (strcmp ($result, "VERIFIED") == 0)
        return TRUE;
    else
        return FALSE;
}

$is_request_verified = salesautomator_ipn_validate();
if($is_request_verified) {
    switch ($_POST['txn_type']) {
        case 'cart':
            ob_start("rt_log");
            echo 'cart'."\n";
            print_r($_POST);

            $item_ids = '';
            $item_count = (int)$_POST['num_cart_items'];
            for($i=1;$i<=$item_count;$i++) {
                $item_id = 'item_number'.$i;
                $item_ids .= $_POST["$item_id"].', ';
            }
            $item_ids = substr($item_ids, 0, -2);


            $total_price = 0;

            switch($_POST['option_selection2_1']) {

                // if coupon code is set for all
                case 'coupon_code_all':
                    $sql_coupon_all = "SELECT * FROM {$wpdb->prefix}wpsa_coupon WHERE product_id = 0 and coupon_code = '" .$_POST['option_name2_1']. "'";
                    $row_coupon_all = $wpdb->get_row($sql_coupon_all);

                    for($i=1;$i<=$item_count;$i++) {

                        if($_POST['option_selection3_1']=='affiliate_ref')
                            $sql_product = "SELECT a.price, b.commission  FROM {$wpdb->prefix}wpsa_product_details a LEFT JOIN {$wpdb->prefix}wpsa_affiliate_product_commission b on a.id = b.product_id where a.id = ".$_POST['item_number'.$i];

                        else
                            $sql_product = "SELECT price FROM {$wpdb->prefix}wpsa_product_details WHERE id = ".$_POST['item_number'.$i];
                            
                        $row_product = $wpdb->get_row($sql_product);

                        if($row_coupon_all->discount_type == 'per') {
                            $discount = ( ( $row_product->price * $row_coupon_all->discount ) / 100);
                            $discount_price = $row_product->price - $discount;
                            //$product_details[ $_POST['item_number'.$i] ] =  round((float)$discount_price, 2) ;
                            $product_details[ $_POST['item_number'.$i] ] =  $discount_price;

                            if($_POST['option_selection3_1']=='affiliate_ref'){
                                $prod_commission = ($discount_price * $row_product->commission)/100;
                                //$prod_commission = round((float)$prod_commission, 2);
                            }
                        }

                        else{
                            $discount_price = ( $row_product->price * $row_coupon_all->discount) / ($_POST['mc_gross'] + $row_coupon_all->discount );
                            $discount = $row_product->price - $discount_price ;
                            //$product_details[ $_POST['item_number'.$i] ] =  round((float)$discount_price, 2);
                            $product_details[ $_POST['item_number'.$i] ] =  $discount_price;
    
                            if(trim($_POST['option_selection3_1'])=='affiliate_ref'){
                                $prod_commission = ($discount_price * $row_product->commission)/100;
                                //$prod_commission = round((float)$prod_commission, 2);
                            }
                        }
                        $total_price += $discount_price;
                        //insert into referal table
                        if ( trim( $_POST['option_selection3_1'] ) == 'affiliate_ref' ) {
                            $sql_referal = "INSERT INTO {$wpdb->prefix}wpsa_affiliate_product_sales ( `affiliate_uid`, `pid`, `pprice`, `discounted_price`, `payment_date`, `date`, `txn_id`, `coupon_code`, `discount`, `commission`, `status`) VALUES
                                    ( ". $_POST['option_name3_1']. ", '" .$_POST['item_number'.$i]. "', '" .$row_product->price. "', '" .$discount_price. "', '" .$_POST['payment_date']. "', now(), '" .$_POST['txn_id']. "', '" .$_POST['option_name2_1']. "', '" .$discount. "','" .$prod_commission. "', 'pending');";
                            $wpdb->query($sql_referal);
                        }
                    }

                    echo $sql_coupon = "INSERT INTO {$wpdb->prefix}wpsa_coupon_log ( `product_details`, `total_product_sold`, `payment_date`, `txn_id`, `gross_sell`, `coupon_code`, `discount`) VALUES
                                ( '" .serialize($product_details). "', " .$item_count. ", '" .$_POST['payment_date']. "', '" .$_POST['txn_id']. "', " .$_POST['mc_gross']. ", '" .$_POST['option_name2_1']. "', '" .$_POST['discount']. "');";
                    $wpdb->query($sql_coupon);
                    break;
                    
                // if coupon code is set for individual products
                case 'coupon_code':
                    for($i=1;$i<=$item_count;$i++) {

                        if($_POST['option_selection3_1']=='affiliate_ref')
                            $sql_product = "SELECT a.price, b.commission  FROM {$wpdb->prefix}wpsa_product_details a LEFT JOIN {$wpdb->prefix}wpsa_affiliate_product_commission b on a.id = b.product_id where a.id = ".$_POST['item_number'.$i];

                        else
                        $sql_product = "SELECT price FROM {$wpdb->prefix}wpsa_product_details WHERE id = ".$_POST['item_number'.$i];
                        $row_product = $wpdb->get_row($sql_product);

                        //if coupon code for product i is set
                        if( $_POST['option_name2_'.$i] != '') {

                            $sql_coupon = "SELECT * FROM {$wpdb->prefix}wpsa_coupon WHERE product_id = ".$_POST['item_number'.$i]. " and coupon_code = '" .$_POST['option_name2_'.$i]. "'";
                            $row_coupon = $wpdb->get_row($sql_coupon);

                            if($row_coupon->discount_type == 'per') {
                                $discount = ( ( $row_product->price * $row_coupon->discount ) / 100);
                                $discount_price = $row_product->price - $discount ;
                                //$product_details[ $_POST['item_number'.$i] ] =  round((float)$discount_price, 2) ;
                                $product_details[ $_POST['item_number'.$i] ] = $discount_price ;

                                if($_POST['option_selection3_1']=='affiliate_ref'){
                                    $prod_commission = ($discount_price * $row_product->commission)/100;
                                    //$prod_commission = round((float)$prod_commission, 2);
                                }
                            }
                            else{
                                $discount = $row_coupon->discount ;
                                $discount_price = $row_product->price -  $row_coupon->discount ;
                                //$product_details[ $_POST['item_number'.$i] ] =  round((float)$discount_price, 2);
                                $product_details[ $_POST['item_number'.$i] ] = $discount_price;

                                if($_POST['option_selection3_1']=='affiliate_ref'){
                                    $prod_commission = ($discount_price * $row_product->commission)/100;
                                    //$prod_commission = round((float)$prod_commission, 2);
                                }
                            }
                            $total_price += $discount_price;
                        }
                        //if coupon code for product i is not set
                        else{
                            $discount = 0;
                            $discount_price = $row_product->price;
                            //$product_details[ $_POST['item_number'.$i] ] =  round($row_product->price, 2);
                            $product_details[ $_POST['item_number'.$i] ] = $row_product->price;
                            
                            if($_POST['option_selection3_1']=='affiliate_ref'){
                                $prod_commission = ($row_product->price * $row_product->commission)/100;
                                //$prod_commission = round((float)$prod_commission, 2);
                            }
                            $total_price += $row_product->price;
                        }
                        //insert into referal table
                        if(trim($_POST['option_selection3_1'])=='affiliate_ref'){
                            $sql_referal = "INSERT INTO {$wpdb->prefix}wpsa_affiliate_product_sales ( `affiliate_uid`, `pid`, `pprice`, `discounted_price`, `payment_date`, `date`, `txn_id`, `discount`, `commission`, `status`) VALUES
                                    ( ". $_POST['option_name3_1']. ", '" .$_POST['item_number'.$i]. "', '" .$row_product->price. "', '" .$discount_price. "', '" .$_POST['payment_date']. "', now(), '" .$_POST['txn_id']. "', '" .$discount. "','" .$prod_commission. "', 'pending');";
                            $wpdb->query($sql_referal);
                        }
                    }
                    echo $sql_coupon = "INSERT INTO {$wpdb->prefix}wpsa_coupon_log ( `product_details`, `total_product_sold`, `payment_date`, `txn_id`, `gross_sell`, `coupon_code`, `discount`) VALUES
                                ( '" .serialize($product_details). "', " .$item_count. ", '" .$_POST['payment_date']. "', '" .$_POST['txn_id']. "', " .$_POST['mc_gross']. ", '" .$_POST['option_name2_1']. "', '" .$_POST['discount']. "');";
                    $wpdb->query($sql_coupon);
                    break;

                // if coupon code is not set
                // but affiliate-referal is set
                //then simple calculate commission on base value of product
                case 'affiliate_ref':
                    $commission = 0;
                    for($i=1;$i<=$item_count;$i++) {
                        //$sql_product = "SELECT a.price, b.commission  FROM {$wpdb->prefix}wpsa_product_details as a, {$wpdb->prefix}wpsa_affiliate_product_commission as b WHERE a.id = b.product_id and a.id = ".$_POST['item_number'.$i];
                        $sql_product = "SELECT a.price, b.commission  FROM {$wpdb->prefix}wpsa_product_details a LEFT JOIN {$wpdb->prefix}wpsa_affiliate_product_commission b on a.id = b.product_id where a.id = ".$_POST['item_number'.$i];
                        $row_product = $wpdb->get_row($sql_product);
                        $total_price += $row_product->price;

                        $product_details[ $_POST['item_number'.$i] ] =  $row_product->price ;

                        $prod_commission = ($row_product->price*$row_product->commission)/100;
                        //$prod_commission = round((float)$prod_commission, 2);
                        $commission += $prod_commission;
                        $commission_details[ $_POST['item_number'.$i] ] =  $prod_commission;

                        //insert into referal table
                        echo $sql_referal = "INSERT INTO {$wpdb->prefix}wpsa_affiliate_product_sales ( `affiliate_uid`, `pid`, `pprice`, `discounted_price`, `payment_date`, `date`, `txn_id`, `discount`, `commission`, `status`) VALUES
                                ( ". $_POST['option_name2_1']. ", '" .$_POST['item_number'.$i]. "', " .$row_product->price. ", " .$row_product->price. ", '" .$_POST['payment_date']. "', now(), '" .$_POST['txn_id']. "', '0', '" .$prod_commission. "', 'pending');";
                        $wpdb->query($sql_referal);
                    }
                    break;

                // if coupon code is not set
                // and affiliate-referal is not set
                //then simple calculate total price and no insertion on referal table
                default :
                    for($i=1;$i<=$item_count;$i++) {
                        $sql_product = "SELECT price FROM {$wpdb->prefix}wpsa_product_details WHERE id = ".$_POST['item_number'.$i];
                        $row_product = $wpdb->get_row($sql_product);
                        $total_price += $row_product->price;
                    }
                    break;
            }
            
            $gross_price = (float)$_POST['mc_gross'];
            $total_price = round($total_price, 2);
            $total_price  = (float)$total_price ;

            if (abs($gross_price-$total_price) < 0.00001) {
                //$domain_name = 'no domain';
                $custom_explode = $_POST['custom'];
                $custom_explode = explode('|', $custom_explode);
                $check_time = $custom_explode[0];
                $referal_url = $custom_explode[1];
                //error_log('---------------------UN----------------------------');
                //error_log(serialize($_POST)); Added customer_fname and customer_lname in table:umesh
                $save_sql = "INSERT INTO ".$wpdb->prefix."wpsa_product_transaction (`product_id` ,`product_name` ,`customer_fname` ,`customer_lname` ,`customer_email` ,`customer_ip` , `paypal_transaction_id` , `status` , `time`, `referal_url`, `check_time`, `price`) VALUES ";
                for($i=1;$i<=$item_count;$i++) {
                    $item_id = 'item_number'.$i;
                    $item_name = 'item_name'.$i;
                    $item_price = 'mc_gross_'.$i;
                    $remote_ip = 'option_selection1_'.$i;
                    $save_sql .= "('".$_POST["$item_id"]."', '".$_POST["$item_name"]."','".$_POST['first_name']."','".$_POST['last_name']."', '".$_POST['payer_email']."', '".$_POST["$remote_ip"]."', '".$_POST['txn_id']."','active',  now(), '".$referal_url."', '".$check_time."',  '".$_POST["$item_price"]."'), ";
                }

                echo $save_sql = substr($save_sql, 0, -2);
                //rt_log($save_sql);
                $wpdb->query( $save_sql);
                rt_sa_send_download_link( $item_ids, $pypal_transaction_detail = $_POST);

            }else {
                //handle failed internal check
                echo 'There something goes wrong.';
            }
            ob_end_flush();
            break;

        case 'subscr_payment':
            $custom_explode = $_POST['custom'];
            $custom_explode = explode('|', $custom_explode);
            $check_time = $custom_explode[0];
            $subscriber_id_pay = $_POST['subscr_id'];
            $txn_id = $_POST['txn_id'];
            $receiver_id = $_POST['receiver_id'];
            $payment_date = $_POST['payment_date'];
            $table_name = $wpdb->prefix . "wpsa_subscription_transaction";

            ob_start("rt_log");
            echo 'subscr_payment'."\n";
            
            /*
             * if referal is set then make entry in affiliate _referal table
             */
            if ( isset($_POST['option_selection1'] ) && $_POST['payment_status'] == 'Completed' ) {
                echo $sql_subsc = "SELECT a.amount3, b.commission  FROM {$wpdb->prefix}wpsa_subscriptions a LEFT JOIN {$wpdb->prefix}wpsa_affiliate_subscription_commission b on a.id = b.subsc_id where a.id = ".$_POST['item_number'];
                $row_subsc = $wpdb->get_row($sql_subsc);
                $subs_commission = ($_POST['payment_gross'] * $row_subsc->commission)/100;
                $subs_commission = round((float)$subs_commission, 2);
            
                //insert into referal table
                $uu = get_user_by('login', $_POST['option_selection1']);
                echo $sql_referal = "INSERT INTO {$wpdb->prefix}wpsa_affiliate_subscription_sales ( `affiliate_uid`, `subsc_id`, `payment_date`, `date`, `txn_id`, `sell`, `commission`, `status`) VALUES
                        ( ". $uu->ID. ",". $_POST['item_number']. ", '" .$_POST['payment_date']. "', now(), '" .$_POST['txn_id']. "', '" .$_POST['payment_gross']. "', '" .$subs_commission. "', 'pending');";
//                        ( ". $_POST['option_selection1']. ",". $_POST['item_number']. ", '" .$_POST['payment_date']. "', now(), '" .$_POST['txn_id']. "', '" .$_POST['payment_gross']. "', '" .$subs_commission. "', 'pending');";
                $wpdb->query($sql_referal);
            }
            //end

            $qry = "INSERT INTO {$table_name} (`txn_id`, `reciever_id`, `payment_date`, `subscr_status`, `subscriber_id`, `check_time`) VALUES('{$txn_id}', '{$receiver_id}', '{$payment_date}', 'active', '{$subscriber_id_pay}', '".$check_time."' )";
            echo $qry."\n";
            $subscr_table_updated = $wpdb->query($qry);
            if(!$subscr_table_updated) {
                $qry = "UPDATE {$table_name} SET `txn_id`='{$txn_id}', `reciever_id`='{$receiver_id}', `payment_date`='{$payment_date}', `subscr_status`='active' WHERE `subscriber_id`='{$subscriber_id_pay}'";
                echo $qry."\n";
                $subscr_table_updated =  $wpdb->query($qry);
            }
            ob_end_flush();
            break;

        case 'subscr_signup':
            $custom_explode = $_POST['custom'];
            $custom_explode = explode('|', $custom_explode);
            $check_time = $custom_explode[0];
            $wpsa_user_id = $custom_explode[1];
            $item_name = $_POST['item_name'];
            $item_number = $_POST['item_number'];
            $payer_email = $_POST['payer_email'];
            $receiver_email = $_POST['receiver_email'];
            $first_name = $_POST['first_name'];
            $last_name = $_POST['last_name'];
            $payer_id = $_POST['payer_id'];
            $subscriber_id_sign = $_POST['subscr_id'];
            $subscription_date = $_POST['subscr_date'];
            $amount = $_POST['amount3'];
            $period = $_POST['period3'];
            $recurring = $_POST['recurring'];
            $table_name = $wpdb->prefix . "wpsa_subscription_transaction";

            ob_start("rt_log");
            echo 'subscr_signup'."\n";


            $qry = "INSERT INTO {$table_name} (`subscriber_id`, `subscr_date`, `amount`, `period`, `recurring`, `item_name`, `item_number`, `payer_email`, `reciever_email`, `first_name`, `last_name`, `payer_id`, `subscr_status`, `check_time`) VALUES('{$subscriber_id_sign}', '{$subscription_date}', '{$amount}', '{$period}', '{$recurring}' ,'{$item_name}', '{$item_number}', '{$payer_email}', '{$receiver_email}', '{$first_name}', '{$last_name}', '{$payer_id}', 'inactive', '".$check_time."' )";
            echo $qry."\n";
            $subscr_table_inserted = $wpdb->query($qry);
            if(!$subscr_table_inserted) {
                $qry = "UPDATE {$table_name} SET `subscr_date`='{$subscription_date}', `amount`='{$amount}', `period`='{$period}', `recurring`='{$recurring}', `item_name`='{$item_name}', `item_number`='{$item_number}', `payer_email`='{$payer_email}', `reciever_email`='{$receiver_email}', `first_name`='{$first_name}', `last_name`='{$last_name}', `payer_id`='{$payer_id}', `subscr_status`='active' WHERE `subscriber_id`='{$subscriber_id_sign}'";
                echo $qry."\n";
                $wpdb->query($qry);
            }

                update_option('wpsa_debug', 'outside');
            if(!empty($wpsa_user_id) && $wpsa_user_id != 0){
                $new_sub_id = $wpdb->prepare($_POST['subscr_id']);
                $user_get_sub_id = get_usermeta($wpsa_user_id, 'subscription_id');
                update_option('wpsa_debug', $user_get_sub_id.' '.$wpsa_user_id);
                if ($user_get_sub_id) {
                    $new_sub_id .= ','.$user_get_sub_id;
                }
                update_usermeta( $wpsa_user_id, 'subscription_id', $new_sub_id);
                $qry = "UPDATE {$table_name} SET `user_ID`='{$wpsa_user_id}' WHERE `subscriber_id`='{$_POST['subscr_id']}'";
                $wpdb->query($qry);
                do_action('wpsa_subscr_signup', $wpsa_user_id, $_POST['subscr_id']);
                echo $qry."\n";
            }
            ob_end_flush();
            break;

        case 'subscr_eot':
        //do something
            break;
        case 'subscr_cancel':
            $subscription_date = $_POST['subscr_date'];
            $subscriber_id_cancel = $_POST['subscr_id'];
            $table_name = $wpdb->prefix . "wpsa_subscription_transaction";
            $qry = "UPDATE {$table_name} SET `subscr_date`='{$subscription_date}', `subscr_status`='inactive' WHERE `subscriber_id`='{$subscriber_id_cancel}'";
            $wpdb->query($qry);
            break;
        default:
            break;
    }
}else {
//handle failed ipn request
}
?>