<?php

	include "library.php";

	$cxn = start_code( true );
	
	$cxn_common = db_common_login();


	page_header( "Payment", $cxn, $cxn_common );

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

	$payment_status = $status;
	$payment_type = "";
	
	$sent = date("Y-m-d H:i:s");
	
	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 != "100.00" && $amt != "200.00" && $amt != "400.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 == "100.00")
				$num_credits = 50;
			else
			if ($amt == "200.00")
				$num_credits = 100;
			else
			if ($amt == "400.00")
				$num_credits = 200;

			$num_credits = 20;

			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;


			$query = "UPDATE profile SET credits_balance = ".$credits_balance." WHERE id = ".$member_id;

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

			$query = "INSERT INTO credits (member_id, event, number, event_datetime) VALUES ".$member_id.", 'purchase',".$num_credits.", '".$sent."'";

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

			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();
?>