<?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";
if(isset( $_SESSION["sess_artistid"]) and $_SESSION["sess_artistid"]!= ""){
	$userid = $_SESSION["sess_artistid"];
}



$sql = "SELECT * FROM ".$tableprefix."settings ";
$res = mysql_query($sql);
$row = mysql_fetch_array($res);
$txtPaypalEmail = $row["paypalemail"];
$txtPaypalSandbox = $row["enablepaypalsandbox"];

$gift_coupon_flag = 0;
$paypal_check = 0;

if($txtPaypalSandbox == "Y"){

	$paypalurl = "www.sandbox.paypal.com";

}else{

	$paypalurl = "www.paypal.com";

}

/** check paypal****************/
                    $sql = "SELECT * FROM ".$tableprefix."settings ";
					$res = mysql_query($sql);
					$row = mysql_fetch_array($res);
					$auth_token = $row["paypalidentitytoken"];

					$flag_to_continue=false;

                                        if($auth_token!='') { 

					//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");
						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) {
							// log for manual investigation
							//		echo("Fail in result");
							$flag_to_continue=false;
						}

					}
                                       if($txtPaypalSandbox=='Y')
                                       {
                                            $flag_to_continue=true;
                                        }

					if($flag_to_continue == true){
					  //echo "successs";
					  ;
					}else{
						
						header("Location:failure.php");
						/*
					   echo "<script>alert(\"Invalid request.Please try again later\");</script>";
					   echo "<script>location.href='index.php';</script>";*/
					   exit;


					}

                                        }
                                        else
                                            {

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

                                                        }
                                                }
                                        }

/*******************************/

//$currency_attributes = displayCurrencyType();

//$totaltopay = number_format(($currency_attributes[1] * getCartTotal($userid)),2,".","");

//$amount_compare = number_format(($currency_attributes[1] * $_GET['amt']),2,".","");

/*---------checking if there is any difference in amounts------*/

$amount_compare=trim($_GET['amt']);


if(isset($_SESSION['SESS_pay_amount']) && $_SESSION['SESS_pay_amount'] != "")
{
	if($_SESSION['SESS_pay_amount'] == trim($_GET['amt']))
	{
		$paypal_check = 0;
		
	}
}


if($paypal_check==0)
{
	if(function_exists('session_register')){
            session_unregister($_SESSION['SESS_pay_amount']);
        }
        else{
            
            unset($_SESSION['SESS_pay_amount']);
        }
}


if(isset($_SESSION['SESS_pay_amount']) && $_SESSION['SESS_pay_amount'] != "")
{
	if($_SESSION['SESS_pay_amount'] != $amount_compare)
	{
		$paypal_check = 1;
	}
}


	$select_Plan = "SELECT plan_Period
								   FROM ".$tableprefix."sellerPlans
								   WHERE plan_Id = ".trim($_SESSION['membership']['plan_Id']);
	$result_Plan = mysql_query($select_Plan) or die(mysql_error());
	$result_Plan = mysql_fetch_assoc($result_Plan);	
	if($result_Plan['plan_Period']=="M")
	$noOfDays=30;
	if($result_Plan['plan_Period']=="Y")
	$noOfDays=365;
	

$_SESSION['SES_MEMPLAN']=$_SESSION['membership']['plan_Id'];

if($paypal_check==0)
{ // check if paypal is success

		 $sql = "UPDATE " .$tableprefix. "artists SET sellerPlanID =".$_SESSION['membership']['plan_Id'].",plan_expired='N'  WHERE artist_id =".$_SESSION['sess_artistid'];
		mysql_query($sql) or die(mysql_error());
		$orderid = mysql_insert_id();
		
		$fromDate= date("Y-m-d");
		$endDate= date("Y-m-d",strtotime("+".$noOfDays." day"));


		$sql = "INSERT INTO " .$tableprefix. "artists_membershipDetails (artist_id, artist_memStartDate, artist_memEndDate,plan_Id,plan_SubscriptionCharge,transaction_id) VALUES
				(".$_SESSION['sess_artistid'].",'".$fromDate."','".$endDate."',".$_SESSION['membership']['plan_Id'].",".$_SESSION['membership']['plan_SubscriptionCharge'].",'".$tx_token."')";
		mysql_query($sql) or die(mysql_error());
		$orderid = mysql_insert_id();
		
			unset($_SESSION['membership']);
			unset($_SESSION['SESS_pay_amount']);
			unset($_SESSION['SESS_insertQry']);
			
			$_SESSION['PAY_MESSAGE']=MSG_PROC_SUC;
			
			header("location:artistmain.php");
			
			exit;
		
		
}		
else
{
		header("location:failure.php");
		exit;
}




?>															