<?php
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
$path="https://rpsonline.com.sg/journals";
include "journal-conf.php";


/*

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-synch';


$tx_token = $_GET['tx'];
$auth_token = "t0IUlHDF-q5rlJblDTeFAT5B2W-u9NGtwovj9xpjufKWsHm4lb-fIc2TO3e";

// print '<pre>' . print_r($tx_token) . '</pre>';
// print '<pre>' . print_r($auth_token) . '</pre>';


$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 ('www.paypal.com', 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.paypal.com', 443, $errno, $errstr, 30);

if (!$fp) {
	// 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

//print '<pre>' . print_r($res, true) . '</pre>';

	$lines = explode("\n", $res);
	$keyarray = array();
	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
		$first_name = $keyarray['first_name'];
		$last_name = $keyarray['last_name'];
		$itemname = $keyarray['item_name'];
		$item_number = $keyarray['item_number'];
		//$amount = $keyarray['payment_gross'];
		$amount = $keyarray['mc_gross'];


		$payment_status = $keyarray['payment_status'];
		$payment_currency = $keyarray['mc_currency'];
		$receiver_email = $keyarray['receiver_email'];
		$payer_email = $keyarray['payer_email'];

		$pending_reason=$keyarray['pending_reason'];

		$address_street=$keyarray['address_street'];
		$address_city=$keyarray['address_city'];
		$address_state=$keyarray['address_state'];
		$address_zip=$keyarray['address_zip'];
		$address_country=$keyarray['address_country'];

*/


		$regtiming=date("ymdHi", time());  // eg: date("d/m/y : H:i:s", time())

		$mode ="PayPal";
		$txid =	$mode.' '.$tx_token;



