<?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"];
}
if(checkArtistExpired($userid)){
	header("Location:seller_plan_upgrade.php?sellerid=".$userid);
	exit;
}
$pids = $_GET['pid'];

$productListingFee = getSettingsValue('product_listing_fee');

if($pids != '')
{
    //$pids = explode($pids, ',');
    if(!empty($pids))
    {
        //$pids = array_unique($pids);
        $sql = "SELECT product_id, product_name
                  FROM ".$tableprefix."products p
                 WHERE p.product_id IN (". mysql_real_escape_string($pids) .")
            AND p.product_artist_id = " . $userid;

        $resultsP = mysql_query($sql) or die(mysql_error());
        $prdCount = mysql_num_rows($resultsP);
    }
}
//die("her1e");
if(!($productListingFee > 0) || !($prdCount > 0))
{
    header("Location:mycatalog.php");
    exit;
}



$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"];
if($auth_token != ''){


					$flag_to_continue=false;

                                        if($txtPaypalSandbox == "Y"){
                                            $req = 'cmd=_notify-synch';
                                            $tx_token = $_GET['tx'];
                                            $st = $_GET['st'];
                                            if($st == "Completed")
                                                $flag_to_continue= true;
                                            else
                                                $flag_to_continue=false;
					}
					else
					{

					//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: text/html; charset=utf-8\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;
						}

					}
                                        }

}else
{
    $flag_to_continue=true;

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






if($flag_to_continue && ($amount_compare == ($productListingFee * $prdCount)))
{
    $sql = "UPDATE ".$tableprefix."products
               SET payment_status = 'COMPLETED'
             WHERE product_id IN (". mysql_real_escape_string($pids) .")
               AND product_artist_id = " . $userid;
        $resultsP = mysql_query($sql) or die(mysql_error());

        $pids = explode(',', $pids);
        if(!empty($pids))
        {
            foreach($pids as $id)
            {
                    $sql = "INSERT INTO ".$tableprefix."product_listing_fee_payment
                                    SET payment_status = 'COMPLETED',
                                        product_id = '". mysql_real_escape_string($id) ."',
                                        total_amount = '". mysql_real_escape_string($productListingFee) ."',
                                        amount_paid= '". mysql_real_escape_string($productListingFee) ."',
                                        payment_method = 'PAYPAL'";
                    $resultsP = mysql_query($sql) or die(mysql_error());
            }
        }


        header("Location:myproducts.php?message=".MSG_PAYMNT_COMP_SUC);
}else{

						header("Location:failure_pay_listing_fee.php?pid=".$pids);
						/*
					   echo "<script>alert(\"Invalid request.Please try again later\");</script>";
					   echo "<script>location.href='index.php';</script>";*/
					   exit;


					}