<?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 );
$checkout_mode = $aOptions[ 'checkout_mode' ];
$checkout_vendor = $aOptions[ 'checkout_vendor' ];
$checkout_secret = $aOptions[ 'checkout_secret' ];
$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 library
include_once ( TEMPLATEPATH . '/gateways/TwoCo.php' );

// Create an instance of the 2checkout library
$my2CO = new TwoCo();

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

// Specify your 2checkout login and secret
$my2CO->setSecret( $checkout_secret );
$my2CO->addField( 'sid', $checkout_vendor );

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

// Check validity and write down it
$txn_id = stripslashes( strip_tags( $_GET[ 'order_number' ] ) ); // OK
$payment_amount = stripslashes( strip_tags( $_GET[ 'total' ] ) ); // OK
$payment_date = current_time( mysql ); // OK
$entire_name = stripslashes( strip_tags( $_GET[ 'ship_name' ] ) );
$payer_status = stripslashes( strip_tags( $_GET[ 'fraud_status' ] ) ); // OK
$custom = urldecode( stripslashes( strip_tags( $_GET[ 'custom' ] ) ) ); // OK
$payer_email = stripslashes( strip_tags( $_GET[ 'email' ] ) ); // OK
$contact_phone = stripslashes( strip_tags( $_GET[ 'phone' ] ) ); // OK
$address_street = stripslashes( ( $_GET[ 'ship_street_address' ] ) ); // OK
$address_zip = stripslashes( strip_tags( $_GET[ 'ship_zip' ] ) ); // OK
$address_city = stripslashes( strip_tags( $_GET[ 'ship_city' ] ) ); // OK
$address_country = stripslashes( strip_tags( $_GET[ 'ship_country' ] ) );
$address_country_code = ( isset( $_GET[ 'ship_state' ] ) ) ? ( ', ' . stripslashes( strip_tags( $_GET[ 'ship_state' ] ) ) ) : '';
$entire_country = $address_country . $address_country_code; // OK
$mc_currency = $entrycurrency; // OK

// Check validity and write down it
if ( $my2CO->validateIpn() )
{
    //file_put_contents('2co.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, 2CO 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, purchase details will be sent by 2CheckOut.", "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=2co';
	wp_redirect( $redir_to );
}
else
{
    //file_put_contents('2co.txt', "FAILURE\n\n" . $my2CO->ipnData);
	$subject = __( "Purchase not accepted", "sofa_shoppr" ) . ', ' . get_bloginfo( 'name' );
	$message = __( "2CheckOut 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 );
}