if (isset($_POST['submit'])) {

$item_name=$_POST['item_name'];
$item_number=$_POST['item_number'];
$amount=$_POST['amount'];


$payment_currency = "USD";
$payer_email = "vimallog@yahoo.com";

$address_street= "Testing 1";
$address_city= "Testing 1";
$address_state= "Testing 1";
$address_zip= "Testing 1";
$address_country= "Testing 1";

$custname = "Testing";

$payment_status = "Completed";








$custname = $first_name.' '.$last_name;
$invcurr = "sing";
$gtotalword= "US Dollar Thirty-Nine and cents ninety only.";

if($payment_status == 'Completed')
{

		$check = "SELECT * FROM journal_dtl WHERE `doi`='".$item_number."'";
		$result = mysql_query($check);
		while($row = mysql_fetch_array($result)) {
		$rp_doi = $row['doi'];
		$rp_issn = $row['issn'];
		$rp_title = $row['p_title'];


		$aut1fn=$row['aut1_firstname'];
		$aut1mn=$row['aut1_midname'];
		$aut1sn=$row['aut1_surname'];
		$caut1n=trim($aut1fn.' '.$aut1mn.' '.$aut1sn);

		$aut2fn=$row['aut2_firstname'];
		$aut2mn=$row['aut2_midname'];
		$aut2sn=$row['aut2_surname'];
		$caut2n=trim($aut2fn.' '.$aut2mn.' '.$aut2sn);

		$aut3fn=$row['aut3_firstname'];
		$aut3mn=$row['aut3_midname'];
		$aut3sn=$row['aut3_surname'];
		$caut3n=trim($aut3fn.' '.$aut3mn.' '.$aut3sn);

		$aut4fn=$row['aut4_firstname'];
		$aut4mn=$row['aut4_midname'];
		$aut4sn=$row['aut4_surname'];
		$caut4n=trim($aut4fn.' '.$aut4mn.' '.$aut4sn);

		$aut5fn=$row['aut5_firstname'];
		$aut5mn=$row['aut5_midname'];
		$aut5sn=$row['aut5_surname'];
		$caut5n=trim($aut5fn.' '.$aut5mn.' '.$aut5sn);


		$aut6fn=$row['aut6_firstname'];
		$aut6mn=$row['aut6_midname'];
		$aut6sn=$row['aut6_surname'];
		$caut6n=trim($aut6fn.' '.$aut6mn.' '.$aut6sn);


		$aautfn=$row['aaut_firstname'];
		$aautmn=$row['aaut_midname'];
		$aautsn=$row['aaut_surname'];
		$caautn=trim($aautfn.' '.$aautmn.' '.$aautsn);

		$totauthors = $caut1n.', '.$caut2n.', '.$caut3n.', '.$caut4n.', '.$caut5n.', '.$caut6n.', '.$caautn;

		$pattern = "/(\w+),  /i";

		$replacement = "${1}, ";

		$finalaut = preg_replace($pattern, $replacement, $totauthors);

		$finalaut = rtrim($finalaut, ', ');

		}

		$remarks = "Paid for paper [doi: $rp_doi]";

		//echo"DOI$rp_doi<br>ISBN Folder: $rp_issn";

		//$split_rp_doi = explode('_', $rp_doi);
		//$rp_doi_name=$split_rp_doi[0];
		//$rp_doi_file=$split_rp_doi[1];

		$ftp_server="ftp.itekcmsonline.com";
		$ftp_user_name="docdown@itekcmsonline.com";
		$ftp_user_pass="doc4down100%";

		$pdf="pdf";

		$file1="$rp_doi.pdf";
		//$file2="$rp_doi_file.pdf";
		//$file2="$rp_doi.pdf";
		$file2=$regtiming.'_'.$rp_doi.'.'.$pdf;

		$source_file = "$file1";
		$destination_file  = "/home/rpsonl5/public_html/download_doc/$file2";


		// set up basic connection
		$conn_id = ftp_connect($ftp_server);

		// login with username and password
		$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

		// check connection
		//echo"<Br>conection id $conn_id, destfile $destination_file, soucefile :$source_file<br>";

		if (ftp_chdir($conn_id, "/protected_doc/$rp_issn")) {
	   // echo "Current directory is now: " . ftp_pwd($conn_id) . "\n";

		} else {
    	//echo "Couldn't change directory\n";
		}

		$dload = ftp_get($conn_id, $destination_file, $source_file, FTP_BINARY);

		// check upload status
		if ($dload) {
	   // echo "Downloaded $source_file to $ftp_server as $destination_file.";
		} else {
	   // echo "Download failed!";
		}

		// close the FTP stream
		ftp_close($conn_id);

		$idate=date('Y').'-'.date('m').'-'.date('d');
		$ddate=date('Y').'-'.date('m').'-'.date('d');
		$payterm = "PayPal";



   		$qry = mysql_query("SELECT MAX(invoiceno) AS invoiceno FROM sales_sing_invno");
   		$row = mysql_fetch_assoc($qry);
   		$invoiceno=$row['invoiceno'] + 1;

		//echo"Invoice Number: $invoiceno";

		$qry1 = mysql_query("SELECT MAX(dcno) AS dcno FROM sales_inv_dtl");
		$row1 = mysql_fetch_assoc($qry1);
		$dcno=$row1['dcno']+1;

		$dh_charge = 4.90;
		$netamount = $amount - $dh_charge;



		$sql="INSERT INTO sales_inv_dtl
		(invoiceno,invdate,orderref,dcno,dcdate,payterm,email,custname,iuniv,iaddr1,iaddr2,icity,istate,izip,icountry,suniv,saddr1,saddr2,scity,sstate,szip,scountry,invcoun,invcurr,convrate,dh_charge,grandtotal,gtotalword,disp_on,disp_from,disp_throu,remarks,custid,sign)
		VALUES
		('$invoiceno','$idate','$txid','$dcno','$ddate','$payterm','$payer_email','$custname','','$address_street',' ','$address_city','$address_state','$address_zip','$address_country',' ','$address_street',' ','$address_city','$address_state','$address_zip','$address_country','$invcoun','$payment_currency',' ','$dh_charge','$amount','$gtotalword','','','','$remarks',' ','Y')";


	if (!mysql_query($sql))
		{
	  	die('Error: ' . mysql_error());
	  	}


	$sql3="INSERT INTO sales_inv_book_dtl (invoiceno,isbn,title,amtinvoice,indamtinvoice,quantity,discount,disamt,netamount,backorder,remarks)
	VALUES	('$invoiceno','$rp_issn','$rp_title','$netamount','','1','0','0','$netamount',' ','$remarks')";
	if (!mysql_query($sql3))
	{
	die('Error: ' . mysql_error());
	}



	$sql4="INSERT INTO sales_sing_invno (invoiceno)
	VALUES	('$invoiceno')";
	if (!mysql_query($sql4))
	{
	die('Error: ' . mysql_error());
	}



	$sql5="INSERT INTO sales_paypal (invoiceno, doi, filename)
	VALUES	('$invoiceno', '$rp_doi', '$file2')";
	if (!mysql_query($sql5))
	{
	die('Error: ' . mysql_error());
	}



	session_register('myusername');
	$_SESSION["rp_issn"]=$rp_issn;
	$_SESSION["rp_doi"]=$rp_doi;
	$_SESSION["payer_email"]=$payer_email;
	$_SESSION["custname"]=$custname;

	//echo"Customer name before redirecting: $rp_issn";
	//echo"Path: $path/thanku.php";
header("Location:$path/thanku.php");


}




} //if loop closes


/*

if($payment_status == 'Pending')
{

$_SESSION["$pending_reason"]=$pending_reason;
header("location:$path/paypal_pending.php");
}


if($payment_status == 'Failed')
{
$_SESSION["$pending_reason"]=$pending_reason;
header("location:$path/paypal_failed.php");
}


if($payment_status == 'Denied')
{
header("location:$path/paypal_denied.php");
}
//		echo ("<p><h3>Thank you for your purchase!</h3></p>");
//		echo ("<b>Payment Details</b><br>\n");
//		echo ("<li>Name: $firstname $lastname</li>\n");
//		echo ("<li>Item: $itemname</li>\n");
//		echo ("<li>Amount: $amount</li>\n");
//		echo ("");

		}
	else if (strcmp ($lines[0], "FAIL") == 0) {
		// log for manual investigation
	}
}

fclose ($fp);

*/

?>