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

// alternative
//require_once( '../../../wp-config.php' );

$msg_str = '';
$arr_missing_items = array();
$this_domain = get_option( 'home' );
$this_domain_arr = explode( '/', $this_domain );
$this_referr = urldecode( $_POST[ 'referr' ] );
$this_referr = stripslashes( strip_tags( $this_referr ) );
$this_referr_arr = explode( '/', $this_referr );

$aOptions = SofaShoppr::initOptions( false );
$stock_notify_on_low = $aOptions[ 'stock_notify_on_low' ];

$owner = get_userdata( 1 );
$adminmail = $owner->user_email;
$arr_adminmail = explode( '@', $adminmail );
$robot_sender = 'noreply@' . $arr_adminmail[ 1 ];

if( $this_domain_arr[ 0 ] == $this_referr_arr[ 0 ] && $this_domain_arr[ 2 ] == $this_referr_arr[ 2 ] ) {
	
	$serial_data = urldecode( $_POST[ 'serialdata' ] );
	$serial_data = stripslashes( strip_tags( $serial_data ) );
	
	if( $serial_data != '' ) {
		
		// update post meta: stock inventory
		$arr_temp_all_basket_items = array();
		$arr_to_merge_products = array();
		$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 ) {
			
			// check for duplicated items in da basket
			$z = 0;
			while( $z < $aiib_len ) {
				$arr_temp = explode( ':', $arr_items_in_basket[ $z ] );
				array_push( $arr_temp_all_basket_items, $arr_temp[ 0 ] . '^' . $arr_temp[ 3 ] ); // must match both product ID and size
				$z ++;
			}
			
			$matches_count = array_count_values( $arr_temp_all_basket_items ); // check for multiple occurences
			
			foreach( $matches_count as $k => $v ) {
				
				if( $v > 1 ) { // any?
					$arr_occurences = array_keys( $arr_temp_all_basket_items, $k ); // where exactly, at which positions...get the key
					
					if( count( $arr_occurences ) > 0 ) {
						$m = 0;
						$cnt_o = count( $arr_occurences );
						$final_product_quantity = 0;
						while( $m < $cnt_o ) {
							$val_temp = $arr_items_in_basket[ $arr_occurences[ $m ] ];
							$arr_val_temp = explode( ':', $val_temp ); // ID, ID, QUANTITY, SIZE, COLOR, PRICE
							$final_product_quantity = $final_product_quantity + $arr_val_temp[ 2 ];
							$arr_val_temp[ 2 ] = $final_product_quantity;
							$arr_items_in_basket[ $arr_occurences[ $m ] ] = implode( ':', $arr_val_temp );
							if( $m > 0 ) $arr_items_in_basket[ $arr_occurences[ $m - 1 ] ] = implode( ':', $arr_val_temp ); // backward update
							$m ++;
						}
					}
				}
			}
			
			// make array unique in disregard of duplicated items
			$arr_items_in_basket = array_unique( $arr_items_in_basket );

			// proceed
			while( $cnt_aiib < $aiib_len ) {
			  
				$arr_sub_split_item = explode( ':', $arr_items_in_basket[ $cnt_aiib ] );
				$target_post = intval( $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 = $item_stock_array[ intval( $pos_in_arr ) ] - $item_quantity;
				//what if someone has made a purchase in the mean time and stock is out of product?
				if( $stock_calc < 0 ) {
					// can't proceed. gotta notify both user and site admin. User needs to know that his/her order can't be accepted while admin has to be notified about product missing in stock.
					$p_ob = get_post( $target_post );
					$msg_str .= urlencode( stripslashes( strip_tags( $p_ob->post_title ) ) . '~' . $item_stock_array[ $pos_in_arr ] . '^' );
					array_push( $arr_missing_items, $target_post );
				}
				
				$cnt_aiib ++;
			  
			}
		  
		}
	
	}
	
}

if( $msg_str != '' && $stock_notify_on_low == 'yes' ) {

	$subject_str = get_bloginfo( 'name' ) . ', ' . __( "Stock inventory low!", "sofa_shoppr" );
	$msg_from = get_bloginfo( 'name' ) . ', Admin';
	
	$message = __( "Just to let you know that certain items in your webshop are out of stock or someone tried to order more than currently available. Here's the report:", "sofa_shoppr" );
	$message .= '<br /><br />';
	
	$jjj = 0;
	$ami_len = count( $arr_missing_items );
	while( $jjj < $ami_len ) {
		$po_numeric = intval( $arr_missing_items[ $jjj ] );
		$post_obj = get_post( $po_numeric );
		$message .= $post_obj->post_title . ' | link: ' . get_permalink( $po_numeric ) . '<br />';
		$jjj ++;
	}
	
	$headers = "Content-Type: text/html; charset=utf-8; format=flowed\r\n"
	. "Content-Transfer-Encoding: 8bit\r\n"
	. "MIME-Version: 1.0\r\n"
	. "From: $robot_sender\r\n"
	. "Reply-To: $robot_sender\r\n"
	. "Return-Path: $adminmail\r\n";
	
	$msg  = "From : $msg_from<br />";
	$msg .= "e-Mail : $robot_sender<br />";
	$msg .= "Subject : $subject_str<br /><br />";
	$msg .= "--------------Message--------------<br />$message<br /><br />";
	
	//@mail( $adminmail, $subject_str, $msg, $headers );
	
}
echo $msg_str;
?>