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

$aOptions = SofaShoppr::initOptions( false );
$paypal_mode = $aOptions[ 'paypal_mode' ];
global $wpdb;

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

// Create an instance of the paypal library
$myPaypal = new Paypal();

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

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

// Check validity and write down it
if ($myPaypal->validateIpn())
{
	
	$owner = get_userdata( 1 ); // to admin
	$to = $owner->user_email; // feele free change to: $to = 'recipient@domain.com'; :if required!
	
	// assign posted variables to local variables
	$txn_id = urldecode( stripslashes( $_POST[ 'txn_id' ] ) ); // OK
	$payment_amount = urldecode( stripslashes( $_POST[ 'mc_gross' ] ) ); // OK
	$receiver_email = urldecode( stripslashes( $_POST[ 'receiver_email' ] ) );
	$payment_date = current_time( mysql ); // OK
	$first_name = urldecode( stripslashes( $_POST[ 'first_name' ] ) );
	$last_name = urldecode( stripslashes( $_POST[ 'last_name' ] ) );
	$entire_name = $first_name . ' ' . $last_name; // OK
	$payer_status = urldecode( stripslashes( $_POST[ 'payer_status' ] ) ); // OK
	$custom = urldecode( stripslashes( $_POST[ 'custom' ] ) ); // OK
	$payer_email = urldecode( stripslashes( $_POST[ 'payer_email' ] ) ); // OK
	$contact_phone = urldecode( stripslashes( $_POST[ 'contact_phone' ] ) ); // OK
	$address_street = urldecode( stripslashes( $_POST[ 'address_street' ] ) ); // OK
	$address_zip = urldecode( stripslashes( $_POST[ 'address_zip' ] ) ); // OK
	$address_city = urldecode( stripslashes( $_POST[ 'address_city' ] ) ); // OK
	$address_country = urldecode( stripslashes( $_POST[ 'address_country' ] ) );
	$address_country_code = urldecode( stripslashes( $_POST[ 'address_country_code' ] ) );
	$entire_country = $address_country . ', ' . $address_country_code; // OK
	$mc_currency = urldecode( stripslashes( $_POST[ 'mc_currency' ] ) ); // OK
	
    if ($myPaypal->ipnData['payment_status'] == 'Completed')
    {
        // file_put_contents('paypal.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 ++;
				  
				}
			  
			}
		
		}
		
		foreach( $_COOKIE[ 'sofashoppr' ] as $name => $value ) {
			$itemid = $name;
			setcookie( "sofashoppr[$itemid]", "", time()-36000, '/' );
		}
		
		// send notification
		$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 PayPal.", "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 );
				
    }
    else
    {
        //file_put_contents('paypal.txt', "FAILURE\n\n" . $myPaypal->ipnData);
		$subject = __( "Purchase not accepted", "sofa_shoppr" ) . ', ' . get_bloginfo( 'name' );
		$message = __( "PayPal did not accept your payment due to the fact your PayPal 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 );
    }
}