<?php

	include "library.php";

	$cxn = start_code( true );

	page_header( "Payment", $cxn );

	$tx = val( $_GET, "tx" );
 	$status = val( $_GET, "st" );
 	$amt = val( $_GET, "amt" );
	$custom = val( $_GET, "cm" );

	$payment_status = $status;
	$payment_type = "";

	echo "<br><br>";

	if ($status != "Completed" && $status != "Pending" && $status != "Processed")
	{
		echo black( "Unfortunately your payment was declined.<br><br>" );
	}
	else
	{
		$data = split_csv( $custom );

		$type = $data[0];
		$member_id = $data[1];
		$credits_code = $data[2];
		$magic = $data[3];

		if ($type == "donation")
		{
			echo red( "Thank you for your donation<br><br>" );
		}
		else
		if ($type == "subscription")
		{
			echo red( "Thank you for your subscription<br><br>" );
		}
		else
		{

//			if ($amt != "1.20" && $amt != "8.00" && $amt != "20.00"	 && $amt != "40.00" && $amt != "80.00")
//				crash( "Corrupt payment amount ".$amt.", tx=".$tx.", member id =".$member_id, $cxn );

			if (md5( $member_id."|".$credits_code ) != $magic)
				crash( "Bad magic code in payment check, tx=".$tx.", member id =".$member_id, $cxn );

			$query = "SELECT credits_code, credits_balance FROM profile WHERE id = ".$member_id;

			$result = run_query( $query, $cxn );

			$data2 = get_row( $result );

			if ($data2['credits_code'] != "" && $data2['credits_code'] != $credits_code)
				crash( "Corrupt credits code, tx=".$tx.", member id =".$member_id, $cxn );

			if ($amt == "0.40")
				$num_credits = 1;
			else
			if ($amt == "4.00")
				$num_credits = 10;
			else
			if ($amt == "10.00")
				$num_credits = 25;
			else
			if ($amt == "20.00")
				$num_credits = 50;
			else
			if ($amt == "40.00")
				$num_credits = 100;

			echo red( "Payment succeeded<br><br>" );

			if ($num_credits == 1)
				echo red( "You purchased 1 credit.<br><br>" );
			else
				echo red( "You purchased ".$num_credits." credits.<br><br>" );


				/* if already processed */

			if ($data2['credits_code'] == "")
				$credits_balance = $data2['credits_balance'];
			else
				$credits_balance = $data2['credits_balance'] + $num_credits;

			echo red( "Your new credits balance is ".$credits_balance."<br><br>" );
		}

		echo red( "A receipt for this transaction has been emailed to you.<br><br><br>" );
	}

	echo show_home_link();
?>
