<?php

	include "library.php";

		// this is the latest payment code, 19/07/17
		
		// sample URL request to this form: amt=2.60&cc=USD&cm=133&item_name=Academic%20Dating%20donation&st=Completed&tx=19029293UE0786729
		
		
	$cxn = start_code( true );



	$payment_status = val( $_GET, "st" );

	$data = val( $_GET, "cm" );
	
	$amt = val( $_GET, "amt" );

	$currency = val( $_GET, "cc" );
		
	$transaction_id = val( $_GET, "tx" );
	
	$date_created = date("Y-m-d H:i:s");

	$today_date = date_create( date("Y-m-d") );
	
	$today_plus_367_days = clone $today_date;
		
	date_add( $today_plus_367_days, date_interval_create_from_date_string( '367 days' ));
    $today_plus_367_days_str = $today_plus_367_days->format( "Y-m-d" );		


    $second_section = false;
    
    $account_id = "";
    
    for ($i=0; $i < strlen( $data ); $i++)
    {
        if (substr( $data, $i, 1 ) == ",")
            $second_section = true;
        else
        if (! $second_section)
        {
            $account_id = $account_id.substr( $data, $i, 1 );
        }
    }

	page_header( "Purchase Credits", $cxn );


	if ($account_id != "" && ($payment_status == "Completed" || $payment_status == "Processed"))
	{
    	echo "<br><br>Thank you for purchasing credits.<br><br>";

    	echo "A receipt for your payment will be emailed to you.<br><br>";
    	
    	echo "Your transaction ID is ".$transaction_id."<br><br><br>";
	
    	
    	$number_credits = 0;
    	
    	if ($amt == 5)
    	    $number_credits = 1;
    	else
    	if ($amt == 25)
    	    $number_credits = 5;
    	else
    	if ($amt == 50)
    	    $number_credits = 10;
    	else
    	    echo red( "Your credits purchase failed. Please contact site administration.<br><br>" );
    	    

		$query = "SELECT * FROM account WHERE id = ".$account_id;
		
		$result = run_query( $query, $cxn );
	
		$data = get_row( $result );

        $current_balance = val( $data, "credits_balance" );
        
        $current_balance = $current_balance + $number_credits;
        
		$query = "UPDATE account SET credits_balance = ".$current_balance." WHERE id = ".$account_id;

		$result = run_query( $query, $cxn );
		
    	send_email( "Academic Dating", "noreply@academicdating.net", "mark.mcilroy@outlook.com", "Academic Dating", "noreply@academicdating.net", "ABFS Credits purchase", "", "", $cxn, "live" );
	}
	else
	{
    	echo "<br>Your payment could not be processed. Please contact site administration.<br><br>";
	}


	$query = "INSERT INTO payment_notification_log (account_id, payment_status, type, currency, amount, transaction_id, date_created) VALUES (".$account_id.", '".$payment_status."', 'credits purchase', '".$currency."', ".$amt.", '".$transaction_id."', '".$date_created."')";		
	$result = run_query( $query, $cxn );


	echo show_home_link();

?>