<?php
$this_file = str_replace( '\\', '/', __FILE__ );
$this_file = explode( 'wp-content', $this_file );
$this_file = $this_file[ 0 ];

// required for making tables easier
require_once( $this_file . 'wp-config.php' );

global $wpdb;
$aOptions = SofaShoppr::initOptions( false );
$authorize_mode = $aOptions[ 'authorize_mode' ];
$authorize_user = $aOptions[ 'authorize_user' ];
$authorize_secret_key = $aOptions[ 'authorize_secret_key' ];
$entrycurrency = $aOptions[ 'entrycurrency' ];

$owner = get_userdata( 1 ); // to admin
$to = $owner->user_email; // feele free change to: $to = 'recipient@domain.com'; :if required!

// Include the paypal library
include_once ( TEMPLATEPATH . '/gateways/Authorize.php' );

// Create an instance of the authorize.net library
$myAuthorize = new Authorize();

// Log the IPN results
$myAuthorize->ipnLog = TRUE;

// Specify your authorize login and secret
$myAuthorize->setUserInfo($authorize_user, $authorize_secret_key);

// Enable test mode if needed
if( $authorize_mode == 'sandbox' ) $myAuthorize->enableTestMode();

// Check validity and write down it
$txn_id = stripslashes( strip_tags( $_POST[ 'x_trans_id' ] ) ); // OK
$payment_amount = stripslashes( strip_tags( $_POST[ 'x_amount' ] ) ); // OK
$payment_date = current_time( mysql ); // OK
$first_name = stripslashes( strip_tags( $_POST[ 'x_first_name' ] ) );
$last_name = stripslashes( strip_tags( $_POST[ 'x_last_name' ] ) );
$entire_name = $first_name . ' ' . $last_name; // OK
$payer_status = stripslashes( strip_tags( $_POST[ 'x_auth_code' ] ) ); // OK
$custom = stripslashes( strip_tags( $_POST[ 'custom_internal_code' ] ) ); // OK
$payer_email = stripslashes( strip_tags( $_POST[ 'x_email' ] ) ); // OK
$contact_phone = stripslashes( strip_tags( $_POST[ 'x_phone' ] ) ); // OK
$address_street = stripslashes( strip_tags( $_POST[ 'x_address' ] ) ); // OK
$address_zip = stripslashes( strip_tags( $_POST[ 'x_zip' ] ) ); // OK
$address_city = stripslashes( strip_tags( $_POST[ 'x_city' ] ) ); // OK
$address_country = stripslashes( strip_tags( $_POST[ 'x_country' ] ) );
$address_country_code = stripslashes( strip_tags( $_POST[ 'x_state' ] ) );
$entire_country = $address_country . ', ' . $address_country_code; // OK
$mc_currency = $entrycurrency; // OK


if ($myAuthorize->validateIpn())
{
    //file_put_contents('authorize.txt', 'SUCCESS');
	// insert to database
	$wpdb->insert( ( $wpdb->prefix . 'purchases_history' ), array( 'trans_date' => $payment_date, 'unique_code' => $txn_id, 'trans_status' => $payer_status, 'trans_basket' => $custom, 'user_name' => $entire_name, 'user_email' => $payer_email, 'user_phone' => $contact_phone, 'user_address' => $address_street, 'user_zip' => $address_zip, 'user_city' => $address_city, 'user_country' => $entire_country, 'currency' => $mc_currency, 'gross' => $payment_amount, 'flag_shipped' => 0 ), array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%d' ) );
	
	// update stock inventory
	if( $custom != '' ) {
		
		$serial_data = $custom;
		
		$arr_all_ids = array();
		$arr_items_in_basket = explode( ',', $serial_data );
		array_pop( $arr_items_in_basket ); // remove last empty element
		$cnt_aiib = 0;
		$aiib_len = count( $arr_items_in_basket );
		if( $aiib_len > 0 ) {
			
			while( $cnt_aiib < $aiib_len ) {
			  
				$arr_sub_split_item = explode( ':', $arr_items_in_basket[ $cnt_aiib ] );
				$target_post = (int)$arr_sub_split_item[ 0 ];
				$custom_fields = get_post_custom( $target_post );
				$item_stock = $custom_fields[ 'stock' ][ 0 ]; // currently in stock
				// perform correspondence test size: a, b, c | stock: 1, 2, 3
				$item_sizes = $custom_fields[ 'size' ][ 0 ]; // size and stock are bound, they must match in length!
				$item_sizes_array = explode( "\n", $item_sizes );
				foreach( $item_sizes_array as $k => $v ) $item_sizes_array[ $k ] = trim( $v );
				$item_stock_array = explode( "\n", $item_stock );
				foreach( $item_stock_array as $k => $v ) $item_stock_array[ $k ] = trim( $v );
				// position in array of sizes
				$serach_size = trim( $arr_sub_split_item[ 3 ] ); // search for size in basket
				$pos_in_arr = array_search( (string)$serach_size, $item_sizes_array ); // get the key for stock value
				$item_quantity = intval( $arr_sub_split_item[ 2 ] ); // quantity placed in buyer order
				$stock_calc = intval( $item_stock_array[ $pos_in_arr ] ) - $item_quantity;
				//now it's safe to remove items from stock, products became reserved for that very buyer.
				$item_stock_array[ intval( $pos_in_arr ) ] = $stock_calc; // put new value in array at the same position - we gotta replace an old one
				$save_cf_string = implode( "\n", $item_stock_array ); // make it safe for WordPress
				update_post_meta( $target_post, 'stock', $save_cf_string );
				
				$cnt_aiib ++;
			  
			}
		  
		}
	
	}

	// send notification? No need to, Authorize.net does it automatically! Uncomment if really necessary.
	/*
	$subject = __( "Purchase made", "sofa_shoppr" ) . ', ' . get_bloginfo( 'name' );
	$message = __( "Just to let you know that your order has been received. On a side note, shopping and payment details will be sent by Authorize.net.", "sofa_shoppr" );
	$message .= '<br /><br />';
	$message .= __( "Thank you very much!", "sofa_shoppr" );
	$message .= '<br />' . get_bloginfo( 'url' );
	$headers = "MIME-Version: 1.0\n" . "From: <$to>\n" . "Content-Type: text/html; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
	wp_mail( $payer_email, $subject, $message, $headers );
	*/
	
	$redir_to = get_option( 'home' ) . '/?dc=an';
	wp_redirect( $redir_to );
	
}
else
{
	$subject = __( "Purchase not accepted", "sofa_shoppr" ) . ', ' . get_bloginfo( 'name' );
	$message = __( "Authorize.net did not accept your payment due to the fact your account is not valid. We are sorry but your order has to be disregarded.", "sofa_shoppr" );
	$message .= '<br /><br />';
	$message .= __( "Thank you very much!", "sofa_shoppr" );
	$message .= '<br />' . get_bloginfo( 'url' );
	$headers = "MIME-Version: 1.0\n" . "From: <$to>\n" . "Content-Type: text/html; charset=\"" . get_option( 'blog_charset' ) . "\"\n";
	// send mail
	wp_mail( $payer_email, $subject, $message, $headers );
	
	$redir_to = get_option( 'home' );
	wp_redirect( $redir_to );
	
}