<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.com>        		              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com � 2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<?php
include "includes/config.php";
include "includes/session.php";
include "includes/functions.php";
include_once "classes/cls_user.php";
include_once "classes/cls_utils.php";
include_once "classes/cls_store.php";
if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE); 
} 
if(isset( $_SESSION["sess_userid"]) and $_SESSION["sess_userid"]!= ""){
	$userid = $_SESSION["sess_userid"];
}else{
	header("Location:login.php");
	exit;
}

$paymentMethod="PP";

$chkPaypal              =   getSettingsValue('enablepaypal');
$txtPaypalEmail         =   getSettingsValue('paypalemail');
$txtPaypalSandbox       =   getSettingsValue('enablepaypalsandbox');
$auth_token             =   getSettingsValue("paypalidentitytoken");

if($txtPaypalSandbox == "Y"){
    //$paypalurl ="http://192.168.0.11/sudheesh/paypal.php";
	$paypalurl = "www.sandbox.paypal.com";
}else{
    //$paypalurl ="http://192.168.0.11/sudheesh/paypal.php";
	$paypalurl = "www.paypal.com";
}

$referrer =  $_SERVER["HTTP_REFERER"];
$flag_to_continue=false;

                                    if($auth_token!='' && $_GET['tx']!='')  {

					//Data check for PDT and proceeded further
					// read the post from PayPal system and add 'cmd'
					$req = 'cmd=_notify-synch';

					$tx_token = $_GET['tx'];

					//$auth_token = "Yl95T6hgNiiI3TsU4VYxHabtIiy-AZzCP5ks92AzLz3We2Jknt5lhx-wQtK";
					//$auth_token="DQ8jgAhGTxqV-7sdW1iCXsKw_fg_qWt2cW2XlLCA6HenqkLxmEQGbEX4jBC";
					$req .= "&tx=$tx_token&at=$auth_token";

					// 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 ($paypalurl, 80, $errno, $errstr, 30);

					// If possible, securely post back to paypal using HTTPS
					// Your PHP server will need to be SSL enabled
					 //$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

					if (!$fp) 
					{
					    //echo "socket error";
						// HTTP ERROR
					} else {
						fputs ($fp, $header . $req);
						// read the body data
						$res = '';
						$headerdone = false;
						while (!feof($fp)) {
							$line = fgets ($fp, 1024);

							if (strcmp($line, "\r\n") == 0) {
								// read the header
								$headerdone = true;
							}
							else if ($headerdone)
							{
								// header has been read. now read the contents
								$res .= $line;
							}
						}
                                                   
							// parse the data
						$lines = explode("\n", $res);
						$keyarray = array();
						//echo($lines[0] . " here");
                                                // echopre($lines);
                                          if(!empty($lines[0]))  {      
						if (strcmp ($lines[0], "SUCCESS") == 0) {
							for ($i=1; $i<count($lines);$i++){
								list($key,$val) = explode("=", $lines[$i]);
								$keyarray[urldecode($key)] = urldecode($val);
							}
						// 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
							$flag_to_continue=true;
						}
						else if (strcmp ($lines[0], "FAIL") == 0) {
                                                    if($txtPaypalSandbox == "Y") { 
                                                            $flag_to_continue   =true;
                                                    }else{
                                                            $flag_to_continue   =false;
                                                        }
						}
					}else{
                                             if($txtPaypalSandbox == "Y") { 
                                                            $flag_to_continue   =true;
                                                    }else{
                                                            $flag_to_continue   =false;
                                                        }
                                            
                                            }
                                        
                                        }

					if($flag_to_continue == true){
					  //echo "successs";
					  ;
					}else{
						
						//header("Location:failure_reg_payment.php");
                                                //exit;
					}
                             }
                             else
                                 {

                                        if($_SESSION['SESS_pay_amount'] != "" && $_GET['amt']!='')
                                     {
                                         if($_SESSION['SESS_pay_amount'] == trim($_GET['amt']))
                                         {
                                                 $flag_to_continue =true;
                                         }
                                     }else {
                                             $flag_to_continue =true;
                                     }
                             }

                   
   if($flag_to_continue)
   {
                if($_SESSION['SELLER_PLAN_OBJ']->sellerPlanID!='') {
                 $planObj                =   Utils::getsellerPlansByPlanId($_SESSION['SELLER_PLAN_OBJ']->sellerPlanID);

                 if($planObj->status==SUCCESS)
                 {
                     $planObjVal =   $planObj->data;

                      $planAmount       = generalMethods::numberFormat($planObjVal->plan_SubscriptionCharge);
                      $planName         = Utils::html_entity($planObjVal->plan_Title);
                      $planPeriod       = $planObjVal->plan_Period; 
                 }

                 $totaltopay     =   $planAmount;

                 if($totaltopay<=0)
                 {
                         $redirecturl    =   SITE_URL."/choosesellerplan.php";
                         generalMethods::redirect($redirecturl);
                 }
         }
        //Create Seller Account with user details
                $objVo        = $_SESSION['SELLER_PLAN_OBJ'];
                $accObj       =   Store::createsellerAccount($objVo);
                if($accObj->status==SUCCESS)
                        {
                             $sellerid              = $accObj->data;
                            //Update Seller Account Activation in User side
                             $userObjVo             =   new stdclass();
                             $userObjVo->userid     =   $userid;
                             $userObjVo->sellerid   =  $sellerid;
                             $userObj               =   User::updateSellerAccountActivation($userObjVo);
                             //Get Seller Approval Status And Re-direction
                             $sellerStatusObj       =   Store::get_seller_account_info($sellerid);
                             if($sellerStatusObj->status==SUCCESS)
                                        {
                                            $sellerobjDataVal   =  $sellerStatusObj->data;
                                            // Save Seller Plan Details 
                                            if($planPeriod=="M")
                                            $noOfDays=30;
                                            if($planPeriod=="Y")
                                            $noOfDays=365;
                                            $fromDate= date("Y-m-d");
                                            $endDate= date("Y-m-d",strtotime("+".$noOfDays." day"));
                                            
                                            $objPlanVo                      = new stdClass();
                
                                            $objPlanVo->artist_id                   =   $sellerid;
                                            $objPlanVo->artist_memStartDate         =   $fromDate;
                                            $objPlanVo->artist_memEndDate           =   $endDate;
                                            $objPlanVo->plan_Id                     =   $_SESSION['SELLER_PLAN_OBJ']->sellerPlanID;
                                            $objPlanVo->plan_SubscriptionCharge     =   $totaltopay;

                                            $objVo->seller_id         =     $sellerid;
                                            
                                            $saveSellerPlanInfo =  Store::savesellerPlanDetails($objPlanVo);

                                             //Unset User Session Data
                                             $_SESSION['SELLER_PLAN_OBJ'] = new stdClass();
                                             unset($_SESSION['SELLER_PLAN_OBJ']);
                                            
                                            // Send Mail Alert to Admin And seller
                                           $malFlag             = Store::sendSellerAccountActivationMail($objVo);
                                          
                                            // End 
                                          // End Plan details 
                                            $approvalStatus    = $sellerobjDataVal->vapproved;
                                                //header("Location:activateselelraccount")
                                                      if($approvalStatus=='NN')
                                                          {
                                                                $activation_msg = MSG_SELLER_ACCOUNT_ACTIVATION;
                                                          }else{
                                                                $activation_msg = MSG_SELLER_ACCOUNT_ACTIVATED;
                                                          }

                                                           $_SESSION['SELLER_ACCOUNT_ACTIVATED_MSG'] = $activation_msg;

                                                           $active_template = displayTemplate();
                                                                include_once "includes/htmltop.php";
                                                                $var_alert= '<link href="'.SITE_URL.'/style/jquery-confirm.css" rel="stylesheet" type="text/css">';
                                                                $var_alert.='<script src="'.SITE_URL.'/js/jquery-confirm.js"></script><script type="text/javascript">$.alert({
                                                        title: "",
                                                        content: "'.$activation_msg.'",
                                                        confirmButton: "okay",
                                                        confirmButtonClass: "btn-info",
                                                        animation: "bottom",
                                                        icon: "fa fa-check",
                                                        backgroundDismiss: true
                                                    }); window.location.href = "myaccount.php"';
                                                       //  $var_alert.='window.location.href = "myaccount.php" ';
                                                        $var_alert.='</script>';
                                                        echo $var_alert;
                                                        exit;
                                       
                                        }
                                
                         }
   }
?>