HEX
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.4.30
System: Linux iZj6c1151k3ad370bosnmsZ 3.10.0-1160.76.1.el7.x86_64 #1 SMP Wed Aug 10 16:21:17 UTC 2022 x86_64
User: root (0)
PHP: 7.4.30
Disabled: NONE
Upload Files
File: /var/www/html/breadsecret.com_bak20260325/api/V2/api_2_0_0.php
<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH, DELETE');
header('Access-Control-Allow-Headers: X-Requested-With,content-type');
header('Access-Control-Allow-Credentials: true');

require_once('../../wp-load.php');
date_default_timezone_set("Asia/Hong_Kong");
global $wpdb, $current_site, $sitepress;

//test//
//define("API_KEY", "ck_6a95fca025df3abbf358c24732bae451c24313c3");
//define("API_SECRET", "cs_86b729b0215bcb2b8f4e5536b39002068d6ea75d");

//live//
define("API_KEY", "ck_1515985f54f992e733df2ae9956786762d8c9a43");
define("API_SECRET", "cs_2c6c34f0fbc462f231093f6db34cc0f4b9824bfd");


$post_param = file_get_contents('php://input');
$param = array();
parse_str($post_param, $param);

$arr_result = array();
$key = isset($param['key'])?$param['key']:$_GET['key'];
$secret = isset($param['secret'])?$param['secret']:$_GET['secret'];
$section = isset($param['section'])?$param['section']:$_GET['section'];


// function to post data to destination and get returning result
function httpPost($url, $data)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;
}

function getCustomerIpAddr() {
      
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

function adjust_stock($order_id){
      if ( ! $order_id )
        return;

	global $wpdb;
    // Getting an instance of the order object
    $order = wc_get_order( $order_id );	
	$delivery_date = $order->get_meta('delivery_date', true);	

	if(get_post_meta( $order_id, 'stock_out', true ) ) 
        return; // Exit if already processed

	//if($order->has_status('processing') || $order->has_status('completed')){
	if($order->has_status('pending') || $order->has_status('processing') || $order->has_status('completed')){

		foreach ( $order->get_items() as $item_id => $item ) {			
			$prod = $item->get_product();
			$sku = $prod->get_sku();
			$variation_id = $item->get_variation_id();									
			$product = wc_get_product(wc_get_product_id_by_sku($sku));

			$stock_sku = get_master_sku($sku);
			$unit_qty = 1;
			if(has_master_sku($sku)){
				$description = $product->get_name(); 
				$unit_qty = get_master_sku_unit_qty($sku);					
			}else{
				 if($variation_id!=0){
					$description = get_name_from_variation_id($product->get_name(),$variation_id);				
					$unit_qty = get_variation_unit_qty($variation_id);
				 }else{					
					$description = $product->get_name(); // make a unique key				
					$unit_qty = 1;
				 }
			}
			
			$quantity = $item->get_quantity()*$unit_qty;
	
			 if(isset($delivery_date)){
				 $qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
				 $qty_to = $qty_from - $quantity;
				 $sql_update = "UPDATE sku_stock SET `".$stock_sku."` = '".$qty_to."' WHERE stock_date = '".$delivery_date."' LIMIT 1";
				 if($wpdb->query($sql_update)){
					write_log($delivery_date, "New Order", "Back End (Mobile)", $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update); 
				 }				 
			 }	
		}
		
		if(isset($delivery_date)){
			//wc_create_order_note($order_id, "Delivery Date: ".sanitize_text_field($delivery_date), false, true);
			update_post_meta($order_id, 'stock_out','1');
		}			
	}	   
}

// wocommerce create order function 2021-06-07 by Samiel //
function create_wc_order( $data ){
	global $wpdb;
    $gateways = WC()->payment_gateways->get_available_payment_gateways();
    $order = new WC_Order(); //create order object 
	
    // Set Billing and Shipping adresses
    /*
	foreach( array('billing_', 'shipping_') as $type ) {
        foreach ( $data['address'] as $key => $value ) {
            if( $type === 'shipping_' && in_array( $key, array( 'email', 'phone' ) ) ) {
				$order->update_meta_data( '_shipping_'.$key, $value ); // add custom shipping field (email & phone)
			} else {
				$type_key = $type.$key;	
				if ( is_callable( array( $order, "set_{$type_key}" ) ) ) {
					$order->{"set_{$type_key}"}( $value );
				}
			}
        }
    }
	*/

	// Set Billing and Shippinh addresses

	//billing
	$order->set_billing_first_name($data['billing']['first_name']);
	$order->set_billing_last_name($data['billing']['last_name']);
	$order->set_billing_company($data['billing']['company']);
	$order->set_billing_address_1($data['billing']['address_1']);
	$order->set_billing_address_2($data['billing']['address_2']);
	$order->set_billing_city($data['billing']['city']);
	$order->set_billing_state($data['billing']['state']);
	$order->set_billing_postcode($data['billing']['postcode']);
	$order->set_billing_country($data['billing']['country']);
	$order->set_billing_phone($data['billing']['phone']);
	$order->set_billing_email($data['billing']['email']);

	//shipping
	$order->set_shipping_first_name($data['shipping']['first_name']);
	$order->set_shipping_last_name($data['shipping']['last_name']);
	$order->set_shipping_company($data['shipping']['company']);
	$order->set_shipping_address_1($data['shipping']['address_1']);
	$order->set_shipping_address_2($data['shipping']['address_2']);
	$order->set_shipping_city($data['shipping']['city']);
	$order->set_shipping_state($data['shipping']['state']);
	$order->set_shipping_postcode($data['shipping']['postcode']);
	$order->set_shipping_country($data['shipping']['country']);
	/* below extra fields must be insert by post meta */
	$order->update_meta_data( '_shipping_phone', $data['shipping']['phone'] ); 
	$order->update_meta_data( '_shipping_email', $data['shipping']['email'] ); 
	

	// Set other details
    $order->set_created_via('bsb app');
    $order->set_customer_id($data['user_id']);
    $order->set_currency(get_woocommerce_currency());
    $order->set_prices_include_tax('yes' === get_option('woocommerce_prices_include_tax'));
    $order->set_customer_note(isset($data['order_comments'])?$data['order_comments']:'');
    //$order->set_payment_method( isset( $gateways[ $data['payment_method'] ] ) ? $gateways[ $data['payment_method'] ] : $data['payment_method'] );

	/* 
	if($data['user_id']!=0) {	
		$customerInfo = new WC_Customer($data['user_id']);
		if($customerInfo->get_billing_first_name()!="" && $customerInfo->get_billing_address_1()!=""){			
			$order->set_billing_first_name($customerInfo->get_billing_first_name());
			$order->set_billing_last_name($customerInfo->get_billing_last_name() );
			$order->set_billing_company($customerInfo->get_billing_company() );
			$order->set_billing_email($customerInfo->get_billing_email());
			$order->set_billing_phone($customerInfo->get_billing_phone());
			$order->set_billing_address_1($customerInfo->get_billing_address_1() );
			$order->set_billing_address_2($customerInfo->get_billing_address_2() );
			$order->set_billing_city($customerInfo->get_billing_city() );
			$order->set_billing_state($customerInfo->get_billing_state() );
			$order->set_billing_postcode($customerInfo->get_billing_postcode() );
			$order->set_billing_country($customerInfo->get_billing_country() );				
		}
	}
	*/
	
	// Set custom details 	
	$order->update_meta_data('delivery_date', $data['delivery_date']);
	$order->update_meta_data('_stripe_intent_id', $data['payment_intent']);	
	$order->update_meta_data('_customer_ip_address', $data['customer_ip']);	
	$order->update_meta_data('payment_terms', $data['payment_terms']);	
		
	// Setting for calculating tax
    $calculate_taxes_for = array(
        'country'  => $data['shipping']['country'],
        'state'    => $data['shipping']['state'],
        'postcode' => $data['shipping']['postcode'],
        'city'     => $data['shipping']['city']
    );

    // Set Line items (product)
    foreach( $data['line_items'] as $line_item ) {
        $args = $line_item['args'];
        $product = wc_get_product( isset($args['variation_id']) && $args['variation_id'] > 0 ? $args['variation_id'] : $args['product_id'] );		
        $item_id = $order->add_product( $product, $line_item['quantity'], $line_item['args'] );		
        $item = $order->get_item( $item_id, false );
        $item->calculate_taxes($calculate_taxes_for);
        $item->save();	
		
		if(isset($args['variation_id']) && $args['variation_id'] > 0){						
			$variation = wc_get_product($args['variation_id']);
			foreach($variation->get_variation_attributes() as $attribute_name => $attribute_value){
				$wpdb->insert('wp_woocommerce_order_itemmeta', array(
					'order_item_id' => $item_id,
					'meta_key' => str_replace("attribute_","",$attribute_name),
					'meta_value' => $attribute_value
				));
			}
		}		
    }
	
	// Set Line items (shipping)	
	$shipping_lines = new WC_Order_Item_Shipping();	
	$shipping_lines->set_method_title($data['shipping_lines']['method_title']);
	$shipping_lines->set_method_id($data['shipping_lines']['method_id']);
	$shipping_lines->set_total($data['shipping_lines']['total']);
	$shipping_lines->calculate_taxes($calculate_tax_for);
	$order->add_item($shipping_lines);
	
    // Coupon items	
    if( isset($data['coupon_items'])){
        foreach( $data['coupon_items'] as $coupon_item ) {
            $order->apply_coupon(sanitize_title($coupon_item['code']));
        }
    }

    // Set calculated totals
    $order->calculate_totals();
        
    if( isset($data['order_status']) ) {
        // Update order status from pending to your defined status and save data        
		//$order->update_status($data['order_status']['status'], $data['order_status']['note']);		
		$order->add_order_note("Delivery Date: ".$data['delivery_date']);
        $order_id = $order->get_id();
		
		if($data['adjust_stock']=="Y"){
			adjust_stock($order_id); 
		}

		update_post_meta($order_id, '_payment_method', $data['payment_method_id']);
		update_post_meta($order_id, '_payment_method_title', $data['payment_method_title']);
		update_post_meta($order_id, 'Payment', $data['payment_method_name']);
		update_post_meta($order_id, 'adjust_stock',$data['adjust_stock']);	
    } else {
        // Save order to database (returns the order ID)
        $order_id = $order->save();
    }
	
	$display_delivery_date = date("d/m/Y", strtotime($data['delivery_date']));
	
	/*
	if($data['delivery_date']!=date("Y-m-d")){
		$title = "NEW ORDER";
	}else{
		$title = "\u{2B50}TODAY";
	}		
	
	$message = "#".$order->get_order_number()." ".$display_delivery_date;
	$topic = "newOrder";	
	initPushNotification($title, $message, $topic, $order_id);	
	*/
	update_post_meta($order_id, 'new_order_notification', '1');
    
    // Returns the order ID
    return $order_id;
}

function get_sequence($stock_sku, $date){
	global $wpdb;
	$result = $wpdb->get_results("SELECT * FROM `stock_init` WHERE sku = '".$stock_sku."' LIMIT 1");
	if(count($result)>0){
		if($date >= $result[0]->start_date && $date <= $result[0]->end_date) {
			return "1";
		} elseif($date >= $result[0]->start_date && $result[0]->end_date == "0000-00-00") {
			return "2";
		} elseif($date > $result[0]->end_date) {
			return "3";
		} elseif($date < $result[0]->start_date) {
			return "0";
		}			
		
	}else{
		return "0";
	}		
}	

function get_product_sorting_info($stock_sku, $date){
	global $wpdb;

	$info = get_custom_calendar_date_info($date);

	$max_date = $info['maxdate'];

	$holiday_list = get_holiday_list();

	$unit_qty = 1;
	if(has_master_sku($sku)){			
		$unit_qty = get_master_sku_unit_qty($sku);					
	}

	$result = $wpdb->get_results("SELECT * FROM `stock_init` WHERE sku = '".$stock_sku."' LIMIT 1");

	if(count($result)>0){		
		
		if($date >= $result[0]->start_date && $date <= $result[0]->end_date) { // in sales period
			$sequence = "1";
		} elseif($date >= $result[0]->start_date && $result[0]->end_date == "0000-00-00") { // in sales period
			$sequence = "2";
		} elseif($date > $result[0]->end_date) { // sales ended
			$sequence = "3";
		} elseif($date < $result[0]->start_date) { // coming soon
			$sequence = "0";
		}					

		if($result[0]->end_date!="0000-00-00" && $result[0]->end_date < $max_date){
			$max_date = $result[0]->end_date;
		}

		for($i=strtotime($date); $i<=strtotime($max_date); $i+=86400){			

		
			if((date("N", $i)!=7) && !in_array(date("Y-m-d", $i), $holiday_list) ) {

				$stock_remain = get_sku_stock_by_date($stock_sku,date('Y-m-d', $i));				

				if(($stock_remain*10)%($unit_qty*10)==0){
					$display_stock_qty = floatval($stock_remain/$unit_qty);
				} else {
					$display_stock_qty = floatval(floor($stock_remain/$unit_qty));
				}				
				
				if($display_stock_qty>0 && $sequence!=3){					
					return array("sequence"=>$sequence, "sales_status"=>true);
				}
			}
		}

		
		return array("sequence"=>$sequence, "sales_status"=>false);

	}else{
		return array("sequence"=>0, "sales_status"=>false);
	}
}	

// check api key
if($key!=API_KEY){
	$array_result['success'] = false;
	$array_result['statusCode'] = 403;
	$array_result['code'] = "invalid_key";
	$array_result['message'] = "Unauthorized API Key";
			$array_result['data'] = array(
				'id'          => null,
				'email'       => null,
				'nicename'    => null,
				'firstName'   => null,
				'lastName'    => null,
				'displayName' => null,
			);			
}elseif($secret!=API_SECRET){ // chcek api secret
	$array_result['success'] = false;
	$array_result['statusCode'] = 403;
	$array_result['code'] = "invalid_secret";
	$array_result['message'] = "Unauthorized API Secret";
	$array_result['data'] = array(
		'id'          => null,
		'email'       => null,
		'nicename'    => null,
		'firstName'   => null,
		'lastName'    => null,
		'displayName' => null,
	);			
}else{
	
	// check login
	if($section=="auth"){
		$user = wp_authenticate( $param['username'], base64_decode($param['password'],true) );
		//$role = "TEST";
		
		foreach($user->roles as $userRole){
			//var_dump($userRole);
			$role = $userRole;
		}
		
		//print_r($user);	
		if ( is_wp_error( $user ) ) {
			$error_code = $user->get_error_code();

			$array_result['success'] = false;
			$array_result['statusCode'] = 403;
			$array_result['code'] = $error_code;
			$array_result['message'] = strip_tags( $user->get_error_message( $error_code ) );
			$array_result['data'] = array(
				'id'          => null,
				'email'       => null,
				'nicename'    => null,
				'firstName'   => null,
				'lastName'    => null,
				'displayName' => null,
			);			
		} elseif(!in_array($role, array("customer","administrator","editor","shop_manager"))){
			$error_code = $user->get_error_code();

			$array_result['success'] = false;
			$array_result['statusCode'] = 403;
			$array_result['code'] = "login_error";
			$array_result['message'] = "This user is not allowed to use this app";
			$array_result['data'] = array(
				'id'          => null,
				'email'       => null,
				'nicename'    => null,
				'firstName'   => null,
				'lastName'    => null,
				'displayName' => null,
			);				
			
		} else {
			/*
			$stripe_customer_id = get_user_meta($user->ID, "wp__stripe_customer_id", true);
			//echo "stripe_id:".$stripe_customer_id;
			if($stripe_customer_id == ""){
				$url = "https://www.breadsecret.com/StripeBackend/createCustomer.php";
				$data = array(
					'email' => $user->user_email,
					'name' => $user->username,
					'phone' => ''
				);
				
				//print_r($data);
				
				$stripe_response = httpPost($url, $data);
				$stripe_data = json_decode($stripe_response, true);
				//print_r($stripe_data);
				
				update_user_meta($user->ID, "wp__stripe_customer_id", $stripe_data['id']);					
			}
			*/

			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "login_success";
			$array_result['message'] = "Login Success!";
						
			$array_result['data'] = array(
				'id'          => $user->ID,
				'email'       => $user->user_email,
				'nicename'    => $user->user_nicename,
				'firstName'   => $user->first_name,
				'lastName'    => $user->last_name,
				'displayName' => $user->display_name,			
			);	
		}
		
	}


    // update device token
	if($section=="update_device_token"){
		$user_id = $_POST['user_id'];		
		$device_token = $_POST['device_token'];
		if(!isset($user_id) || empty($user_id)){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "User ID is missing";
		} elseif(!isset($device_token) || empty($device_token)){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Device Token is missing";
		} else {
			
			update_user_meta($user_id, "device_token", $device_token);
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "User Device Token is updated";
			$array_result['message'] = $device_token;

			
			// for testing only	
			/*
			$title = "TEST";
			$message = "TOKEN UPDATE";
			$token = $device_token;
			$type = "Login";
			$ref_id = $user_id;

			initPushNotificationAppDevice($title, $message, $token, $type, $ref_id);
			$wpdb->insert(
				'bsb_notification_center', 
				array(
					'hash'=>wp_generate_uuid4(),
					'user_id'=>$user_id,			
					'title'=>$title,
					'message'=>$message,
					'device_token'=>$token,
					'type'=>$type,	
					'reference_id'=>intval(0)
				)
			);
			*/
		}
	}


    // update device token
	if($section=="reset_device_token"){

		$user_id = $_POST['user_id'];
		if(!isset($user_id) || empty($user_id)){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "User ID is missing";
		} else {
			update_user_meta($user_id, "device_token", "");
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = "User Device Token is reset";			
		}
		
	}



	// check login
	if($section=="profile_data"){
		$user = new WC_Customer( $_GET['user_id'] );
		
		$array_data = array();
		$array_data['id'] = intval($_GET['user_id']);
		$array_data['email'] = $user->get_email();
		$array_data['first_name'] = $user->get_first_name();
		$array_data['last_name'] = $user->get_last_name();
		$array_data['username'] = $user->get_username();
		$array_data['avatar_url'] = get_avatar_url($_GET['user_id']);	
		$array_data['language'] = empty(get_user_meta($_GET['user_id'], 'default_language', true))?"zh-Hant":get_user_meta($_GET['user_id'], 'default_language', true);
		$array_data['is_staff'] = $user->get_role()=="customer"?false:true;		
		
		$billing = array();
		// Customer billing information details (from account)
		$billing['first_name'] = $user->get_billing_first_name();
		$billing['last_name']  = $user->get_billing_last_name();
		$billing['company']    = $user->get_billing_company();
		$billing['address_1']  = $user->get_billing_address_1();
		$billing['address_2']  = $user->get_billing_address_2();
		$billing['city']       = $user->get_billing_city();
		$billing['state']      = $user->get_billing_state();
		$billing['postcode']   = $user->get_billing_postcode();
		$billing['country']    = $user->get_billing_country();
		$billing['phone']    = $user->get_billing_phone();
		$billing['email']    = $user->get_billing_email();	
		
		$array_data['billing'] = $billing;

		// Customer shipping information details (from account)
		$shipping['first_name'] = $user->get_shipping_first_name();
		$shipping['last_name']  = $user->get_shipping_last_name();
		$shipping['company']    = $user->get_shipping_company();
		$shipping['address_1']  = $user->get_shipping_address_1();
		$shipping['address_2']  = $user->get_shipping_address_2();
		$shipping['city']       = $user->get_shipping_city();
		$shipping['state']      = $user->get_shipping_state();
		$shipping['postcode']   = $user->get_shipping_postcode();
		$shipping['country']    = $user->get_shipping_country();	
		$shipping['phone']    = get_user_meta( $_GET['user_id'], 'shipping_phone', true );
		$shipping['email']    = get_user_meta( $_GET['user_id'], 'shipping_email', true );			
		
		$array_data['shipping'] = $shipping;
		
		// $array_data['stripe_customer_id'] = get_user_meta($_GET['user_id'], 'wp__stripe_customer_id', true)==false?"":get_user_meta($_GET['user_id'], 'wp__stripe_customer_id', true);

		$array_result['data'] = $array_data;

	}		

	if($section=="get_stripe_customer_id") {

		$user_id = $_GET['user_id'];
		$stripe_customer_id = get_user_meta($user_id, "wp__stripe_customer_id", true);
		$customer = new WC_Customer($user_id);

		if(!empty($stripe_customer_id)){
			try {
			
				require_once('../../StripeBackend/stripe-php/init.php');
				
				\Stripe\Stripe::setApiKey('sk_test_51IzXlzJXv3LbLUyO5MAV7N8HXLz0EhRraYDIOI4LDgG70gLQzYxar5ENqf5VH95GQH02du1OpjrXiqzleijJugyA00aN0Tn59J');
				
				$key = \Stripe\Customer::retrieve($stripe_customer_id);
				
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = $stripe_customer_id;	

			} catch (Exception $e) {

				$url = "https://www.breadsecret.com/StripeBackend/createCustomer.php";
				$data = array(
					'email' => $customer->get_email(),
					'name' => $customer->get_username(),
					'phone' => ''
				);
				
				//print_r($data);			
				$stripe_response = httpPost($url, $data);
				$stripe_data = json_decode($stripe_response, true);
				
				update_user_meta($user_id, "wp__stripe_customer_id", $stripe_data['id']);

				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = $stripe_data['id'];				
				
			}
			

		} else {

			$url = "https://www.breadsecret.com/StripeBackend/createCustomer.php";
			$data = array(
				'email' => $customer->get_email(),
				'name' => $customer->get_username(),
				'phone' => ''
			);
			
			//print_r($data);			
			$stripe_response = httpPost($url, $data);
			$stripe_data = json_decode($stripe_response, true);
			
			update_user_meta($user_id, "wp__stripe_customer_id", $stripe_data['id']);

			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = $stripe_data['id'];
		}

	}	
	
	if($section=="order_list") {

		$array_result = array();
		$array_result['data'] = array();
		
		//$delivery_date = isset($_GET['delivery_date']) && $_GET['delivery_date']!=""?$_GET['delivery_date']:date("Y-m-d");

		//$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$delivery_date."' Order by order_master.ID DESC");
		$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_detail.meta_key = '_customer_user' AND order_detail.meta_value = '".$_GET['customer_id']."' Order by order_master.ID DESC");
		
		foreach ($result as $order_obj ){
			$arr_order = array();
			$order = wc_get_order( $order_obj->ID );			
			$arr_order['id'] = $order->get_id();
			$arr_order['number'] = $order->get_order_number();
			$arr_order['date_created'] = date("Y-m-d\TH:i:s", strtotime($order_obj->post_date));
			//$arr_order['delivery_date'] = get_post_meta($order->get_id(), 'delivery_date', true);
			$arr_order['total'] = $order->get_total();
			$arr_order['status'] = $order->get_status();

			foreach ( $order->get_items() as $item_id => $item ) {
				$products = $item->get_product();
				$product_id = $item->get_product_id();


				$zh_post_id = 0;
				$trid = $sitepress->get_element_trid($product_id, 'post_product');
				$translations = $sitepress->get_element_translations($trid, 'product');
				foreach( $translations as $lang=>$translation){
					if($translation->language_code == "zh-hant")
						$zh_post_id = $translation->element_id;
				}	

				$arr_order['product_name'] = html_entity_decode(get_the_title($product_id));			
				$arr_order['product_name_zh'] =get_the_title($zh_post_id);				

				$variations = $item->get_variation_id();	

				if($variations==0){
					$arr_order['variation_name'] = "";
				} else {				
					$arr_variation = explode(":",get_the_excerpt($variations));					
					
					$arr_order['variation_name'] = trim($arr_variation[1]);
				}	

				switch($arr_order['variation_name']){
					case "4 Pieces":
						$arr_order['variation_name_zh'] = "4片";
						break;
					case "Don't cut":
						$arr_order['variation_name_zh'] = "不切";
						break;
					case "8 Pieces":
						$arr_order['variation_name_zh'] = "8片";
						break;
					case "5 Pieces (23mm)":
						$arr_order['variation_name_zh'] = "5片 (23mm)";
						break;
					default:
					$arr_order['variation_name_zh'] = $arr_order['variation_name'];
						break;														
				}				

				$arr_order['image'] = wp_get_attachment_url($products->get_image_id())==false?"":wp_get_attachment_url($products->get_image_id());		

				break;
			}			


			/*
			$arr_billing = array();
			$arr_billing['first_name'] = $order->get_billing_first_name();
			$arr_billing['last_name'] = $order->get_billing_last_name();
			$arr_billing['company'] = $order->get_billing_company();
			$arr_billing['address_1'] = $order->get_billing_address_1();
			$arr_billing['city'] = $order->get_billing_city();
			$arr_billing['state'] = $order->get_billing_state();
			$arr_billing['country'] = $order->get_billing_country();
			$arr_billing['email'] = $order->get_billing_email();
			$arr_billing['phone'] = $order->get_billing_phone();
			$arr_order['billing'] = $arr_billing;
			*/



			
			$arr_order['shipping_method'] = get_shipping_method_from_code($order->get_shipping_method());
			$shipping_type = explode(" ",$order->get_shipping_method());
			$arr_order['shipping_type'] = $shipping_type[0];
			$arr_order['product_id'] = $product_id;
			$arr_order['item_count'] = count($order->get_items());
			array_push($array_result['data'], $arr_order);			
		}
	}
	
	if($section=="order_result_list") {

		$url = "https://www.breadsecret.com/wp-json/wc/v3/orders?consumer_key=".API_KEY."&consumer_secret=".API_SECRET."&orderby=id&order=desc&per_page=30&search=".$_GET['search'];
		
		$content = file_get_contents($url);

		$api_order_data = json_decode($content, true);

		$array_result = array();
		
		foreach($api_order_data as $api_order){
            $arr_order_result = array();
            $arr_order_result['id'] = $api_order['id'];
            $arr_order_result['number'] = $api_order['number'];
            $arr_order_result['date_created'] = $api_order['date_created'];
            $arr_order_result['total'] = $api_order['total'];
            $arr_order_result['status'] = $api_order['status'];
            $arr_order_result['billing'] = $api_order['billing'];
            $arr_order_result['shipping_method'] = get_shipping_method_from_code($api_order['shipping_lines'][0]['method_title']);
            $shipping_type = explode(" ", $arr_order_result['shipping_method']);
            $arr_order_result['shipping_type'] = $shipping_type[0];

            array_push($array_result, $arr_order_result);
        }

	}

	if($section=="check_payable"){
		if(!empty($_GET['order_id'])){
			
			$order = wc_get_order($_GET['order_id']);			
			
			if(!$order){
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Invalid Order ID";
				$array_result['data'] = null;
			} else {
				
				$time_diff = time() - strtotime($order->order_date);
				$status_index = get_order_status_index($_GET['order_id']);

				if($status_index=="-1" && $time_diff < 3600){
					$array_result['success'] = true;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Success";
					$array_result['message'] = "Payable";
					$array_result['data'] = null;	
				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Fail";
					$array_result['message'] = "Non-payable";
					$array_result['data'] = null;	
				}

			} 
			
		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Order ID not found";
			$array_result['data'] = null;
		}

	}


	if($section=="order_detail"){
		if(!empty($_GET['ord_id'])){
			
			$order = wc_get_order($_GET['ord_id']);			
			
			if(!$order){
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Invalid Order ID";
				$array_result['data'] = null;
			} else {

				if($order->get_customer_id()==$_GET['user_id']){

					$countries = new WC_Countries();
					$country_states = $countries->get_states('HK');

					$array_data = array();

					$time_diff = time() - strtotime($order->order_date);
					$status_index = get_order_status_index($_GET['ord_id']);

					$array_data['id'] = intval($_GET['ord_id']);
					$array_data['number'] = $order->get_order_number();
					$array_data['key'] = $order->get_order_key();
					$array_data['status'] = $order->get_status();
					$array_data['currency'] = $order->get_currency();
					//$array_data['date_created'] = $order->get_date_created()->format("m/d/Y");	
					$array_data['date_created'] = date("Y-m-d", strtotime($order->order_date));
					$array_data['time_diff'] = $time_diff;
					$array_data['date_paid'] = is_null($order->get_date_paid())?"":$order->get_date_paid()->format("Y-m-d");						
					$array_data['subtotal'] = strval(number_format($order->get_subtotal(),2,".",","));
					$array_data['discount_total'] = number_format($order->get_discount_total(),2,".",",");
					$array_data['shipping_total'] = number_format($order->get_shipping_total(),2,".",",");
					$array_data['total'] = number_format($order->get_total(),2,".",",");
					$array_data['customer_id'] = $order->get_customer_id();
					$array_data['payment_method_title'] = $order->get_payment_method_title();
					$array_data['payment_terms_title'] = get_post_meta($_GET['ord_id'], 'payment_terms', true)==false?"":get_post_meta($_GET['ord_id'], 'payment_terms', true);
					$array_data['transaction_id'] = $order->get_transaction_id();
					$array_data['delivery_date'] = is_null(get_post_meta($_GET['ord_id'], 'delivery_date', true))?"":date("Y-m-d", strtotime(get_post_meta($_GET['ord_id'], 'delivery_date', true)));
					$array_data['payment'] = get_post_meta($_GET['ord_id'], 'Payment', true);
					$array_data['customer_note'] = $order->get_customer_note();
					$array_data['shipping_method'] = get_shipping_method_from_code($order->get_shipping_method());
					$array_data['status_index'] = $status_index;

					if($status_index=="-1" && $time_diff < 3600){
						$array_data['repayable'] = true;
					} else {
						$array_data['repayable'] = false;
					}

					//billing info.
					$array_billing = array();
					$array_billing['first_name'] = $order->get_billing_first_name();
					$array_billing['last_name'] = $order->get_billing_last_name();
					$array_billing['company'] = $order->get_billing_company();
					$array_billing['address_1'] = $order->get_billing_address_1();	
					$array_billing['address_2'] = $order->get_billing_address_2();			
					$array_billing['city'] = $order->get_billing_city();
					//$array_billing['state'] = get_region_from_code($order->get_billing_state());
					$array_billing['state'] = trim($country_states[$order->get_billing_state()]);			
					$array_billing['country'] = $order->get_billing_country();
					$array_billing['email'] = $order->get_billing_email();
					$array_billing['phone'] = $order->get_billing_phone();
					$array_data['billing'] = $array_billing;

					//shipping info.
					$array_shipping = array();
					$array_shipping['first_name'] = $order->get_shipping_first_name();
					$array_shipping['last_name'] = $order->get_shipping_last_name();
					$array_shipping['company'] = $order->get_shipping_company();
					$array_shipping['address_1'] = $order->get_shipping_address_1();
					$array_shipping['address_2'] = $order->get_shipping_address_2();
					$array_shipping['city'] = $order->get_shipping_city();
					//$array_shipping['state'] = get_region_from_code($order->get_shipping_state());
					$array_shipping['state'] = trim($country_states[$order->get_shipping_state()]);
					$array_shipping['country'] = $order->get_shipping_country();
					$array_shipping['email'] = get_post_meta($_GET['ord_id'], '_shipping_email', true);
					$array_shipping['phone'] = get_post_meta($_GET['ord_id'], '_shipping_phone', true);			
					$array_data['shipping'] = $array_shipping;
					
					//item info.
					$array_line_items = array();
					foreach ( $order->get_items() as $item_id => $item ) {
						
						$product = array();
						$products = $item->get_product();
						$product['id'] = $item->get_product_id();
						$product['type'] = $products->get_type();
						
						$category_name = array();
						$category_id = wp_get_post_terms($product['id'], 'product_cat', array('fields' => 'ids'));
						foreach($category_id as $cat_id){
							$category = get_term_by( 'id', $cat_id, 'product_cat', 'ARRAY_A' );
							array_push($category_name, $category['name']);	
						}
						
						$product['category'] = implode("/",$category_name);								
						$product['variation_id'] = $item->get_variation_id();				
						
						$zh_post_id = 0;
						$trid = $sitepress->get_element_trid($product['id'], 'post_product');
						$translations = $sitepress->get_element_translations($trid, 'product');
						foreach( $translations as $lang=>$translation){
							if($translation->language_code == "zh-hant")
								$zh_post_id = $translation->element_id;
						}				
						

						if($product['variation_id']==0){
							$product['variation_name'] = "";
						} else {				
							$arr_variation = explode(":",get_the_excerpt($product['variation_id']));					
							
							$product['variation_name'] = trim($arr_variation[1]);
						}	
									
						$product['name'] = html_entity_decode(get_the_title($product['id']));				
						$product['name_zh'] = get_the_title($zh_post_id);				
						
						$product['unit'] = get_post_meta($product['id'], '_woo_uom_input', true);
						$product['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true)==false?"":get_post_meta($zh_post_id, '_woo_uom_input', true);					
						
						$product['sku'] = $products->get_sku();
						$product['quantity'] = $item->get_quantity();				
						$product['price'] = number_format($products->get_price(), 2);
						$product['discounted_price'] = number_format($item->get_total()/$item->get_quantity(),2);
						//$product['subtotal'] = $item->get_total();
						$product['image'] = wp_get_attachment_url($products->get_image_id())==false?"":wp_get_attachment_url($products->get_image_id());				
					
						array_push($array_line_items, $product);
					}

					$array_data['line_items'] = $array_line_items;

					$array_result['success'] = true;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Success";
					$array_result['message'] = "";
					$array_result['data'] = $array_data;					
				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Fail";
					$array_result['message'] = "Unauthorized Access";
					$array_result['data'] = null;
				}			

			} 
			
		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Order ID not found";
			$array_result['data'] = null;
		}

	}
	
	if($section=="create_user"){		

		$check_user = username_exists($param['username']);
		
		if ( !$check_user ) {			
			if( email_exists($param['email']) == false) {
				$user_id = wc_create_new_customer($param['email'], $param['username'], $param['password'] );
				if($user_id){
					update_user_meta( $user_id, "billing_first_name", $param['username'] );
					update_user_meta( $user_id, "shipping_first_name", $param['username'] );
					update_user_meta( $user_id, "billing_country", 'HK' );
					update_user_meta( $user_id, "shipping_country", 'HK' );		
					update_user_meta( $user_id, "billing_email", $param['email'] );	
					
					/*
					$url = "https://www.breadsecret.com/StripeBackend/createCustomer.php";
					$data = array(
						'email' => $param['email'],
						'name' => $param['username'],
						'phone' => ''
					);
					
					$stripe_response = httpPost($url, $data);
					$stripe_data = json_decode($stripe_response, true);
					//print_r($stripe_data);
					update_user_meta($user_id, "wp__stripe_customer_id", $stripe_data['id']);	
					*/
					
					$array_result['success'] = true;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "register_success";
					$array_result['message'] = "Register Success";
					$array_result['data'] = array(
						'id'          => $user_id,
						'email'       => $param['email'],
						'username'    => $param['username'],	
					);
								
				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 403;
					$array_result['code'] = "register_fail";
					$array_result['message'] = "Register Fail";
					$array_result['data'] = array(
						'id'          => 0,
						'email'       => "",
						'username'    => "",
					);				
				} 
			} else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 403;
				$array_result['code'] = "register_fail";
				$array_result['message'] = "Email already registered";
				$array_result['data'] = array(
						'id'          => 0,
						'email'       => "",
						'username'    => "",
				);	
			}
			
		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 403;
			$array_result['code'] = "register_fail";
			$array_result['message'] = "User name already registered";
			$array_result['data'] = array(
						'id'          => 0,
						'email'       => "",
						'username'    => "",
			);	
		}
	}

	// update stripe user id
	if($section=="update_stripe_user"){
		update_user_meta($param['user_id'], "wp__stripe_customer_id",  $param['stripe_customer_id']);
		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "update Success";			
	}	
	
	if($section=="lost_password") {	
		
		$user_login = sanitize_text_field($param['login']);
    
		if ( empty( $user_login) ) {
			$array_result['success'] = false;
			$array_result['statusCode'] = 403;
			$array_result['code'] = "Retrieve Password Fail";
			$array_result['message'] = "Please fill in User Name / Email";
		} else if ( strpos( $user_login, '@' ) ) {
			$user_data = get_user_by( 'email', trim( $user_login ) );
		} else {
			$login = trim($user_login);
			$user_data = get_user_by('login', $login);			
		}
	
		//echo "1";
		do_action('lostpassword_post');	
		//echo "2";
		if ( !$user_data ) {
			//echo "3";
			$array_result['success'] = false;
			$array_result['statusCode'] = 403;
			$array_result['code'] = "Retrieve Password Fail";
			$array_result['message'] = "User Name / Email not Found";	
		} else {
			//echo "4";
			// redefining user_login ensures we return the right case in the email
			$user_login = $user_data->user_login;
			$user_email = $user_data->user_email;
		
			do_action('retreive_password', $user_login);  // Misspelled and deprecated
			do_action('retrieve_password', $user_login);
		    				
			$key = wp_generate_password( 20, false );
			do_action( 'retrieve_password_key', $user_login, $key );
		
			if ( empty( $wp_hasher ) ) {
			//	echo "5";
				require_once ABSPATH . 'wp-includes/class-phpass.php';
				$wp_hasher = new PasswordHash( 8, true );
			}
			
			//echo "6";
			$hashed = time() . ':' . $wp_hasher->HashPassword( $key );
			$wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user_login ) );
			
			$message = __('Hi ').$user_login.",\r\n\r\n<br><br>";
			$message .= __('Someone has requested a password reset for the following account:') . "\r\n\r\n<br><br>";
			$message .= network_home_url( '/' ) . "\r\n\r\n<br><br>";
			$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n<br><br>";
			$message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n<br>";
			$message .= __('To reset your password, visit the following address:') . "\r\n\r\n<br><br>";
			$message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login') . "\r\n<br><br>";
			$message .= __('Bread Secret') . "\r\n\r\n<br><br>";
			//echo "7";
			if ( is_multisite() )
				$blogname = $GLOBALS['current_site']->site_name;
			else
				$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
		
			//echo "8";
			
			$title = sprintf( __('[%s] Password Reset'), $blogname );			

			//$title = apply_filters('retrieve_password_title', $title);

			$title = apply_filters( 'retrieve_password_title', $title, $user_login, $user_data );

			if ( $message && !wp_mail($user_email, $title, $message) ) {
				wp_die( __('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...') );
			}
			
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Retrieve Password Success";
			$array_result['message'] = "Link for password reset has been emailed to ".$user_email.". Please check your email.";
			
		}
	}
	

	
	if($section=="change_password") {	

		$userdata = get_user_by('ID', $param['id']);
		$result = wp_check_password($param['cpw'], $userdata->user_pass, $userdata->ID);		
	
		if(!$result){
			$array_result['success'] = false;
			$array_result['statusCode'] = 403;
			$array_result['code'] = "Error";
			$array_result['message'] ="Incorrect current password";	
		}elseif($param['npw']!=$param['cnpw']){
			$array_result['success'] = false;
			$array_result['statusCode'] = 403;
			$array_result['code'] = "Error";
			$array_result['message'] ="New password and confirm new password not match";	
		}else{
			wp_set_password(trim($param['cnpw']), $param['id']);
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = "Change Password Success";	
		}	
	}


	if($section=="delivery_date_list") {
		$arr_holiday = get_holiday_list();
		$array_result = array();
		$dummy_option = array("actualValue"=>"", "displayValue"=>"", "dayOfWeek"=>"");				
		array_push($array_result, $dummy_option);		
		
		$param['cart'] = str_replace("&Amp&", "&", $param['cart']) ;
		
		$arr_cart = json_decode($param['cart'], true);
		$now = time();		
		/*
		if(date('H', $now)>=16){
			$now+=86400;
		}
		*/
		
		for($i = $now-16*86400; $i< $now+16*86400; $i=$i+86400){
			if(date('N',$i)==7 && date('Y-m-d',$i) != "2022-10-30"){ // if sunday, skip list     
			//if(date('N',$i)==7){
				continue;
			}
			/*		
			if(in_array(date('Y-m-d',$i),$arr_holiday)){
				continue;
			}
			*/

			$avail = true;
			foreach($arr_cart['item'] as $cart) {						
				$sku = $cart['sku'];
				$stock_sku = get_master_sku($sku);
				$unit_qty = 1;
				if(has_master_sku($sku)){
					$unit_qty = get_master_sku_unit_qty($sku);	
				}else{
					//check variation for old product
					$variation_id = $cart['variationID'];												
					if($variation_id!=0){				
						$unit_qty = get_variation_unit_qty($variation_id);
					}else{
						$unit_qty = 1;
					}	
				}
	
				$count = $cart['quantity']*$unit_qty;	
									
				if($count>get_sku_stock_by_date($stock_sku,date('Y-m-d', $i)))
					$avail = false;				
			}
			
			/*
			if(!$avail){
				continue;
			}
			*/						
						
			
			$array_option = array("actualValue"=>date('Y-m-d', $i), "displayValue"=>date('Y-m-d', $i), "dayOfWeek"=>date('l', $i));
			array_push($array_result, $array_option);
		}	
		
		//echo "array count: ".count($arr_option);
		if(count($array_result)==1){
			$array_option = array("actualValue"=>"", "displayValue"=>"Please contact (WhatsApp: +852 5612 5381) for help", "dayOfWeek"=>"");
			array_push($array_result, $array_option);
		}

		
		//print_r($array_result);
		
	}
	
	if($section=="region_list") {		
		/*
		$total = (isset($_GET['total']) && $_GET['total']!="")?$_GET['total']:0;
		
		$dummy_method_list = array();
		$dummy_method = array("id"=>"", "instance_id"=>0, "title"=>"", "nice_name"=>"", "requires"=>"", "min_amount"=>0, "cost"=>0);	
		array_push($dummy_method_list, $dummy_method);
		
		$dummy_option = array("id"=>0, "code"=>"", "name"=>"", "location"=>"", "method"=>$dummy_method_list);		
		$array_result = array();
		array_push($array_result, $dummy_option);
		$delivery_zones = WC_Shipping_Zones::get_zones();
		
		foreach ((array) $delivery_zones as $key => $zone ) {

		  $methodList = array();
		  $methodArr =  array("id"=>"", "instance_id"=>0, "title"=>"", "nice_name"=>"", "requires"=>"", "min_amount"=>0, "cost"=>0);	
		  array_push($methodList, $methodArr);
		  foreach($zone['shipping_methods'] as $idx => $method) {
			  
			  $show = false;
			  
			  if($method->enabled == "yes") {
				  if($method->instance_settings['requires']=="" || is_null($method->instance_settings['requires'])){
						$show = true;  
				  }elseif($method->instance_settings['requires']=="min_amount"){
					  $min_amount = (isset($method->instance_settings['min_amount']) && $method->instance_settings['min_amount']!="")?$method->instance_settings['min_amount']:0;
					  if($total>=$min_amount){
						   $show = true;  
					  } 
				  }
			  }
			  
			  if($show) {
				  			  
				$result = $wpdb->get_results("SELECT name FROM `custom_shipping_method` WHERE code = '".trim($method->instance_settings['title'])."' LIMIT 1");
				if(count($result)==1){
					$nice_name = $result[0]->name;
				}else{
					$nice_name = $method->instance_settings['title'];
				}				  						
			  
				$methodArr = array("id"=>$method->id, "instance_id"=>$method->instance_id, "title"=>$method->instance_settings['title'], "nice_name"=>$nice_name, "requires"=>isset($method->instance_settings['requires'])?$method->instance_settings['requires']:"", "min_amount"=>intval((isset($method->instance_settings['min_amount']) && $method->instance_settings['min_amount']!="")?$method->instance_settings['min_amount']:0), "cost"=>intval((isset($method->instance_settings['cost']) && $method->instance_settings['cost']!="")?$method->instance_settings['cost']:0));	
				array_push($methodList, $methodArr);  
				  
			  }
		  }
		  
		  $code = explode(":",$zone['zone_locations'][0]->code);
		  		  
		  $array_option = array("id"=>$zone['id'], "code"=>$code[1], "name"=>$zone['zone_name'], "location"=>$zone['formatted_zone_location'], "method"=>$methodList);

		  array_push($array_result, $array_option);
		}	
		
		$keys = array_column($array_result, 'location');
		array_multisort($keys, SORT_ASC, $array_result);

		*/

		$total = (isset($_GET['total']) && $_GET['total']!="")?$_GET['total']:0;
		
		$dummy_method_list = array();
		$dummy_method = array("id"=>"", "instance_id"=>0, "title"=>"", "nice_name"=>"", "requires"=>"", "min_amount"=>0, "cost"=>0);	
		array_push($dummy_method_list, $dummy_method);
		
		$dummy_option = array("id"=>0, "code"=>"", "name"=>"", "location"=>"", "method"=>$dummy_method_list);		
		$array_result = array();
		$aray_data = array();
		array_push($aray_data, $dummy_option);
		$delivery_zones = WC_Shipping_Zones::get_zones();
		
		foreach ((array) $delivery_zones as $key => $zone ) {

		  $methodList = array();
		  $methodArr =  array("id"=>"", "instance_id"=>0, "title"=>"", "nice_name"=>"", "requires"=>"", "min_amount"=>0, "cost"=>0);	
		  array_push($methodList, $methodArr);
		  foreach($zone['shipping_methods'] as $idx => $method) {
			  
			  $show = false;
			  
			  if($method->enabled == "yes") {
				  if($method->instance_settings['requires']=="" || is_null($method->instance_settings['requires'])){
						$show = true;  
				  }elseif($method->instance_settings['requires']=="min_amount"){
					  $min_amount = (isset($method->instance_settings['min_amount']) && $method->instance_settings['min_amount']!="")?$method->instance_settings['min_amount']:0;
					  if($total>=$min_amount){
						   $show = true;  
					  } 
				  }
			  }
			  
			  if($show) {
				  			  
				$result = $wpdb->get_results("SELECT name FROM `custom_shipping_method` WHERE code = '".trim($method->instance_settings['title'])."' LIMIT 1");
				if(count($result)==1){
					$nice_name = $result[0]->name;
				}else{
					$nice_name = $method->instance_settings['title'];
				}				  						
			  
				$methodArr = array("id"=>$method->id, "instance_id"=>$method->instance_id, "title"=>$method->instance_settings['title'], "nice_name"=>$nice_name, "requires"=>isset($method->instance_settings['requires'])?$method->instance_settings['requires']:"", "min_amount"=>intval((isset($method->instance_settings['min_amount']) && $method->instance_settings['min_amount']!="")?$method->instance_settings['min_amount']:0), "cost"=>intval((isset($method->instance_settings['cost']) && $method->instance_settings['cost']!="")?$method->instance_settings['cost']:0));	
				array_push($methodList, $methodArr);  
				  
			  }
		  }
		  
		  $code = explode(":",$zone['zone_locations'][0]->code);
		  		  
		  $array_option = array("id"=>$zone['id'], "code"=>$code[1], "name"=>$zone['zone_name'], "location"=>$zone['formatted_zone_location'], "method"=>$methodList);

		  array_push($aray_data, $array_option);
		}	
		
		$keys = array_column($aray_data, 'location');
		array_multisort($keys, SORT_ASC, $aray_data);	
		$array_result['data'] =  $aray_data;

	}		
	
	if($section=="verify_coupon") {	
		
		$array_result['success'] = true;
		
		//$param['cart'] = str_replace("&Amp&", "&", $param['cart']) ;
		//$cart = json_decode($param['cart'], true);
		
		/* 
			Modified by: Benton Tsang @2023-07-03 
		*/
		//var_dump($_POST);
		$cart = $_POST['cart'];
		$code = $_POST['code'];

		$product = $cart['item'];
		/* End Modification */

		if(count($product) == 0 ){
			$array_result['success'] = false;
		}
				
		$subTotal = 0;
		foreach($cart['item'] as $cartItem){
			$subTotal += ($cartItem['quantity'] * $cartItem['product_price']);
		}

		$coupon = new WC_Coupon($code);
		
		if($code!=""){
		
			if($coupon->id != 0){ // check coupon exist
				$coupon_post = get_post($coupon->id);	
				$coupon_data = array(
					'id' => $coupon->id,
					'code' => $coupon->code,
					'type' => $coupon->type,
					'created_at' => $coupon_post->post_date_gmt,
					'updated_at' => $coupon_post->post_modified_gmt,
					'amount' => wc_format_decimal($coupon->coupon_amount, 2),
					'individual_use' => ( 'yes' === $coupon->individual_use ),
					'product_ids' => array_map('absint', (array) $coupon->product_ids),
					'exclude_product_ids' => array_map('absint', (array) $coupon->exclude_product_ids),
					'usage_limit' => (!empty($coupon->usage_limit) ) ? $coupon->usage_limit : null,
					'usage_count' => (int) $coupon->usage_count,
					'expiry_date' => (!empty($coupon->expiry_date) ) ? date('Y-m-d', strtotime($coupon->expiry_date)) : null,		
					'enable_free_shipping' => $coupon->enable_free_shipping(),
					'product_category_ids' => array_map('absint', (array) $coupon->product_categories),
					'exclude_product_category_ids' => array_map('absint', (array) $coupon->exclude_product_categories),
					'exclude_sale_items' => $coupon->exclude_sale_items(),
					'minimum_amount' => wc_format_decimal($coupon->minimum_amount, 2),
					'maximum_amount' => wc_format_decimal($coupon->maximum_amount, 2),
					'customer_emails' => $coupon->customer_email,
					'description' => $coupon_post->post_excerpt,
				);				
				

				$discount = 0.00;
				if($coupon_data['type'] == 'percent') {
					//$subTotal = (float) $subTotal;
					//$coupon_data['amount'] = (float) $coupon_data['amount'];
					//$discount = number_format(($subTotal * $coupon_data['amount'] / 100),2);
					$discount = $subTotal * $coupon_data['amount']/100;
					//$discount = number_format($discount, 2, "");
				} elseif($coupon_data['type'] == 'fixed_cart'){
					$discount = number_format($coupon_data['amount'],2);
				}
				
				
				if($coupon_data['expiry_date']=="" || date('Y-m-d') <= $coupon_data['expiry_date']) { //check coupon expire
					
					if($coupon_data['minimum_amount']==0.00 || $subTotal >= $coupon_data['minimum_amount']){ //check min. cart amount
						
						if($coupon_data['maximum_amount']==0.00 || $subTotal <= $coupon_data['maximum_amount']){ //check max. cart amount
							
							if($coupon_data['usage_limit']==0.00 || $coupon_data['usage_limit'] > $coupon_data['usage_count']) { // check usage limit
							
								if(count($coupon_data['product_ids'])>0) { //check allowable list			
									$check_allowable = true;			
									foreach($cart as $cartItem){
										if(!in_array($cartItem['product_id'],$coupon_data['product_ids']))	{
											$check_allowable = false;	
										}
									}
									
									if(!$check_allowable){
										$array_result['success'] = false;
										$array_result['statusCode'] = 200;
										$array_result['code'] = "Error";
										$array_result['message'] = "Coupon cannot be applied on some products";
										$array_result['discount'] = 0.00;
									} else {
										$array_result['success'] = true;
										$array_result['statusCode'] = 200;
										$array_result['code'] = "Success";
										$array_result['message'] = "Coupon Validated";
										$array_result['discount'] = (float)$discount;///////////////////////////////
									}
									
								} elseif(count($coupon_data['exclude_product_ids'])>0) { //check exclude list		
										
									$check_exlude = true;			
									foreach($cart as $cartItem){
										if(!in_array($cartItem['product_id'],$coupon_data['exclude_product_ids']))	{
											$check_exlude = false;	
										}
									}
									
									if(!$check_exlude) {
										$array_result['success'] = false;
										$array_result['statusCode'] = 200;
										$array_result['code'] = "Error";
										$array_result['message'] = "Coupon cannot be applied on some products";
										$array_result['discount'] = 0.00;
									} else {
										$array_result['success'] = true;
										$array_result['statusCode'] = 200;
										$array_result['code'] = "Success";
										$array_result['message'] = "Coupon Validated";
										$array_result['discount'] = (float)$discount; ///////////////////////////////
									}
														
								} else {
									$array_result['success'] = true;
									$array_result['statusCode'] = 200;
									$array_result['code'] = "Success";
									$array_result['message'] = "Coupon Validated";
									$array_result['discount'] = (float)$discount; ///////////////////////////////
								}
								
							} else {
								$array_result['success'] = false;
								$array_result['statusCode'] = 200;
								$array_result['code'] = "Error";
								$array_result['message'] = "Coupon reached usage limit";
								$array_result['discount'] = 0.00;	
							}
							
						} else {
							$array_result['success'] = false;
							$array_result['statusCode'] = 200;
							$array_result['code'] = "Error";
							$array_result['message'] = "Coupon does not meet the max. order amount";
							$array_result['discount'] = 0.00;				
						}
						
					} else {
						$array_result['success'] = false;
						$array_result['statusCode'] = 200;
						$array_result['code'] = "Error";
						$array_result['message'] = "Coupon does not meet the min. order amount";
						$array_result['discount'] = 0.00;		
					}
					
				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Error";
					$array_result['message'] = "Coupon expired";
					$array_result['discount'] = 0.00;
				}
						
				
			} else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] = "Invalid coupon code";
				$array_result['discount'] = 0.00;			
			}
		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";
			$array_result['message'] = "Empty coupon code";
			$array_result['discount'] = 0.00;			
		}
	} 	

	if($section=="check_stock"){

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "";
		$array_result['data'] = array();
		
		$order_id = $_POST['order_id'];
		$cart = $_POST['cart'];
		$delivery_date = $cart['date'];

		$check_stock = true;

		if(!empty($order_id)){
			$check_order = wc_get_order($order_id);	

			if(!$check_order->has_status('pending') && !$check_order->has_status('failed')){
				$check_stock = false;
			}

		} 

		if($check_stock){

			if(count($cart['item']) == 0 ){
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";	
				$array_result['message'] = "No item(s) in Cart";		
			} else {
				$i = 0;
				$arr_error_item = 0;
				foreach($cart['item'] as $item_info){						
					$stock_sku = get_master_sku($item_info['sku']);
					$unit_qty = 1;
					if(has_master_sku($item_info['sku'])){
						$unit_qty = get_master_sku_unit_qty($item_info['sku']);	
						$description = $item_info['product_name'];
					} else {
						$variation_id = $item_info['variation_id'];	
						
						if($variation_id!=0){				
							$description = $item_info['product_name'];
							$unit_qty = get_variation_unit_qty($variation_id);
						} else {					
							$description = $item_info['product_name'];
							$unit_qty = 1;
						}	
					}
					$quantity = $item_info['quantity']*$unit_qty;	
								
					$diff = (get_sku_stock_by_date($stock_sku, $delivery_date)<0?0:get_sku_stock_by_date($stock_sku, $delivery_date)) - $quantity;

					// for testing //
					/*
					if($i==0) {
						$diff = rand(1,$item_info['quantity'])*-1;
					}
					*/
					
					if($diff<0) {
						$arr_error_item++;

						$array_result['data'][] = array(
							"product_id"=>intval($item_info['product_id']),
							"variation_id"=>intval(is_null($item_info['variation_id'])?0:$item_info['variation_id']),
							"stock_qty"=>get_sku_stock_by_date($stock_sku, $delivery_date),
							"input_qty"=>$quantity,
							"subtract_by"=>abs($diff/$unit_qty),
						);
					}
					$i++;
				}

				//echo "error count:".$arr_error_item;

				if($arr_error_item>0){
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Error";				
					$array_result['message'] = $arr_error_item." item(s) is out of stock in the selected date. Please select another delivery date";		
				}

			}
		} else {
			$array_result['data']=array();
		}
	}		
	
	if($section=="create_order") {	
		
//		error_reporting(E_ALL);
//		ini_set('display_errors', 1);		

		$create_order = true;
		
		if(isset($_POST['order_id']) && !empty($_POST['order_id'])){ // if order id is set and not empty

			$check_order = wc_get_order($_POST['order_id']);	

			if($check_order->has_status('pending') || $check_order->has_status('processing') || $check_order->has_status('failed')){
				$create_order = false;
			}
		} 

		if($create_order){

			$array_result['success'] = false;
			
			// added queue for creating order (by samiel 13/4/2022)
			// will try for 20 times with 0.5 second interval
			for($trail_count = 1; $trail_count <= 20; $trail_count++){	
				$flag = get_custom_value("creating_order");			
				if($flag=="N"){
					$array_result['success'] = true;
					break;
				}		
				usleep(500000);
			}

			// init and get value
			$cart = $_POST['cart'];
			$data = $_POST['data'];

			if(count($cart['item']) == 0 ){
				$array_result['success'] = false;
			}		

			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = "";
			$array_result['data'] = array();


			$user_id = $data['id'];
			$delivery_date = $cart['date'];
			$order_status = $_POST['order_status'];
			$shipment_method = $_POST['shipment_method'];
			$payment_method = $_POST['payment_method'];

			$billing_first_name = $data['billing']['first_name'];
			$billing_last_name  = $data['billing']['last_name'];
			$billing_company 	= $data['billing']['company'];
			$billing_address_1  = $data['billing']['address_1'];
			$billing_address_2  = $data['billing']['address_2'];
			$billing_city 	    = $data['billing']['city'];
			$billing_state 		= $data['billing']['state'];
			$billing_postcode   = $data['billing']['postcode'];
			$billing_country    = $data['billing']['country'];
			$billing_phone      = $data['billing']['phone'];
			$billing_email      = $data['billing']['email'];

			$shipping_first_name = $data['shipping']['first_name'];
			$shipping_last_name  = $data['shipping']['last_name'];
			$shipping_company 	 = $data['shipping']['company'];
			$shipping_address_1  = $data['shipping']['address_1'];
			$shipping_address_2  = $data['shipping']['address_2'];
			$shipping_city 	     = $data['shipping']['city'];
			$shipping_state 	 = $data['shipping']['state'];
			$shipping_postcode   = $data['shipping']['postcode'];
			$shipping_country    = $data['shipping']['country'];
			$shipping_phone      = $data['shipping']['phone'];
			$shipping_email      = $data['shipping']['email'];
			
			$shipping_method_title = $shipment_method['title'];
			$shipping_method_id = $shipment_method['id'];
			$shipping_method_total = $shipment_method['cost'];
			
			$payment_method_title = $payment_method['title'];
			$payment_method_id = $payment_method['id'];
			$payment_method_name = $payment_method['id'];
			$payment_terms = $payment_method['payment_terms'];
			
			$order_comments = $_POST['order_remark'];		
			//$paymentIntent = $info['paymentIntentID'];
			$coupon_code = $_POST['coupon_code'];				
			$adjust_stock = $_POST['adjust_stock'];
			
			
			// init product variable for woocommerce
			$arr_item = array();
			
			$i = 0;
			$arr_error_item = 0;
			foreach($cart['item'] as $item_info){						
				$stock_sku = get_master_sku($item_info['sku']);
				$unit_qty = 1;
				if(has_master_sku($item_info['sku'])){
					$unit_qty = get_master_sku_unit_qty($item_info['sku']);	
					$description = $item_info['product_name'];
				} else {
					$variation_id = $item_info['variation_id'];	
					
					if($variation_id!=0){				
						$description = $item_info['product_name'];
						$unit_qty = get_variation_unit_qty($variation_id);
					} else {					
						$description = $item_info['product_name'];
						$unit_qty = 1;
					}	
				}
				$quantity = $item_info['quantity']*$unit_qty;	
							
				$diff = (get_sku_stock_by_date($stock_sku, $delivery_date)<0?0:get_sku_stock_by_date($stock_sku, $delivery_date)) - $quantity;

				if($diff<0) {
					$arr_error_item++;

					$array_result['data'][] = array(
						"product_id"=>intval($item_info['product_id']),
						"variation_id"=>intval(is_null($item_info['variation_id'])?0:$item_info['variation_id']),
						"stock_qty"=>get_sku_stock_by_date($stock_sku, $delivery_date),
						"input_qty"=>$quantity,
						"subtract_by"=>abs($diff/$unit_qty),
					);
				}
				$i++;

				$arr_content = array();
				$arr_content['quantity'] = $item_info['quantity'];
				$arr_content['args'] = array();
				$arr_content['args']['sku'] = $item_info['sku'];
				$arr_content['args']['product_id'] = $item_info['product_id'];
				$arr_content['args']['variation_id'] = $item_info['variation_id'];
				$arr_content['args']['variation'] = array();
				$arr_content['args']['subtotal'] = $item_info['product_price'];
				$arr_content['args']['total'] = $item_info['quantity'] * $item_info['product_price'];
				array_push($arr_item, $arr_content);			
			}

			/*
			if($arr_error_item>0){
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";				
				$array_result['message'] = $arr_error_item." item(s) is out of stock in the selected date. Please select another delivery date";						
			}
			*/
			
			if($array_result['success']==true) {

					$wpdb->update('custom_value', array( 'field_value' => 'Y' ), array( 'field_name' => 'creating_order'));
					
					$order_id = create_wc_order( 
						array(				
							'billing' => array(
								'first_name' => $billing_first_name,
								'last_name'  => $billing_last_name,
								'company'  	 => $billing_company,
								'email'      => $billing_email,
								'phone'      => $billing_phone,
								'address_1'  => $billing_address_1,
								'address_2'  => $billing_address_2,				
								'city'       => $billing_city,
								'state'      => $billing_state,
								'postcode'   => $billing_postcode,
								'country'    => $billing_country
							),
							'shipping' => array(
								'first_name' => $shipping_first_name,
								'last_name'  => $shipping_last_name,
								'company'  	 => $shipping_company,
								'email'      => $shipping_email,
								'phone'      => $shipping_phone,
								'address_1'  => $shipping_address_1,
								'address_2'  => $shipping_address_2,				
								'city'       => $shipping_city,
								'state'      => $shipping_state,
								'postcode'   => $shipping_postal_code,
								'country'    => $shipping_country
							),				
							'user_id'        => $user_id,
							'order_comments' => $order_comments,
							'payment_method_title' => $payment_method_title,		
							'payment_method_id' => $payment_method_id,
							'payment_method_name' => $payment_method_name,		
							'order_status'   => array(
								'status' => $order_status,
								//'status' => 'on-hold',
								'note'   => '',
							),
							'line_items' => $arr_item,
							'coupon_items' => array(
								array(
									'code' => $coupon_code
								),
							),				
							'shipping_lines' => array(
								'method_id' => $shipping_method_id,
								'method_title' => $shipping_method_title,
								'total' => $shipping_method_total
							),
							'delivery_date' => $delivery_date,		
							'payment_intent' => $paymentIntent,
							'customer_ip' => getCustomerIpAddr(),
							'adjust_stock' => $adjust_stock,
							'payment_terms' => $payment_terms
						)
					); 
				
					
				if(isset($order_id) && $order_id>0) {
						$new_order = new WC_Order($order_id);				  
						$array_result['success'] = true;
						$array_result['statusCode'] = 200;
						$array_result['code'] = $paymentIntent;
						$array_result['message'] = "Order# created: ".$new_order->get_order_number();
						$array_result['id'] = $order_id;
						$array_result['number'] = $new_order->get_order_number();
						$array_result['total'] = strval($new_order->get_total());
				} else {
						$array_result['success'] = false;
						$array_result['statusCode'] = 200;
						$array_result['code'] = "Error";
						$array_result['message'] ="Fail to create order";
						$array_result['id'] = 0;
						$array_result['number'] = "";
						$array_result['total'] = strval(0);
				}				
					
				$wpdb->update('custom_value', array( 'field_value' => 'N' ), array( 'field_name' => 'creating_order'));
				
								
			} else {
				if($flag=="Y"){
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Error";
					$array_result['message'] ="System is busy right now. Please try again later";
					$array_result['id'] = 0;
					$array_result['number'] = "";			
				}
			}	
		} else {

			if(isset($_POST['shipment_method']['title']) && !empty($_POST['shipment_method']['title'])){

				$ship_line_sql = $wpdb->get_results("Select order_item_id FROM wp_woocommerce_order_items WHERE order_id = '".$_POST['order_id']."' AND order_item_type = 'shipping' ");
				foreach($ship_line_sql as $ship_line_obj){
					wc_delete_order_item($ship_line_obj->order_item_id);
				}

				$shipping_lines = new WC_Order_Item_Shipping();	
				$shipping_lines->set_method_title($_POST['shipment_method']['title']);
				$shipping_lines->set_method_id($_POST['shipment_method']['id']);
				$shipping_lines->set_total($_POST['shipment_method']['cost']);
				$check_order->add_item($shipping_lines);
				$check_order->calculate_totals();
				$check_order->save();				
			}			
			
			if($check_order->has_status('pending')){	
				if(isset($_POST['coupon_code']) && !empty($_POST['coupon_code'])){
					$check_order->apply_coupon(sanitize_title($_POST['coupon_code']));
					$check_order->calculate_totals();
					$check_order->save();
				} else {
					$current_conpon_code_list = $check_order->get_coupon_codes();
					foreach($current_conpon_code_list as $current_coupon_code){
						$check_order->remove_coupon($current_coupon_code);
					}
					$check_order->calculate_totals();
					$check_order->save();
				}
			}

			if(isset($_POST['payment_method']['id']) && !empty($_POST['payment_method']['id'])){
				update_post_meta($_POST['order_id'], '_payment_method', $_POST['payment_method']['id']);
				update_post_meta($_POST['order_id'], '_payment_method_title', $_POST['payment_method']['title']);
				update_post_meta($_POST['order_id'], 'Payment', $_POST['payment_method']['nice_name']);
			}

			if(isset($_POST['data']['shipping'])){

				foreach ($_POST['data']['shipping'] as $meta_key => $meta_value ) {
					$update_key = "_shipping_".$meta_key;
					update_post_meta($_POST['order_id'], $update_key, $meta_value );
				}

				update_post_meta($_POST['order_id'], "_shipping_address_index", implode('', $_POST['data']['shipping']) );
				
			}


			if($check_order->has_status('pending')){				
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Order is in pending status";
				$array_result['id'] = intval($_POST['order_id']);
				$array_result['number'] = $check_order->get_order_number();
				$array_result['total'] = strval($check_order->get_total());
			}

			if($check_order->has_status('processing')){				
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Order is in processing status";
				$array_result['id'] = 0;
				$array_result['number'] = "";
				$array_result['total'] = "";
			}

			if($check_order->has_status('failed')){				
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Order is in failed status";
				$array_result['id'] = intval($_POST['order_id']);
				$array_result['number'] = $check_order->get_order_number();
				$array_result['total'] = strval($check_order->get_total());
			}			

		}
	} 	

/*	
	if($section=="create_order") {		
		
		$array_result['success'] = false;
		
		// added queue for creating order (by samiel 13/4/2022)
		// will try for 20 times with 0.5 second interval
		for($trail_count = 1; $trail_count <= 20; $trail_count++){	
			$flag = get_custom_value("creating_order");			
			if($flag=="N"){
				$array_result['success'] = true;
				break;
			}		
			usleep(500000);
		}

		// init and get value
		$cart = $_POST['cart'];
		$data = $_POST['data'];

		if(count($cart['item']) == 0 ){
			$array_result['success'] = false;
		}		

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "";
		$array_result['data'] = array();


		$user_id = $data['id'];
		$delivery_date = $cart['date'];
		$order_status = $_POST['order_status'];
		$shipment_method = $_POST['shipment_method'];
		$payment_method = $_POST['payment_method'];

		$billing_first_name = $data['billing']['first_name'];
		$billing_last_name  = $data['billing']['last_name'];
		$billing_company 	= $data['billing']['company'];
		$billing_address_1  = $data['billing']['address_1'];
		$billing_address_2  = $data['billing']['address_2'];
		$billing_city 	    = $data['billing']['city'];
		$billing_state 		= $data['billing']['state'];
		$billing_postcode   = $data['billing']['postcode'];
		$billing_country    = $data['billing']['country'];
		$billing_phone      = $data['billing']['phone'];
		$billing_email      = $data['billing']['email'];

		$shipping_first_name = $data['shipping']['first_name'];
		$shipping_last_name  = $data['shipping']['last_name'];
		$shipping_company 	 = $data['shipping']['company'];
		$shipping_address_1  = $data['shipping']['address_1'];
		$shipping_address_2  = $data['shipping']['address_2'];
		$shipping_city 	     = $data['shipping']['city'];
		$shipping_state 	 = $data['shipping']['state'];
		$shipping_postcode   = $data['shipping']['postcode'];
		$shipping_country    = $data['shipping']['country'];
		$shipping_phone      = $data['shipping']['phone'];
		$shipping_email      = $data['shipping']['email'];
		
		$shipping_method_title = $shipment_method['title'];
		$shipping_method_id = $shipment_method['local_pickup'];
		$shipping_method_total = $shipment_method['cost'];
		
		$payment_method_title = $payment_method['title'];
		$payment_method_id = $payment_method['id'];
		$payment_method_name = $payment_method['id'];
		$payment_terms = $payment_method['payment_terms'];
		
		$order_comments = $_POST['order_remark'];		
		//$paymentIntent = $info['paymentIntentID'];
		$coupon_code = $_POST['coupon_code'];				
		$adjust_stock = $_POST['adjust_stock'];
		
		
		// init product variable for woocommerce
		$arr_item = array();
		
		$i = 0;
		$arr_error_item = 0;
		foreach($cart['item'] as $item_info){						
			$stock_sku = get_master_sku($item_info['sku']);
			$unit_qty = 1;
			if(has_master_sku($item_info['sku'])){
				$unit_qty = get_master_sku_unit_qty($item_info['sku']);	
				$description = $item_info['product_name'];
			} else {
				$variation_id = $item_info['variation_id'];	
				
				if($variation_id!=0){				
					$description = $item_info['product_name'];
					$unit_qty = get_variation_unit_qty($variation_id);
				} else {					
					$description = $item_info['product_name'];
					$unit_qty = 1;
				}	
			}
			$quantity = $item_info['quantity']*$unit_qty;	
						
			$diff = (get_sku_stock_by_date($stock_sku, $delivery_date)<0?0:get_sku_stock_by_date($stock_sku, $delivery_date)) - $quantity;

			if($diff<0) {
				$arr_error_item++;

				$array_result['data'][] = array(
					"product_id"=>intval($item_info['product_id']),
					"variation_id"=>intval(is_null($item_info['variation_id'])?0:$item_info['variation_id']),
					"stock_qty"=>get_sku_stock_by_date($stock_sku, $delivery_date),
					"input_qty"=>$quantity,
					"subtract_by"=>abs($diff/$unit_qty),
				);
			}
			$i++;

			$arr_content = array();
			$arr_content['quantity'] = $item_info['quantity'];
			$arr_content['args'] = array();
			$arr_content['args']['sku'] = $item_info['sku'];
			$arr_content['args']['product_id'] = $item_info['product_id'];
			$arr_content['args']['variation_id'] = $item_info['variation_id'];
			$arr_content['args']['variation'] = array();
			$arr_content['args']['subtotal'] = $item_info['product_price'];
			$arr_content['args']['total'] = $item_info['quantity'] * $item_info['product_price'];
			array_push($arr_item, $arr_content);			
		}

		if($arr_error_item>0){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";				
			$array_result['message'] = $arr_error_item." item(s) is out of stock in the selected date. Please select another delivery date";		
		}
		
		if($array_result['success']==true) {

				$wpdb->update('custom_value', array( 'field_value' => 'Y' ), array( 'field_name' => 'creating_order'));
			    
				$order_id = create_wc_order( 
					array(				
						'billing' => array(
							'first_name' => $billing_first_name,
							'last_name'  => $billing_last_name,
							'company'  	 => $billing_company,
							'email'      => $billing_email,
							'phone'      => $billing_phone,
							'address_1'  => $billing_address_1,
							'address_2'  => $billing_address_2,				
							'city'       => $billing_city,
							'state'      => $billing_state,
							'postcode'   => $billing_postcode,
							'country'    => $billing_country
						),
						'shipping' => array(
							'first_name' => $shipping_first_name,
							'last_name'  => $shipping_last_name,
							'company'  	 => $shipping_company,
							'email'      => $shipping_email,
							'phone'      => $shipping_phone,
							'address_1'  => $shipping_address_1,
							'address_2'  => $shipping_address_2,				
							'city'       => $shipping_city,
							'state'      => $shipping_state,
							'postcode'   => $shipping_postal_code,
							'country'    => $shipping_country
						),				
						'user_id'        => $user_id,
						'order_comments' => $order_comments,
						'payment_method_title' => $payment_method_title,		
						'payment_method_id' => $payment_method_id,
						'payment_method_name' => $payment_method_name,		
						'order_status'   => array(
							'status' => $order_status,
							//'status' => 'on-hold',
							'note'   => '',
						),
						'line_items' => $arr_item,
						'coupon_items' => array(
							array(
								'code' => $coupon_code
							),
						),				
						'shipping_lines' => array(
							'method_id' => $shipping_method_id,
							'method_title' => $shipping_method_title,
							'total' => $shipping_method_total
						),
						'delivery_date' => $delivery_date,		
						'payment_intent' => $paymentIntent,
						'customer_ip' => getCustomerIpAddr(),
						'adjust_stock' => $adjust_stock,
						'payment_terms' => $payment_terms
					)
			    ); 
			
				
			  if(isset($order_id) && $order_id>0) {
				    $new_order = new WC_Order($order_id);				  
					$array_result['success'] = true;
					$array_result['statusCode'] = 200;
					$array_result['code'] = $paymentIntent;
					$array_result['message'] = "Order# created: ".$new_order->get_order_number();
					$array_result['id'] = $order_id;
					$array_result['number'] = $new_order->get_order_number();
					$array_result['total'] = strval($new_order->get_total());
			  } else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Error";
					$array_result['message'] ="Fail to create order";
					$array_result['id'] = 0;
					$array_result['number'] = "";
					$array_result['total'] = strval(0);
			  }				
				
			  $wpdb->update('custom_value', array( 'field_value' => 'N' ), array( 'field_name' => 'creating_order'));
			  
							  
		} else {
			if($flag=="Y"){
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] ="System is busy right now. Please try again later";
				$array_result['id'] = 0;
				$array_result['number'] = "";			
			}
		}	
		
	} 	
*/
	

	if($section=="update_order") {
		global $wpdb;			
		  if($param['order_id']!="0" && $param['payment_intent']!="") {			    
				update_post_meta($param['order_id'], '_stripe_intent_id', $param['payment_intent']);			  	
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = $param['payment_intent'];
				$array_result['message'] = "Order Updated: #".$order_id;
				$array_result['id'] = intval($param['order_id']);				
		  } else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] ="Fail to update order";
				$array_result['id'] = 0;
		  }
	}
	
	if($section=="cancel_order") {
		global $wpdb;			
		  if($_POST['order_id']!="0") {			    
				$order = new WC_Order($_POST['order_id']); 
				if (!empty($order)) {
					$order->update_status('cancelled');
					//change_status_to_cancelled($param['order_id']);
					$array_result['success'] = true;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Success";
					$array_result['message'] = "Order is cancelled";
					$array_result['id'] = intval($_POST['order_id']);
				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Error";
					$array_result['message'] = "Fail to cancel order";
					$array_result['id'] = intval($_POST['order_id']);				
				}
				
		  } else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] ="Fail to cancel order";
				$array_result['id'] = 0;
		  }
	}
	
	if($section=="fail_order") {
		global $wpdb;			
		  if($_POST['order_id']!="0") {			    
				$order = new WC_Order($_POST['order_id']); 
				if (!empty($order)) {
					$order->update_status('failed');
					//change_status_to_cancelled($param['order_id']);
					$array_result['success'] = true;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Success";
					$array_result['message'] = "Order is changed to fail status";
					$array_result['id'] = intval($_POST['order_id']);
				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Error";
					$array_result['message'] = "Unable ro change order to fail staus";
					$array_result['id'] = intval($_POST['order_id']);				
				}
				
		  } else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] ="Unable ro change order to fail staus";
				$array_result['id'] = 0;
		  }
	}


	// no longer use
	if($section=="mark_order_complete"){
		$array_result = array();
			
		if($param['order_id']!=""){		
			$orderDetail = new WC_Order( $param['order_id'] );
			$orderDetail->update_status("wc-completed", 'Completed', TRUE);		
			if($param['payment_method']!=""){
				if(metadata_exists('post', $param['order_id'], 'Payment')) {
					update_post_meta($param['order_id'], 'Payment', $param['payment_method']);			
					wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true);
				} else {
					add_post_meta($param['order_id'], 'Payment', $param['payment_method'], TRUE);
					wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true);
				}
			}		
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] ="Order is marked as completed";
			$array_result['id'] = intval($param['order_id']);
		}else{
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";
			$array_result['message'] ="Fail to complete order";
			$array_result['id'] = 0;
		}
	}		
	
	// update order detail
	if($section=="update_order_detail"){
		
		$array_result = array();
		
		if(!empty($param['order_id'])){

			$orderDetail = new WC_Order($param['order_id']);
			$oldStatus = $orderDetail->get_status();
			$oldPaymenyMethod = get_post_meta($param['order_id'], 'Payment', true);				
			
			if($param['status']=="on-hold" || $param['status']=="pending" || $param['status']=="processing"){
				if($oldStatus!=$param['status']){
					$orderDetail->update_status($param['status'], ucwords($param['status']), TRUE);		
				}
				
				if($param['payment_method']!=""){
					if(metadata_exists('post', $param['order_id'], 'Payment')) {
						update_post_meta($param['order_id'], 'Payment', $param['payment_method']);			
						if($oldPaymenyMethod!=$param['payment_method']){
							wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true);
						}
					} else {
						add_post_meta($param['order_id'], 'Payment', $param['payment_method'], TRUE);
						wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true);
					}
				}	
					
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] ="Order data is updated";
				$array_result['id'] = intval($param['order_id']);				
			} elseif($param['status']=="completed") {
				if($oldStatus!=$param['status']){
					$orderDetail->update_status("completed", 'Completed', TRUE);		
				}
				
				if($param['payment_method']!=""){
					if(metadata_exists('post', $param['order_id'], 'Payment')) {
						update_post_meta($param['order_id'], 'Payment', $param['payment_method']);			
						if($oldPaymenyMethod!=$param['payment_method']){
							wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true);
						}
					} else {
						add_post_meta($param['order_id'], 'Payment', $param['payment_method'], TRUE);
						wc_create_order_note($param['order_id'], "Payment: ".sanitize_text_field( $param['payment_method'] ), false, true);
					}
				}		
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] ="Order data is updated";
				$array_result['id'] = intval($param['order_id']);
			} elseif($param['status']=="cancelled") {
				if($oldStatus!=$param['status']){
					$orderDetail->update_status("cancelled", 'Cancelled', TRUE);	
				}
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Order data is updated";
				$array_result['id'] = intval($param['order_id']);				
			} else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] ="Unknow process";
				$array_result['id'] = 0;				
			}
		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";
			$array_result['message'] ="Fail to change order status";
			$array_result['id'] = 0;			
		}
		
	}
		

	if($section=="get_my_product_review"){

		$user_id = $_GET['user_id'];

		$comments = array();
		
		$sql_query = "SELECT wpc.comment_post_ID, wpc.comment_author, wpc.comment_author_email, wpc.comment_date, wpc.comment_content, wpcm.meta_value AS rating FROM wp_comments AS wpc INNER JOIN  wp_commentmeta AS wpcm ON wpcm.comment_id = wpc.comment_id AND wpcm.meta_key = 'rating' WHERE wpc.user_id = '".$user_id."' AND wpc.comment_approved = '1' ORDER BY wpc.comment_date DESC";

		$comment_and_reviews = $wpdb->get_results($sql_query);
		foreach($comment_and_reviews as $review){	
			$comments[] = array(
				"product_id"=>intval($review->comment_post_ID),
				"author"=>$review->comment_author,
				"email"=>$review->comment_author_email,
				"date"=>$review->comment_date,
				"content"=>$review->comment_content,
				"rating"=>floatval($review->rating)
			);
		}

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "Review Count: ".count($comments);
		$array_result['data'] = $comments;
	}	




	if($section=="get_product_review"){

		$product_id = $_GET['id'];

		$product_id_zh = 0;
		$trid = $sitepress->get_element_trid($product_id, 'post_product');
		$translations = $sitepress->get_element_translations($trid, 'product');
		foreach( $translations as $lang=>$translation){
			if($translation->language_code == "zh-hant")
				$product_id_zh = $translation->element_id;
		}

		$comments = array();
		
		$sql_query = "SELECT wpc.comment_author, wpc.comment_author_email, wpc.comment_date, wpc.comment_content, wpcm.meta_value AS rating FROM wp_comments AS wpc INNER JOIN  wp_commentmeta AS wpcm ON wpcm.comment_id = wpc.comment_id AND wpcm.meta_key = 'rating' WHERE wpc.comment_post_id IN ('".$product_id."','".$product_id_zh."')  AND wpc.comment_approved = '1' ORDER BY wpc.comment_date DESC";

		$comment_and_reviews = $wpdb->get_results($sql_query);
		foreach($comment_and_reviews as $review){						
			$comments[] = array(
				"author"=>$review->comment_author,
				"email"=>$review->comment_author_email,
				"date"=>$review->comment_date,
				"content"=>$review->comment_content,
				"rating"=>floatval($review->rating)
			);
		}

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "Review Count: ".count($comments);
		$array_result['data'] = $comments;
	}

	if($section=="post_product_review") {

		$product_id = $_POST['product_id'];
		$author = $_POST['author'];
		$email = $_POST['email'];
		$content = $_POST['content'];
		$rating = $_POST['rating'];
		$user_id = $_POST['user_id'];

		$comment_id = wp_insert_comment( array(
			'comment_post_ID'      => $product_id, // <=== The product ID where the review will show up
			'comment_author'       => $author,
			'comment_author_email' => $email, // <== Important
			'comment_author_url'   => '',
			'comment_content'      => $content,
			'comment_type'         => 'review',
			'comment_parent'       => 0,
			'user_id'              => $user_id, // <== Important
			'comment_author_IP'    => '',
			'comment_agent'        => '',
			'comment_date'         => date('Y-m-d H:i:s'),
			'comment_approved'     => 0, // pending review
		) );

		// HERE inserting the rating (an integer from 1 to 5)
		if (isset($_POST['rating']) && !empty($_POST['rating'])){
			update_comment_meta($comment_id, 'rating', $_POST['rating']);
		}

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "Thanks for your review. It will be posted once it is approved";
		
	}


	if($section=="favourite_list"){

		$arr_product_list = array();

		$user_id = $_GET['user_id'];

		$favouriteList = $wpdb->get_results("SELECT * FROM customer_favourite WHERE user_id = '".$user_id."' ORDER BY product_id ASC"); 

		foreach($favouriteList as $favouriteObj){
			$product_id = $favouriteObj->product_id;
			$productObject = wc_get_product($product_id);
			if($productObject->get_status()=="publish")
				array_push($arr_product_list, array("product_id"=>intval($product_id)));
		}

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "";		
		$array_result['data'] = $arr_product_list;

	}

	if($section=="update_favourite_list") {

		$user_id = $_POST['user_id'];
		$action = $_POST['action'];
		$product_id = $_POST['product_id'];

		switch($action){
			case "add":					
				$result = $wpdb->get_results("SELECT * FROM `customer_favourite` WHERE user_id = '".$user_id."' AND product_id = '".$product_id."' LIMIT 1");
				if(count($result)==0){
					$wpdb->insert(
						'customer_favourite', 
						array(
							'user_id' => $user_id,
							'product_id' => $product_id
						)
					);
				}
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Favourite List is Updated";			
				break;

			case "delete":
				$wpdb->delete(
					'customer_favourite', 
					array(
						'user_id'=>$user_id, 
						'product_id'=>$product_id
					)
				);
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Favourite List is Updated";
				break;

			default:
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Invalid Action";
				break;				
		}
	}
	

	if($section=="get_product_list"){
		
		$today = date("Y-m-d");
		//$stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:$today;
		$stock_date = $today;

		if($today==$stock_date){
			$isToday = true;
		} else {
			$isToday = false;
		}
		
		$arr_holiday = get_holiday_list();

		$arr_product_list = array();

		$skuList = $wpdb->get_results("SELECT * FROM stock_init WHERE show_in_app = 'Y' Order By start_date DESC, sku ASC ");		
		
		foreach($skuList as $skuSettingObj){

			$masterSku = $skuSettingObj->sku;
			//$product_id = 0;
			$arr_product_id = array();

			if(has_slave_sku($masterSku)){	
				$skus = get_salve_sku($masterSku);
				foreach($skus as $skuObj){
					$slaveSku = $skuObj->slave_sku;		
					$id = wc_get_product_id_by_sku($slaveSku);
					$arr_product_id[]=$id;
				}							
			} else {
				$id = wc_get_product_id_by_sku($masterSku);	
				$arr_product_id[]=$id;
			}

			foreach($arr_product_id as $product_id){
				
				$product_id_zh = 0;
				$trid = $sitepress->get_element_trid($product_id, 'post_product');
				$translations = $sitepress->get_element_translations($trid, 'product');
				foreach( $translations as $lang=>$translation){
					if($translation->language_code == "zh-hant")
						$product_id_zh = $translation->element_id;
				}

				$productObject = wc_get_product( $product_id );

				if($product_id_zh == 0){
					$product_id_zh = $product_id;
				}
				
				$productZHObject = wc_get_product( $product_id_zh );
				
				$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($product_id),'single-post-thumbnail');
				$arr_images = array();
				if($featured_image){
					$arr_images[] = $featured_image[0];
				}
				$images = $productObject->get_gallery_image_ids();
				foreach($images as $image) {
					$arr_images[] = wp_get_attachment_image_url( $image, 'full');
				}
				
				$stock_qty = intval(get_sku_stock_by_date($masterSku,$stock_date));			
				$unit_qty = floatval(get_master_sku_unit_qty($masterSku));	
				$limit = floor(floatval(get_sku_stock_by_date($masterSku,$stock_date))/$unit_qty);
				
				$notice = "";	
				$notice_zh = "";	
				$notice_color = "";
				//$purchasable = true;				

				if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){
					$notice = "It's holiday today";
					$notice_zh = "是日店休";	
					$notice_color = "red";
					//$purchasable = false;				
				}else{
					// 0 = discontinued; 1 = selling; 2 = coming soon
					$init_status = check_stock_init($masterSku, $stock_date);	
					if($init_status == 0) {
						$notice = "Sales Ended";
						$notice_zh = "售賣期已完結";
						$notice_color = "gray";
						//$purchasable = false;					
					} elseif($init_status == 2){
						$notice = "Coming soon";	
						$notice_zh = "即將推出";	
						$notice_color = "blue";
						//$purchasable = false;
					} elseif($init_status == 1) {
						if($stock_date==date("Y-m-d") && date('H')>=16){					
							$notice = "Sold Out ".($isToday?'Today':'');
							$notice_zh = ($isToday?'今天已':'')."售罄";
							//$purchasable = false;
							$notice_color = "red";
						}elseif($limit <= 0){
							$notice = "Sold Out ".($isToday?'Today':'');
							$notice_zh = ($isToday?'今天已':'')."售罄";
							//$purchasable = false;
							$notice_color = "red";
						}else{								
							$notice = $limit." Left";
							$notice_zh = "今天餘".$limit."份";
							$notice_color = "yellow";
						}
					}
				}				

				$sorting_info = get_product_sorting_info($masterSku, $stock_date);
				
				$arr_variations = array();
				$variations = $productObject->get_children();
				$attributes = $productObject->get_attributes();
				foreach($variations as $variation_id){
					$arr_variations[] = array("variation_id"=>$variation_id);
				}

				//$idx = 0;
				foreach ( $attributes as $attribute ) {				
					$attribute_terms = $attribute->get_terms(); // The terms
					foreach($attribute_terms as $idx=>$attributeObj){
						$arr_variations[$idx]['variation_name'] = $attributeObj->name;
						switch($attributeObj->name){
							case "4 Pieces":
								$variation_name_zh = "4片";
								break;
							case "Don't cut":
								$variation_name_zh = "不切";
								break;
							case "8 Pieces":
								$variation_name_zh = "8片";
								break;
							case "5 Pieces (23mm)":
								$variation_name_zh = "5片 (23mm)";
								break;
							default:
								$variation_name_zh = $attributeObj->name;
								break;														
						}
						$arr_variations[$idx]['variation_name_zh'] = $variation_name_zh;
						//$idx++;
					}
				}

				$total_sales_count = intval(get_post_meta($product_id,'total_sales', true));
				$sales_figure_length = strlen($total_sales_count);
				if($sales_figure_length>2){					
					$total_sales_string = floor($total_sales_count/pow(10,($sales_figure_length-1))) * pow(10,($sales_figure_length-1))."+";
				} else {
					$total_sales_string = $total_sales_count;
				}
							
				$arr_product_list[] = array(					
					"date"=>$stock_date,				
					"product_id"=>$product_id,
					"product_id_zh"=>$product_id_zh,
					"name"=>$productObject->get_name(),
					"name_zh"=>$productZHObject->get_name(),
					"sku"=>$productObject->get_sku(),					
					"short_description"=>$productObject->get_short_description(),
					"short_description_zh"=>$productZHObject->get_short_description(),
					"variations"=>$arr_variations,
					"image"=>$arr_images,
					"price"=>$productObject->get_price(),
					"unit"=>get_post_meta($product_id, '_woo_uom_input', true),
					"unit_zh"=>get_post_meta($product_id_zh, '_woo_uom_input', true)==false?"":get_post_meta($product_id_zh, '_woo_uom_input', true),
					"notice"=>$notice,
					"notice_zh"=>$notice_zh,
					"notice_color"=>$notice_color,					
					"purchasable"=>$sorting_info['sales_status'], 
					//"limit"=>$limit,				
					"sequence"=>$sorting_info['sequence'],
					"publish_date"=>get_the_date('Y-m-d', $product_id),
					"rating"=>floatval($productObject->get_average_rating()),					
					"sales_count"=>strval($total_sales_string)
				); 
			}
		} 

		
		usort($arr_product_list,function($a,$b){
			return $b['purchasable'] <=> $a['purchasable']  //first asc
				?: $a['sequence'] <=> $b['sequence']  //second asc
				?: $b['limit'] <=> $a['limit'] //third desc
				?: $b['publish_date'] <=> $a['publish_date']  //forth desc
				?: $a['name'] <=> $b['name']  //fifth asc
			;
		});

		$array_result['data'] = $arr_product_list;
		
	}	

	if($section=="product_search_list"){

		$arr_product_list = array();

		$sql = "
			SELECT a.sku, sum(b.remain) as remains, 
				CASE 
					WHEN CURDATE() >= a.start_date AND CURDATE() <= a.end_date THEN '1' 
					WHEN CURDATE() >= a.start_date AND a.end_date = '0000-00-00' THEN '2' 
					WHEN CURDATE() > a.end_date THEN '3' 
					ELSE '0' 
				END AS sequence 
			FROM stock_init a 
			LEFT JOIN sku_stock_remake b ON a.sku = b.sku AND b.stock_date in (select date from custom_selectedable_date) 
			WHERE a.show_in_app = 'Y' 
			GROUP BY a.sku ";

		$sql .= "ORDER BY remains DESC, sequence ASC, a.start_date DESC ";		

		$skuList = $wpdb->get_results($sql);	

		//echo count($skuList);
				
		foreach($skuList as $skuSettingObj){

			$masterSku = $skuSettingObj->sku;
			$arr_product_id = array();

			if(has_slave_sku($masterSku)){	
				$skus = get_salve_sku($masterSku);
				foreach($skus as $skuObj){
					$slaveSku = $skuObj->slave_sku;		
					$id = wc_get_product_id_by_sku($slaveSku);
					$arr_product_id[]=$id;
				}							
			} else {
				$id = wc_get_product_id_by_sku($masterSku);	
				$arr_product_id[]=$id;
			}

			foreach($arr_product_id as $product_id){
				$product_id_zh = 0;
				$trid = $sitepress->get_element_trid($product_id, 'post_product');
				$translations = $sitepress->get_element_translations($trid, 'product');
				foreach( $translations as $lang=>$translation){
					if($translation->language_code == "zh-hant")
						$product_id_zh = $translation->element_id;
				}

				$productObject = wc_get_product( $product_id );

				if($product_id_zh == 0){
					$product_id_zh = $product_id;
				}
				
				$productZHObject = wc_get_product( $product_id_zh );
				
				$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($product_id),'single-post-thumbnail');
				$arr_images = array();
				if($featured_image){
					$arr_images[] = $featured_image[0];
				}				
							
				$arr_product_list[] = array(										
					"product_id"=>$product_id,				
					"name"=>$productObject->get_name(),
					"name_zh"=>$productZHObject->get_name(),
					"images"=>$arr_images[0]				
				); 
				
			}
			
		} 
		
		$array_result['data'] = $arr_product_list;		

	}		
	
	if($section=="product_list_remake"){
		
		$today = date("Y-m-d");		
		$stock_date = $today;

		if($today==$stock_date){
			$isToday = true;
		} else {
			$isToday = false;
		}
		
		$arr_holiday = get_holiday_list();

		$arr_product_list = array();

		$sql = "
			SELECT a.sku, sum(b.remain) as remains, 
				CASE 
					WHEN CURDATE() >= a.start_date AND CURDATE() <= a.end_date THEN '1' 
					WHEN CURDATE() >= a.start_date AND a.end_date = '0000-00-00' THEN '2' 
					WHEN CURDATE() > a.end_date THEN '3' 
					ELSE '0' 
				END AS sequence 
			FROM stock_init a 
			LEFT JOIN sku_stock_remake b ON a.sku = b.sku AND b.stock_date in (select date from custom_selectedable_date) 
			WHERE a.show_in_app = 'Y' 
			GROUP BY a.sku ";
		/*
		if(isset($_GET['purchasable'])) {
			if($_GET['purchasable']==true){
				$sql .= "HAVING remains > 0 ";
			} else {
				$sql .= "HAVING remains <= 0 ";
			}
		} else {
			$sql .= "HAVING remains > 0 ";
		}
		*/	
					
		//$sql .= "ORDER BY a.sku ASC ";
		//$sql .= "ORDER BY sequence ASC, a.start_date DESC, remains DESC ";
		$sql .= "ORDER BY remains DESC, sequence ASC, a.start_date DESC ";
		
		$page = 1;
		if(isset($_GET['page'])) {
			if($_GET['page']!=""){
				if($_GET['page']<=0){
					$_GET['page'] = 1;
				} else {
					$page = $_GET['page'];
				} 
			}
		} 			

		$sql .= "LIMIT ".(($page-1)*6).", 6";

		$skuList = $wpdb->get_results($sql);	

		//echo count($skuList);
				
		foreach($skuList as $skuSettingObj){

			$masterSku = $skuSettingObj->sku;
			$arr_product_id = array();

			if(has_slave_sku($masterSku)){	
				$skus = get_salve_sku($masterSku);
				foreach($skus as $skuObj){
					$slaveSku = $skuObj->slave_sku;		
					$id = wc_get_product_id_by_sku($slaveSku);
					$arr_product_id[]=$id;
				}							
			} else {
				$id = wc_get_product_id_by_sku($masterSku);	
				$arr_product_id[]=$id;
			}

			foreach($arr_product_id as $product_id){
				//echo $skuSettingObj->sku."__".$product_id;
				//echo "<br>";
				$product_id_zh = 0;
				$trid = $sitepress->get_element_trid($product_id, 'post_product');
				$translations = $sitepress->get_element_translations($trid, 'product');
				foreach( $translations as $lang=>$translation){
					if($translation->language_code == "zh-hant")
						$product_id_zh = $translation->element_id;
				}

				$productObject = wc_get_product( $product_id );

				if($product_id_zh == 0){
					$product_id_zh = $product_id;
				}
				
				$productZHObject = wc_get_product( $product_id_zh );
				
				$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($product_id),'single-post-thumbnail');
				$arr_images = array();
				if($featured_image){
					$arr_images[] = $featured_image[0];
				}
				$images = $productObject->get_gallery_image_ids();
				foreach($images as $image) {
					$arr_images[] = wp_get_attachment_image_url( $image, 'full');
				}
				
				$stock_qty = intval(get_sku_stock_by_date($masterSku,$stock_date));			
				$unit_qty = floatval(get_master_sku_unit_qty($masterSku));	
				$limit = floor(floatval(get_sku_stock_by_date($masterSku,$stock_date))/$unit_qty);
				
				$notice = "";	
				$notice_zh = "";	
				$notice_color = "";
				//$purchasable = true;				

				if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){
					$notice = "It's holiday today";
					$notice_zh = "是日店休";	
					$notice_color = "red";
					//$purchasable = false;				
				}else{
					// 0 = discontinued; 1 = selling; 2 = coming soon
					$init_status = check_stock_init($masterSku, $stock_date);	
					if($init_status == 0) {
						$notice = "Sales Ended";
						$notice_zh = "售賣期已完結";
						$notice_color = "gray";
						//$purchasable = false;					
					} elseif($init_status == 2){
						$notice = "Coming soon";	
						$notice_zh = "即將推出";	
						$notice_color = "blue";
						//$purchasable = false;
					} elseif($init_status == 1) {
						if($stock_date==date("Y-m-d") && date('H')>=16){					
							$notice = "Sold Out ".($isToday?'Today':'');
							$notice_zh = ($isToday?'今天已':'')."售罄";
							//$purchasable = false;
							$notice_color = "red";
						}elseif($limit <= 0){
							$notice = "Sold Out ".($isToday?'Today':'');
							$notice_zh = ($isToday?'今天已':'')."售罄";
							//$purchasable = false;
							$notice_color = "red";
						}else{								
							$notice = $limit." Left Today";
							$notice_zh = "今天餘".$limit."份";
							$notice_color = "yellow";
						}
					}
				}				

				//$sorting_info = get_product_sorting_info($masterSku, $stock_date);
				
				$arr_variations = array();
				$variations = $productObject->get_children();
				$attributes = $productObject->get_attributes();
				foreach($variations as $variation_id){
					$arr_variations[] = array("variation_id"=>$variation_id);
				}

				//$idx = 0;
				foreach ( $attributes as $attribute ) {				
					$attribute_terms = $attribute->get_terms(); // The terms
					foreach($attribute_terms as $idx=>$attributeObj){
						$arr_variations[$idx]['variation_name'] = $attributeObj->name;
						switch($attributeObj->name){
							case "4 Pieces":
								$variation_name_zh = "4片";
								break;
							case "Don't cut":
								$variation_name_zh = "不切";
								break;
							case "8 Pieces":
								$variation_name_zh = "8片";
								break;
							case "5 Pieces (23mm)":
								$variation_name_zh = "5片 (23mm)";
								break;
							default:
								$variation_name_zh = $attributeObj->name;
								break;														
						}
						$arr_variations[$idx]['variation_name_zh'] = $variation_name_zh;
						//$idx++;
					}
				}

				$total_sales_count = intval(get_post_meta($product_id,'total_sales', true));
				$sales_figure_length = strlen($total_sales_count);
				if($sales_figure_length>2){					
					$total_sales_string = floor($total_sales_count/pow(10,($sales_figure_length-1))) * pow(10,($sales_figure_length-1))."+";
				} else {
					$total_sales_string = $total_sales_count;
				}
							
				$arr_product_list[] = array(					
					//"date"=>$stock_date, 
					"product_id"=>$product_id,				
					//"product_id_zh"=>$product_id_zh,
					"name"=>$productObject->get_name(),
					"name_zh"=>$productZHObject->get_name(),
					//"sku"=>$productObject->get_sku(),
					//"short_description"=>$productObject->get_short_description(),
					//"short_description_zh"=>$productZHObject->get_short_description(),
					//"variations"=>$arr_variations,
					"image"=>$arr_images,
					"price"=>$productObject->get_price(),
					"unit"=>get_post_meta($product_id, '_woo_uom_input', true),
					"unit_zh"=>get_post_meta($product_id_zh, '_woo_uom_input', true)==false?"":get_post_meta($product_id_zh, '_woo_uom_input', true),
					"notice"=>$notice,
					"notice_zh"=>$notice_zh,
					"notice_color"=>$notice_color,
					"purchasable"=>$skuSettingObj->remains>0?true:false,
					"sequence"=>$skuSettingObj->sequence,
					//"publish_date"=>get_the_date('Y-m-d', $product_id),
					"rating"=>floatval($productObject->get_average_rating()),
					"sales_count"=>strval($total_sales_string)		
				
				); 
				
			}
			
		} 
		/*
		usort($arr_product_list,function($a,$b){
			return $b['purchasable'] <=> $a['purchasable']  //first asc
				?: $a['sequence'] <=> $b['sequence']  //second asc
				?: $b['limit'] <=> $a['limit'] //third desc
				?: $b['publish_date'] <=> $a['publish_date']  //forth desc
				?: $a['name'] <=> $b['name']  //fifth asc
			;
		});		
		*/
		$array_result['data'] = $arr_product_list;
		
	}	

	if($section=="get_product_data"){
		
		$today = date("Y-m-d");		
		$stock_date = $today;

		if($today==$stock_date){
			$isToday = true;
		} else {
			$isToday = false;
		}
		
		$arr_holiday = get_holiday_list();

		$product_id = $_GET['product_id'];

		$productObject = wc_get_product( $product_id );

		$masterSku = get_master_sku($productObject->get_sku());

		$product_id_zh = 0;
		$trid = $sitepress->get_element_trid($product_id, 'post_product');
		$translations = $sitepress->get_element_translations($trid, 'product');
		foreach( $translations as $lang=>$translation){
			if($translation->language_code == "zh-hant")
				$product_id_zh = $translation->element_id;
		}

		if($product_id_zh == 0){
			$product_id_zh = $product_id;
		}
		
		$productZHObject = wc_get_product( $product_id_zh );
		
		$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($product_id),'single-post-thumbnail');
		$arr_images = array();
		if($featured_image){
			$arr_images[] = $featured_image[0];
		}
		$images = $productObject->get_gallery_image_ids();
		foreach($images as $image) {
			$arr_images[] = wp_get_attachment_image_url( $image, 'full');
		}
		
		$stock_qty = intval(get_sku_stock_by_date($masterSku,$stock_date));			
		$unit_qty = floatval(get_master_sku_unit_qty($masterSku));	
		$limit = floor(floatval(get_sku_stock_by_date($masterSku,$stock_date))/$unit_qty);
		
		$notice = "";	
		$notice_zh = "";	
		$notice_color = "";
		//$purchasable = true;				

		if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){
			$notice = "It's holiday today";
			$notice_zh = "是日店休";	
			$notice_color = "red";
			//$purchasable = false;				
		}else{
			// 0 = discontinued; 1 = selling; 2 = coming soon
			$init_status = check_stock_init($masterSku, $stock_date);	
			if($init_status == 0) {
				$notice = "Sales Ended";
				$notice_zh = "售賣期已完結";
				$notice_color = "gray";
				//$purchasable = false;					
			} elseif($init_status == 2){
				$notice = "Coming soon";	
				$notice_zh = "即將推出";	
				$notice_color = "blue";
				//$purchasable = false;
			} elseif($init_status == 1) {
				if($stock_date==date("Y-m-d") && date('H')>=16){					
					$notice = "Sold Out ".($isToday?'Today':'');
					$notice_zh = ($isToday?'今天已':'')."售罄";
					//$purchasable = false;
					$notice_color = "red";
				}elseif($limit <= 0){
					$notice = "Sold Out ".($isToday?'Today':'');
					$notice_zh = ($isToday?'今天已':'')."售罄";
					//$purchasable = false;
					$notice_color = "red";
				}else{								
					$notice = $limit." Left Today";
					$notice_zh = "今天餘".$limit."份";
					$notice_color = "yellow";
				}
			}
		}				

		//$sorting_info = get_product_sorting_info($masterSku, $stock_date);
		
		$arr_variations = array();
		$variations = $productObject->get_children();
		$attributes = $productObject->get_attributes();
		foreach($variations as $variation_id){
			$arr_variations[] = array("variation_id"=>$variation_id);
		}

		//$idx = 0;
		foreach ( $attributes as $attribute ) {				
			$attribute_terms = $attribute->get_terms(); // The terms
			foreach($attribute_terms as $idx=>$attributeObj){
				$arr_variations[$idx]['variation_name'] = $attributeObj->name;
				switch($attributeObj->name){
					case "4 Pieces":
						$variation_name_zh = "4片";
						break;
					case "Don't cut":
						$variation_name_zh = "不切";
						break;
					case "8 Pieces":
						$variation_name_zh = "8片";
						break;
					case "5 Pieces (23mm)":
						$variation_name_zh = "5片 (23mm)";
						break;
					default:
						$variation_name_zh = $attributeObj->name;
						break;														
				}
				$arr_variations[$idx]['variation_name_zh'] = $variation_name_zh;
				//$idx++;
			}
		}

		$total_sales_count = intval(get_post_meta($product_id,'total_sales', true));
		$sales_figure_length = strlen($total_sales_count);
		if($sales_figure_length>2){					
			$total_sales_string = floor($total_sales_count/pow(10,($sales_figure_length-1))) * pow(10,($sales_figure_length-1))."+";
		} else {
			$total_sales_string = $total_sales_count;
		}
					
		$arr_product_list = array(					
			"product_id"=>intval($product_id),
			"name"=>$productObject->get_name(),
			"name_zh"=>$productZHObject->get_name(),
			"sku"=>$productObject->get_sku(),
			"variations"=>$arr_variations,
			"images"=>$arr_images,
			"price"=>$productObject->get_price(),
			"unit"=>get_post_meta($product_id, '_woo_uom_input', true),
			"unit_zh"=>get_post_meta($product_id_zh, '_woo_uom_input', true)==false?"":get_post_meta($product_id_zh, '_woo_uom_input', true),
			"notice"=>$notice,
			"notice_zh"=>$notice_zh,
			"notice_color"=>$notice_color,
			"purchasable"=>($skuSettingObj->remains>0 && in_array($skuSettingObj->sequence, array("1","2")))?true:false,
			"sequence"=>$skuSettingObj->sequence,
			"rating"=>floatval($productObject->get_average_rating()),
			"sales_count"=>strval($total_sales_string)		
		
		); 
				
			
		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "";
		
		$array_result['data'] = $arr_product_list;
		
		
	}	
	
	if($section=="product_detail"){

		$productInfo = get_product_description($_GET['product_id']);

		if($result!==false){			
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = "";
			$array_result['data'] = $productInfo;
		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Invalid product ID";
			$array_result['data'] = null;		
		}
	}
	
	
	if($section=="product_list"){
		
		$today = date("Y-m-d");

		$stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:$today;

		if($today==$stock_date){
			$isToday = true;
		} else {
			$isToday = false;
		}
		
		$arr_holiday = get_holiday_list();

		$arr_product_list = array();

		$skuList = $wpdb->get_results("SELECT * FROM stock_init WHERE show_in_app = 'Y' Order By start_date DESC, sku ASC ");		
		
		foreach($skuList as $skuSettingObj){

			$masterSku = $skuSettingObj->sku;
			//$product_id = 0;
			$arr_product_id = array();

			if(has_slave_sku($masterSku)){	
				$skus = get_salve_sku($masterSku);
				foreach($skus as $skuObj){
					$slaveSku = $skuObj->slave_sku;		
					$id = wc_get_product_id_by_sku($slaveSku);
					$arr_product_id[]=$id;
				}							
			} else {
				$id = wc_get_product_id_by_sku($masterSku);	
				$arr_product_id[]=$id;
			}

			foreach($arr_product_id as $product_id){
				
				$product_id_zh = 0;
				$trid = $sitepress->get_element_trid($product_id, 'post_product');
				$translations = $sitepress->get_element_translations($trid, 'product');
				foreach( $translations as $lang=>$translation){
					if($translation->language_code == "zh-hant")
						$product_id_zh = $translation->element_id;
				}

				$productObject = wc_get_product( $product_id );

				if($product_id_zh == 0){
					$product_id_zh = $product_id;
				}
				
				$productZHObject = wc_get_product( $product_id_zh );

				$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($product_id),'single-post-thumbnail');
				$arr_images = array();
				if($featured_image){
					$arr_images[] = $featured_image[0];
				}
				$images = $productObject->get_gallery_image_ids();
				foreach($images as $image) {
					$arr_images[] = wp_get_attachment_image_url( $image, 'full');
				}
				
				$stock_qty = intval(get_sku_stock_by_date($masterSku,$stock_date));			
				$unit_qty = floatval(get_master_sku_unit_qty($masterSku));	
				$limit = floor(floatval(get_sku_stock_by_date($masterSku,$stock_date))/$unit_qty);
				
				$notice = "";	
				$notice_zh = "";	
				$notice_color = "";
				$purchasable = true;							
				
				if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){
					$notice = "It's holiday today";
					$notice_zh = "是日店休";	
					$notice_color = "red";
					$purchasable = false;				
				}else{
					// 0 = discontinued; 1 = selling; 2 = coming soon
					$init_status = check_stock_init($masterSku, $stock_date);	
					if($init_status == 0) {
						$notice = "Sales Ended";
						$notice_zh = "售賣期已完結";
						$notice_color = "gray";
						$purchasable = false;					
					} elseif($init_status == 2){
						$notice = "Coming soon";	
						$notice_zh = "即將推出";	
						$notice_color = "blue";
						$purchasable = false;
					} elseif($init_status == 1) {
						if($stock_date==date("Y-m-d") && date('H')>=16){					
							$notice = "Sold Out ".($isToday?'Today':'');
							$notice_zh = ($isToday?'今天已':'')."售罄";
							$purchasable = false;
							$notice_color = "red";
						}elseif($limit <= 0){
							$notice = "Sold Out ".($isToday?'Today':'');
							$notice_zh = ($isToday?'今天已':'')."售罄";
							$purchasable = false;
							$notice_color = "red";
						}else{								
							$notice = $limit." Left";
							$notice_zh = "餘".$limit."份";
							$notice_color = "yellow";
						}
					}
				}			

				$sequence = get_sequence($masterSku, $stock_date);

				
				$arr_variations = array();
				$variations = $productObject->get_children();
				$attributes = $productObject->get_attributes();
				foreach($variations as $variation_id){
					$arr_variations[] = array("variation_id"=>$variation_id);
				}

				//$idx = 0;
				foreach ( $attributes as $attribute ) {				
					$attribute_terms = $attribute->get_terms(); // The terms
					foreach($attribute_terms as $idx=>$attributeObj){
						$arr_variations[$idx]['variation_name'] = $attributeObj->name;
						switch($attributeObj->name){
							case "4 Pieces":
								$variation_name_zh = "4片";
								break;
							case "Don't cut":
								$variation_name_zh = "不切";
								break;
							case "8 Pieces":
								$variation_name_zh = "8片";
								break;
							case "5 Pieces (23mm)":
								$variation_name_zh = "5片 (23mm)";
								break;
							default:
								$variation_name_zh = $attributeObj->name;
								break;														
						}
						$arr_variations[$idx]['variation_name_zh'] = $variation_name_zh;
						//$idx++;
					}
				}

				$total_sales_count = intval(get_post_meta($product_id,'total_sales', true));
				$sales_figure_length = strlen($total_sales_count);
				if($sales_figure_length>1){					
					$total_sales_string = floor($total_sales_count/pow(10,($sales_figure_length-1))) * pow(10,($sales_figure_length-1))."+";
				} else {
					$total_sales_string = $total_sales_count;
				}				
							
				$arr_product_list[] = array(
					"date"=>$stock_date,				
					"product_id"=>$product_id,
					"product_id_zh"=>$product_id_zh,
					"name"=>$productObject->get_name(),
					"name_zh"=>$productZHObject->get_name(),
					"short_description"=>$productObject->get_short_description(),
					"short_description_zh"=>$productZHObject->get_short_description(),					
					"sku"=>$productObject->get_sku(),
					"variations"=>$arr_variations,
					"image"=>$arr_images,
					"price"=>$productObject->get_price(),
					"unit"=>get_post_meta($product_id, '_woo_uom_input', true),
					"unit_zh"=>get_post_meta($product_id_zh, '_woo_uom_input', true)==false?"":get_post_meta($product_id_zh, '_woo_uom_input', true),
					"notice"=>$notice,
					"notice_zh"=>$notice_zh,
					"notice_color"=>$notice_color,				
					"purchasable"=>$purchasable, 
					"limit"=>$limit,				
					"sequence"=>$sequence,
					"publish_date"=>get_the_date('Y-m-d', $product_id),
					"rating"=>floatval($productObject->get_average_rating()),					
					"sales_count"=> strval($total_sales_string)
				); 
			}
		}

		
		usort($arr_product_list,function($a,$b){
			return $a['sequence'] <=> $b['sequence']  //first asc
				?: $b['limit'] <=> $a['limit'] //second desc
				?: $b['publish_date'] <=> $a['publish_date']  //third desc
				?: $a['name'] <=> $b['name']  //forth asc
			;
		});

		$array_result['data'] = $arr_product_list;			
		
	}		
		
	
	if($section=="product_list_live"){
		$array_result_temp = array();
		$arr_holiday = get_holiday_list();
		$url = "https://www.breadsecret.com/wp-json/wc/v3/products?consumer_key=".API_KEY."&consumer_secret=".API_SECRET."&orderby=id&order=desc&per_page=100";

		$stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d");

		$content = file_get_contents($url);

		$api_product_data = json_decode($content, true);
		
		$today = date("Y-m-d");
		
		if($today==$stock_date){
			$isToday = true;
		} else {
			$isToday = false;
		}
		
		$array_result = array();
		
		foreach($api_product_data as $api_product){
			
			$masterSku = get_master_sku($api_product['sku']);
			$masterSkuObj = get_sku_init_info($masterSku);
			if($masterSkuObj->show_in_app == "Y"){			
			
			//if($api_product['catalog_visibility'] == "visible"){
				if($api_product['type']=="variable"){
					foreach($api_product['variations'] as $idx=>$variation_id){				
						$array_product_result = array();
						$array_product_result['id'] = intval($api_product['id']);
						
						$array_product_result['name'] = $api_product['name'];
						
						$zh_post_id = 0;
						$trid = $sitepress->get_element_trid($api_product['id'], 'post_product');
						$translations = $sitepress->get_element_translations($trid, 'product');
						foreach( $translations as $lang=>$translation){
							if($translation->language_code == "zh-hant")
								$zh_post_id = $translation->element_id;
						}
						
						$array_product_result['id_zh'] = intval($zh_post_id);
						
						$array_product_result['name_zh'] = get_the_title($zh_post_id);
						$array_product_result['short_description_zh'] = get_the_excerpt($zh_post_id);
						
						$array_product_result['create_date'] = $api_product['date_created'];
						$array_product_result['categories'] = $api_product['categories'];
						$array_product_result['status'] = $api_product['status'];
						$array_product_result['catalog_visibility'] = $api_product['catalog_visibility'];				
						$array_product_result['short_description'] = $api_product['short_description'];
						$array_product_result['sku'] = $api_product['sku'];
					
						$array_product_result['stock_date'] = $stock_date;
						
						$stock_sku = get_master_sku($api_product['sku']);
						
						$array_product_result['stock_quantity'] = intval(get_sku_stock_by_date($stock_sku,$stock_date));
						//$array_product_result['stock_quantity'] = 999;
						
						$unit_qty = get_master_sku_unit_qty($api_product['sku']);		
					
						$array_product_result['stock_sku'] = $stock_sku;
						$array_product_result['unit_qty'] = floatval($unit_qty);	
					
						//$limit = floor($array_product_result['stock_quantity']/$unit_qty);
						$limit = floor(floatval(get_sku_stock_by_date($stock_sku,$stock_date))/$unit_qty);
						//$limit = 99;		
						
						
						$array_product_result['stock_status'] = $api_product['stock_status']=="onbackorder"?"instock":$api_product['stock_status'];
						
						$notice = "";	
						$notice_zh = "";	
						
						$array_product_result['purchasable'] = true;
								
						if(in_array($stock_date,$arr_holiday) || (date('N',strtotime($stock_date))==7 && $stock_date != "2022-10-30") ){
						//if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){
							$notice = "It's holiday today";
							$notice_zh = "是日店休";	
							$array_product_result['purchasable'] = true;
							$array_product_result['color'] = "red";
						}else{
							// 0 = discontinued; 1 = selling; 2 = coming soon
							$init_status = check_stock_init($stock_sku, $stock_date);	
							if($init_status == 0) {
								$notice = "Sales Ended";	
								$notice_zh = "售賣期已完結";	
								//$array_product_result['purchasable'] = false;
								$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "gray";
							} elseif($init_status == 2){
								$notice = "Coming soon";	
								$notice_zh = "即將推出";	
								//$array_product_result['purchasable'] = false;
								$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "blue";
							} elseif($init_status == 1) {
								if($stock_date==date("Y-m-d") && date('H')>=16){					
									$notice = "Sold Out ".($isToday?'Today':'');
									$notice_zh = ($isToday?'今天已':'')."售罄";
									//$array_product_result['purchasable'] = false;
									$array_product_result['purchasable'] = true;
									$array_product_result['color'] = "red";
								}elseif($limit <= 0){
									$notice = "Sold Out ".($isToday?'Today':'');
									$notice_zh = ($isToday?'今天已':'')."售罄";
									//$array_product_result['purchasable'] = false;
									$array_product_result['purchasable'] = true;
									$array_product_result['color'] = "red";
								}else{								
									$notice = $limit." Left";
									$notice_zh = "餘".$limit."份";
									$array_product_result['color'] = "yellow";
								}/*else{
									$notice = "In Stock";
									$notice_zh = "有貨";	
									$array_product_result['color'] = "green";								
								}*/
							}
						}
						
						$array_product_result['notice'] = $notice;	
						$array_product_result['notice_zh'] = $notice_zh;							
						$array_product_result['price'] = $api_product['price'];		
						$array_product_result['unit'] = get_post_meta($api_product['id'], '_woo_uom_input', true);	
						$array_product_result['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true)==false?"":get_post_meta($zh_post_id, '_woo_uom_input', true);						
						//$array_product_result['variations'] = $api_product['variations'];	
						//$array_product_result['attributes'] = $api_product['attributes'];	
						$array_product_result['variations'] = $variation_id;	
						$array_product_result['attributes'] = $api_product['attributes'][0]['options'][$idx];							
						$array_product_result['images'] = $api_product['images'];						
						//$array_product_result['stock_status'] = $api_product['stock_status'];
						$array_product_result['publish_date'] = get_the_date('Y-m-d', $api_product['id']);		
						$array_product_result['sequence'] = get_sequence($stock_sku, $stock_date);
						$array_product_result['hasStock'] = ($limit>0)?((date("Y-m-d") == $stock_date && date("H")>=16)?"0":"1"):"0";
						$array_product_result['limit'] = $limit;
						//$array_product_result['limit'] = 999;
						
						array_push($array_result_temp, $array_product_result);
					} // end foreach
				} else { // simple product
					$array_product_result = array();
					$array_product_result['id'] = intval($api_product['id']);
					$array_product_result['name'] = $api_product['name'];
					$zh_post_id = 0;
					$trid = $sitepress->get_element_trid($api_product['id'], 'post_product');
					$translations = $sitepress->get_element_translations($trid, 'product');
					foreach( $translations as $lang=>$translation){
						if($translation->language_code == "zh-hant")
							$zh_post_id = $translation->element_id;
					}
					$array_product_result['id_zh'] = intval($zh_post_id);
					$array_product_result['name_zh'] = get_the_title($zh_post_id);
					$array_product_result['short_description_zh'] = get_the_excerpt($zh_post_id);					
					$array_product_result['create_date'] = $api_product['date_created'];
					$array_product_result['categories'] = $api_product['categories'];
					$array_product_result['status'] = $api_product['status'];
					$array_product_result['catalog_visibility'] = $api_product['catalog_visibility'];				
					$array_product_result['short_description'] = $api_product['short_description'];
					$array_product_result['sku'] = $api_product['sku'];
				
					$array_product_result['stock_date'] = $stock_date;
					
					$stock_sku = get_master_sku($api_product['sku']);
					
					//$array_product_result['stock_quantity'] = 999;
					$array_product_result['stock_quantity'] = intval(get_sku_stock_by_date($stock_sku,$stock_date));
					
					$unit_qty = get_master_sku_unit_qty($api_product['sku']);		
				
					$array_product_result['stock_sku'] = $stock_sku;
					$array_product_result['unit_qty'] = floatval($unit_qty);	
				
					//$limit = floor($array_product_result['stock_quantity']/$unit_qty);
					$limit = floor(floatval(get_sku_stock_by_date($stock_sku,$stock_date))/$unit_qty);
					//$limit = 99;

					
					$array_product_result['stock_status'] = $api_product['stock_status']=="onbackorder"?"instock":$api_product['stock_status'];
					
					$notice = "";	
					$notice_zh = "";	
					
					$array_product_result['purchasable'] = true;
							
					if(in_array($stock_date,$arr_holiday) || (date('N',strtotime($stock_date))==7 && $stock_date != "2022-10-30") ){
					//if(in_array($stock_date,$arr_holiday) || date('N',strtotime($stock_date))==7){
						$notice = "It's holiday today";
						$notice_zh = "是日店休";	
						$array_product_result['purchasable'] = true;
						$array_product_result['color'] = "red";
					}else{
						// 0 = discontinued; 1 = selling; 2 = coming soon
						$init_status = check_stock_init($stock_sku, $stock_date);	
						if($init_status == 0) {
							$notice = "Sales Ended";	
							$notice_zh = "售賣期已完結";	
							//$array_product_result['purchasable'] = false;
							$array_product_result['purchasable'] = true;
							$array_product_result['color'] = "gray";
						} elseif($init_status == 2){
							$notice = "Coming soon";	
							$notice_zh = "即將推出";	
							//$array_product_result['purchasable'] = false;
							$array_product_result['purchasable'] = true;
							$array_product_result['color'] = "blue";
						} elseif($init_status == 1) {
							if($stock_date==date("Y-m-d") && date('H')>=16){					
								$notice = "Sold Out ".($isToday?'Today':'');
								$notice_zh = ($isToday?'今天已':'')."售罄";
								//$array_product_result['purchasable'] = false;
								$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "red";
							}elseif($limit <= 0){
								$notice = "Sold Out ".($isToday?'Today':'');
								$notice_zh = ($isToday?'今天已':'')."售罄";
								//$array_product_result['purchasable'] = false;
								$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "red";
							}else{								
								$notice = $limit." Left";
								$notice_zh = "餘".$limit."份";
								$array_product_result['color'] = "yellow";
							}/*else{
								$notice = "In Stock";
								$notice_zh = "有貨";		
								$array_product_result['color'] = "green";							
							}*/
						}
					}
					$array_product_result['notice'] = $notice;	
					$array_product_result['notice_zh'] = $notice_zh;						
					$array_product_result['price'] = $api_product['price'];		
					$array_product_result['unit'] = get_post_meta($api_product['id'], '_woo_uom_input', true);		
					$array_product_result['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true)==false?"":get_post_meta($zh_post_id, '_woo_uom_input', true);															
					$array_product_result['variations'] = 0;
					$array_product_result['attributes'] = "";
					$array_product_result['images'] = $api_product['images'];
					$array_product_result['publish_date'] = get_the_date('Y-m-d', $api_product['id']);		
					$array_product_result['sequence'] = get_sequence($stock_sku, $stock_date);
					$array_product_result['hasStock'] = ($limit>0)?((date("Y-m-d") == $stock_date && date("H")>=16)?"0":"1"):"0";					
					$array_product_result['limit'] = $limit;
					//$array_product_result['stock_status'] = $api_product['stock_status'];
					
					array_push($array_result_temp, $array_product_result);					
					
				}
			} //end if
		} // end foreach
			
		usort($array_result_temp,function($a,$b){
		  return $a['sequence'] <=> $b['sequence']  //first asc
			  ?: $b['hasStock'] <=> $a['hasStock'] //second desc
			  ?: $b['publish_date'] <=> $a['publish_date']  //third desc
			  ?: $a['name'] <=> $b['name']  //forth asc
		  ;
		});	

		$array_result['data'] = $array_result_temp;
	}

	if($section=="product_list_home"){
		$array_result_temp = array();
		$arr_holiday = get_holiday_list();
		$url = "https://www.breadsecret.com/wp-json/wc/v3/products?consumer_key=".API_KEY."&consumer_secret=".API_SECRET."&orderby=id&order=desc&per_page=100";

		$stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d");

		$content = file_get_contents($url);

		$api_product_data = json_decode($content, true);
		
		$today = date("Y-m-d");
		
		if($today==$stock_date){
			$isToday = true;
		} else {
			$isToday = false;
		}
		
		$array_result = array();
		
		foreach($api_product_data as $api_product){
			
			$masterSku = get_master_sku($api_product['sku']);
			$masterSkuObj = get_sku_init_info($masterSku);
			if($masterSkuObj->show_in_app == "Y"){			
			
			//if($api_product['catalog_visibility'] == "visible"){
				if($api_product['type']=="variable"){
					foreach($api_product['variations'] as $idx=>$variation_id){				
						$array_product_result = array();
						$array_product_result['id'] = intval($api_product['id']);
						
						$array_product_result['name'] = $api_product['name'];
						
						$zh_post_id = 0;
						$trid = $sitepress->get_element_trid($api_product['id'], 'post_product');
						$translations = $sitepress->get_element_translations($trid, 'product');
						foreach( $translations as $lang=>$translation){
							if($translation->language_code == "zh-hant")
								$zh_post_id = $translation->element_id;
						}
						
						$array_product_result['id_zh'] = intval($zh_post_id);
						
						$array_product_result['name_zh'] = get_the_title($zh_post_id);
						//$array_product_result['short_description_zh'] = get_the_excerpt($zh_post_id);
						
						//$array_product_result['create_date'] = $api_product['date_created'];
						//$array_product_result['categories'] = $api_product['categories'];
						//$array_product_result['status'] = $api_product['status'];
						//$array_product_result['catalog_visibility'] = $api_product['catalog_visibility'];				
						//$array_product_result['short_description'] = $api_product['short_description'];
						//$array_product_result['sku'] = $api_product['sku'];
					
						//$array_product_result['stock_date'] = $stock_date;
						
						$stock_sku = get_master_sku($api_product['sku']);
												
						//$array_product_result['stock_quantity'] = 999;
						
						$unit_qty = get_master_sku_unit_qty($api_product['sku']);		
					
						//$array_product_result['stock_sku'] = $stock_sku;
						//$array_product_result['unit_qty'] = floatval($unit_qty);	
											
						$limit = floor(floatval(get_sku_stock_by_date($stock_sku,$stock_date))/$unit_qty);						
						
						//$array_product_result['stock_status'] = $api_product['stock_status']=="onbackorder"?"instock":$api_product['stock_status'];
						
						$notice = "";	
						$notice_zh = "";	
						
						//$array_product_result['purchasable'] = true;
								
						if(in_array($stock_date,$arr_holiday) || (date('N',strtotime($stock_date))==7 && $stock_date != "2022-10-30") ){						
							$notice = "It's holiday today";
							$notice_zh = "是日店休";	
							//$array_product_result['purchasable'] = true;
							$array_product_result['color'] = "red";
						}else{
							// 0 = discontinued; 1 = selling; 2 = coming soon
							$init_status = check_stock_init($stock_sku, $stock_date);	
							if($init_status == 0) {
								$notice = "Sales Ended";	
								$notice_zh = "售賣期已完結";
								//$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "gray";
							} elseif($init_status == 2){
								$notice = "Coming soon";	
								$notice_zh = "即將推出";									
								//$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "blue";
							} elseif($init_status == 1) {
								if($stock_date==date("Y-m-d") && date('H')>=16){					
									$notice = "Sold Out ".($isToday?'Today':'');
									$notice_zh = ($isToday?'今天已':'')."售罄";									
									//$array_product_result['purchasable'] = true;
									$array_product_result['color'] = "red";
								}elseif($limit <= 0){
									$notice = "Sold Out ".($isToday?'Today':'');
									$notice_zh = ($isToday?'今天已':'')."售罄";
									//$array_product_result['purchasable'] = true;
									$array_product_result['color'] = "red";
								}else{								
									$notice = $limit." Left";
									$notice_zh = "餘".$limit."份";
									$array_product_result['color'] = "yellow";
								}
							}
						}
						
						$array_product_result['notice'] = $notice;	
						$array_product_result['notice_zh'] = $notice_zh;							
						$array_product_result['price'] = $api_product['price'];		
						$array_product_result['unit'] = get_post_meta($api_product['id'], '_woo_uom_input', true);	
						$array_product_result['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true)==false?"":get_post_meta($zh_post_id, '_woo_uom_input', true);						
						
						//$array_product_result['variations'] = $variation_id;	
						//$array_product_result['attributes'] = $api_product['attributes'][0]['options'][$idx];							
						$array_product_result['images'] = ($api_product['images'][0]['src']=="")?"":$api_product['images'][0]['src'];
						
						$array_product_result['publish_date'] = get_the_date('Y-m-d', $api_product['id']);		
						$array_product_result['sequence'] = get_sequence($stock_sku, $stock_date);
						$array_product_result['hasStock'] = ($limit>0)?((date("Y-m-d") == $stock_date && date("H")>=16)?"0":"1"):"0";
						$array_product_result['limit'] = $limit;
						
						array_push($array_result_temp, $array_product_result);
					} // end foreach
				} else { // simple product
					$array_product_result = array();
					$array_product_result['id'] = intval($api_product['id']);
					$array_product_result['name'] = $api_product['name'];
					$zh_post_id = 0;
					$trid = $sitepress->get_element_trid($api_product['id'], 'post_product');
					$translations = $sitepress->get_element_translations($trid, 'product');
					foreach( $translations as $lang=>$translation){
						if($translation->language_code == "zh-hant")
							$zh_post_id = $translation->element_id;
					}
					$array_product_result['id_zh'] = intval($zh_post_id);
					$array_product_result['name_zh'] = get_the_title($zh_post_id);
					//$array_product_result['short_description_zh'] = get_the_excerpt($zh_post_id);					
					//$array_product_result['create_date'] = $api_product['date_created'];
					//$array_product_result['categories'] = $api_product['categories'];
					//$array_product_result['status'] = $api_product['status'];
					//$array_product_result['catalog_visibility'] = $api_product['catalog_visibility'];				
					//$array_product_result['short_description'] = $api_product['short_description'];
					//$array_product_result['sku'] = $api_product['sku'];
				
					//$array_product_result['stock_date'] = $stock_date;
					
					$stock_sku = get_master_sku($api_product['sku']);
					
					//$array_product_result['stock_quantity'] = 999;
					//$array_product_result['stock_quantity'] = intval(get_sku_stock_by_date($stock_sku,$stock_date));
					
					$unit_qty = get_master_sku_unit_qty($api_product['sku']);		
				
					//$array_product_result['stock_sku'] = $stock_sku;
					//$array_product_result['unit_qty'] = floatval($unit_qty);	
									
					$limit = floor(floatval(get_sku_stock_by_date($stock_sku,$stock_date))/$unit_qty);					
					
					//$array_product_result['stock_status'] = $api_product['stock_status']=="onbackorder"?"instock":$api_product['stock_status'];
					
					$notice = "";	
					$notice_zh = "";	
					
					//$array_product_result['purchasable'] = true;
							
					if(in_array($stock_date,$arr_holiday) || (date('N',strtotime($stock_date))==7 && $stock_date != "2022-10-30") ){
						$notice = "It's holiday today";
						$notice_zh = "是日店休";	
						//$array_product_result['purchasable'] = true;
						$array_product_result['color'] = "red";
					}else{
						// 0 = discontinued; 1 = selling; 2 = coming soon
						$init_status = check_stock_init($stock_sku, $stock_date);	
						if($init_status == 0) {
							$notice = "Sales Ended";	
							$notice_zh = "售賣期已完結";								
							//$array_product_result['purchasable'] = true;
							$array_product_result['color'] = "gray";
						} elseif($init_status == 2){
							$notice = "Coming soon";	
							$notice_zh = "即將推出";								
							//$array_product_result['purchasable'] = true;
							$array_product_result['color'] = "blue";
						} elseif($init_status == 1) {
							if($stock_date==date("Y-m-d") && date('H')>=16){					
								$notice = "Sold Out ".($isToday?'Today':'');
								$notice_zh = ($isToday?'今天已':'')."售罄";
								//$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "red";
							}elseif($limit <= 0){
								$notice = "Sold Out ".($isToday?'Today':'');
								$notice_zh = ($isToday?'今天已':'')."售罄";
								//$array_product_result['purchasable'] = true;
								$array_product_result['color'] = "red";
							}else{								
								$notice = $limit." Left";
								$notice_zh = "餘".$limit."份";
								$array_product_result['color'] = "yellow";
							}
						}
					}
					$array_product_result['notice'] = $notice;	
					$array_product_result['notice_zh'] = $notice_zh;						
					$array_product_result['price'] = $api_product['price'];		
					$array_product_result['unit'] = get_post_meta($api_product['id'], '_woo_uom_input', true);		
					$array_product_result['unit_zh'] = get_post_meta($zh_post_id, '_woo_uom_input', true)==false?"":get_post_meta($zh_post_id, '_woo_uom_input', true);															
					//$array_product_result['variations'] = 0;
					//$array_product_result['attributes'] = "";
					$array_product_result['images'] = ($api_product['images'][0]['src']=="")?"":$api_product['images'][0]['src'];
					$array_product_result['publish_date'] = get_the_date('Y-m-d', $api_product['id']);		
					$array_product_result['sequence'] = get_sequence($stock_sku, $stock_date);
					$array_product_result['hasStock'] = ($limit>0)?((date("Y-m-d") == $stock_date && date("H")>=16)?"0":"1"):"0";					
					$array_product_result['limit'] = $limit;
					
					array_push($array_result_temp, $array_product_result);					
					
				}
			} //end if
		} // end foreach
			
		usort($array_result_temp,function($a,$b){
		  return $a['sequence'] <=> $b['sequence']  //first asc
			  ?: $b['hasStock'] <=> $a['hasStock'] //second desc
			  ?: $b['publish_date'] <=> $a['publish_date']  //third desc
			  ?: $a['name'] <=> $b['name']  //forth asc
		  ;
		});	

		//$array_result_temp = array_slice($array_result_temp,0,10);

		$array_result['data']=$array_result_temp;
		
		
		
	}


	
	if($section=="get_payment_method_list") {
		
		$array_result = array(array('name'=>''));		
		foreach(get_customer_payment_method_list() as $payment_method){
			$arr = array();
			$arr['name'] = $payment_method;
			array_push($array_result, $arr);
		}	
	}
	
	
	if($section=="get_payment_terms_list") {
		$array_result = array(array('name'=>''));		
		foreach(get_customer_payment_terms_list() as $payment_terms){
			$arr = array();
			$arr['name'] = $payment_terms;
			array_push($array_result, $arr);
		}	
	}	
			
	if($section=="check_app_version") {
		 $array_result = array();
		 $app_version = $wpdb->get_results("SELECT * FROM custom_value WHERE field_name = 'app_version' and status = 1 LIMIT 1 ");		
		
		 $a = $_GET['version'];
		 $b = $app_version[0]->field_value;
		 
		 $arr_a = explode(".",$a);
		 $arr_b = explode(".",$b);
		
		 $str_a = "";
		 $str_b = "";
		
		 foreach($arr_a as $digita) {
	 		 $str_a .= sprintf("%03d", $digita);
		 }
		
		 foreach($arr_b as $digitb) {
			 $str_b .= sprintf("%03d", $digitb);
		 }
		 
		 if($str_a >= $str_b) {
			 $array_result['success'] = true;
		 } else {
			 $array_result['success'] = false;			 
		 }		
	}			
	/*
	if($section=="get_customer_list"){
		$array_result = array();
		
		foreach(get_users() as $user){
			$customer = new WC_Customer( $user->ID );
			$arr_user = array();	
			$arr_user['customerID'] = $user->ID;
			$arr_user['firstName'] = $customer->get_shipping_first_name()==""?($customer->get_billing_first_name()==""?($customer->get_first_name()==""?$customer->get_display_name():$customer->get_first_name()):$customer->get_billing_first_name()):$customer->get_shipping_first_name();
			$arr_user['lastName'] = $customer->get_shipping_last_name()==""?($customer->get_billing_last_name()==""?$customer->get_last_name():$customer->get_billing_last_name()):$customer->get_shipping_last_name();
			$arr_user['email'] = $customer->get_billing_email()==""?$customer->get_email():$customer->get_billing_email();				
			$arr_user['phone'] = $customer->get_billing_phone();			
			$arr_user['state'] = $customer->get_shipping_state()==""?$customer->get_billing_state():$customer->get_shipping_state();			
			$arr_user['address'] = $customer->get_shipping_address_1()==""?$customer->get_billing_address_1():$customer->get_shipping_address_1();	
			$arr_user['company'] = $customer->get_shipping_company()==""?$customer->get_billing_company():$customer->get_shipping_company();			
			array_push($array_result, $arr_user);
			
		}
	}
	*/
	
	if($section=="customer_list"){
		$array_result = array();

		$countries = new WC_Countries();
		$country_states = $countries->get_states('HK');		
		
		foreach(get_users() as $user){
			$customer = new WC_Customer( $user->ID );
			
			
			$arr_user = array();	
			$arr_user['customerID'] = $user->ID;			
			$arr_user['firstName'] = $customer->get_first_name();
			$arr_user['lastName'] = $customer->get_last_name();
			$arr_user['email'] = $customer->get_email();
			
			$arr_billing = array();
			$arr_billing['first_name'] = $customer->get_billing_first_name();
			$arr_billing['last_name'] = $customer->get_billing_last_name();
			$arr_billing['company'] = $customer->get_billing_company();						
			$arr_billing['address_1'] = $customer->get_billing_address_1();			
			$arr_billing['address_2'] = $customer->get_billing_address_2();
			$arr_billing['city'] = $customer->get_billing_city();
			$arr_billing['state'] = $customer->get_billing_state();			
			$arr_billing['postcode'] = $customer->get_billing_postcode();
			$arr_billing['country'] = $customer->get_billing_country();
			$arr_billing['email'] = $customer->get_billing_email();
			$arr_billing['phone'] = $customer->get_billing_phone();
			$arr_user['billing_address'] = $arr_billing;
			
			$arr_shipping = array();
			$arr_shipping['first_name'] = $customer->get_shipping_first_name();
			$arr_shipping['last_name'] = $customer->get_shipping_last_name();
			$arr_shipping['company'] = $customer->get_shipping_company();						
			$arr_shipping['address_1'] = $customer->get_shipping_address_1();			
			$arr_shipping['address_2'] = $customer->get_shipping_address_2();
			$arr_shipping['city'] = $customer->get_shipping_city();
			$arr_shipping['state'] = $customer->get_shipping_state();			
			$arr_shipping['postcode'] = $customer->get_shipping_postcode();
			$arr_shipping['country'] = $customer->get_shipping_country();
			$arr_shipping['district'] = trim($country_states[$customer->get_shipping_state()]);
			$arr_user['shipping_address'] = $arr_shipping;			
			
			array_push($array_result, $arr_user);
			
		}
	}		
		
	// no longer used 
	if($section=="daily_sku_stock") { 
		$array_result = array();
		$stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d");		
		
		$stockRecord = $wpdb->get_results("SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 ");		
		
		foreach($stockRecord as $dataObj){
			$dataArr = (Array)$dataObj;
			
			//loop all column name in the stock table (except id and stock date), in order to get the sku# automatically
			$skuList = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date')" );
			
			foreach($skuList as $skuObj){			
				//create product object from sku#
				$arr_sku = array(); 
				
				if(check_stock_init($skuObj->Field, $dataArr['stock_date'])){ //check if sku is already discontinued
					
					$product = wc_get_product(wc_get_product_id_by_sku($skuObj->Field));
					$arr_sku['product_id'] = $product->get_id();
					$arr_sku['sku'] = $skuObj->Field;
					$arr_sku['name'] = $product->get_name();
					
					$zh_post_id = 0;
					
					$trid = $sitepress->get_element_trid($product->get_id(), 'post_product');
					
					$translations = $sitepress->get_element_translations($trid, 'product');
					foreach( $translations as $lang=>$translation){
						if($translation->language_code == "zh-hant")
							$zh_post_id = $translation->element_id;
					}			
					$arr_sku['name_zh'] = get_the_title($zh_post_id);
					
					$arr_sku['remain'] = floatval($dataArr[$skuObj->Field]);
					$arr_sku['production'] = get_production_qty($skuObj->Field, $dataArr['stock_date']);
					$arr_sku['stock_date'] = $dataArr['stock_date'];
					array_push($array_result, $arr_sku);
				}
			}
		}	
		
		usort($array_result,function($a,$b){
		  return $a['name'] <=> $b['name'];
		});			
	}

	if($section=="sku_stock_test") {		
		$array_result = array();
		$stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d");		
		$arrSkuList = array();
		$stockRecord = $wpdb->get_results("SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 ");		
		
		foreach($stockRecord as $dataObj){
			$dataArr = (Array)$dataObj;
			
			//loop all column name in the stock table (except id and stock date), in order to get the sku# automatically
			$skuList = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date','stock_dayofweek')" );
			
			foreach($skuList as $skuObj){				
				//create product object from sku#
				$arr_sku = array(); 			
				
				$product_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $skuObj->Field) );
				if ( $product_check ) {					
					if(check_stock_init($skuObj->Field, $dataArr['stock_date'])){ //check if sku is already discontinued	
						//array_push($arrSkuList, $skuObj->Field);
						$arrSkuList[$skuObj->Field] = true;
					} else {					
						$product = wc_get_product(wc_get_product_id_by_sku($skuObj->Field));					
						$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
						$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['stock_date']."'");						
						foreach ($result as $order_obj ){
							$order = wc_get_order( $order_obj->ID );
							foreach ( $order->get_items() as $item ) {							
								if($item->get_product()->get_sku() == $product->get_sku()) {
									//array_push($arrSkuList, $product->get_sku());
									$arrSkuList[$skuObj->Field] = false;
								}
							}
						}
					}
				}
			}
		}	
				
		foreach($arrSkuList as $productSKU=>$editable){
			$product = wc_get_product(wc_get_product_id_by_sku($productSKU));
			$arr_sku['product_id'] = $product->get_id();
			$arr_sku['sku'] = $productSKU;
			$arr_sku['name'] = $product->get_name();
			
			$zh_post_id = 0;
			
			$trid = $sitepress->get_element_trid($product->get_id(), 'post_product');
			
			$translations = $sitepress->get_element_translations($trid, 'product');
			foreach( $translations as $lang=>$translation){
				if($translation->language_code == "zh-hant")
					$zh_post_id = $translation->element_id;
			}			
			$arr_sku['name_zh'] = get_the_title($zh_post_id);
			
			$checkStock = $wpdb->get_results("SELECT `".$productSKU."` FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 ");	
			$stockObj = $checkStock[0];
			
			$arr_sku['remain'] = floatval($stockObj->$productSKU);
			$arr_sku['production'] = get_production_qty($productSKU, $_GET['stock_date']);
			$arr_sku['stock_date'] = $_GET['stock_date'];
			$arr_sku['editable'] = $editable;
			array_push($array_result, $arr_sku);
		}
		
		
		
		
		usort($array_result,function($a,$b){
		  return $a['name'] <=> $b['name'];
		});			
	}
	
	
	if($section=="sku_stock") {		
		$array_result = array();
		$stock_date = isset($_GET['stock_date']) && $_GET['stock_date']!=""?$_GET['stock_date']:date("Y-m-d");		
		$arrSkuList = array();
		$stockRecord = $wpdb->get_results("SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 ");		
		$holiday_list = get_holiday_list();
		foreach($stockRecord as $dataObj){
			$dataArr = (Array)$dataObj;
			
			//loop all column name in the stock table (except id and stock date), in order to get the sku# automatically
			$skuList = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date','stock_dayofweek')" );
			
			foreach($skuList as $skuObj){				
			
				
				//create product object from sku#
				$arr_sku = array(); 			
				
				$product_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $skuObj->Field) );
				//if ( $product_check ) {
					$status_checks = check_stock_init($skuObj->Field, $dataArr['stock_date']);				
					if($status_checks>0){ //check if sku is in sales period or coming soon
						//array_push($arrSkuList, $skuObj->Field);
						if($status_checks==1) {
							$arrSkuList[$skuObj->Field] = true;
							
							$skuObjs = get_sku_init_info($skuObj->Field);

							$arr_block_dates = array_map("trim", explode(",", $skuObjs->block_date_from_holiday));
													
							// check block days from holiday
							foreach($holiday_list as $holiday) {
								foreach($arr_block_dates as $buffer){
									if($stock_date == date("Y-m-d",strtotime($buffer." days",strtotime($holiday)))){
										$arrSkuList[$skuObj->Field] = false;
									}
								}
							}
							

							$stock_dayofweek = date('N', strtotime($dataArr['stock_date']));
							if($arrSkuList[$skuObj->Field]==true){ // check block date
								$arr_block_dayofweeks = array_map("trim", explode(",", $skuObjs->block_dayofweek));
								if(in_array($stock_dayofweek, $arr_block_dayofweeks)) { // check block dayofweek
									$arrSkuList[$skuObj->Field] = false;
								}
							}


						} else {
							$arrSkuList[$skuObj->Field] = false;
						}

					} else { // add other sku that has order
						$product = wc_get_product(wc_get_product_id_by_sku($skuObj->Field));											
						$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );						
						if(has_slave_sku($skuObj->Field)){							
							
							$arr_slave_sku = array();
							foreach(get_salve_sku($skuObj->Field) as $salveSkuObject){
								array_push($arr_slave_sku,$salveSkuObject->slave_sku);								
							}	
							
							$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['stock_date']."'");						
							foreach ($result as $order_obj ){
								$order = wc_get_order( $order_obj->ID );
								foreach ( $order->get_items() as $item ) {							
									/*
									if($item->get_product()->get_sku() == $product->get_sku()) {
										//array_push($arrSkuList, $product->get_sku());
										$arrSkuList[$skuObj->Field] = false;
									}
									*/
									if(in_array($item->get_product()->get_sku(),$arr_slave_sku)){
										$arrSkuList[$skuObj->Field] = false;
									}
								}
							}														
						} else {
							$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['stock_date']."'");						
							foreach ($result as $order_obj ){
								$order = wc_get_order( $order_obj->ID );
								foreach ( $order->get_items() as $item ) {							
									if($item->get_product()->get_sku() == $product->get_sku()) {
										//array_push($arrSkuList, $product->get_sku());
										$arrSkuList[$skuObj->Field] = false;
									}
								}
							}		
						}
						/*

						$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['stock_date']."'");						
						foreach ($result as $order_obj ){
							$order = wc_get_order( $order_obj->ID );
							foreach ( $order->get_items() as $item ) {							
								if($item->get_product()->get_sku() == $product->get_sku()) {
									//array_push($arrSkuList, $product->get_sku());
									$arrSkuList[$skuObj->Field] = false;
								}
							}
						}
						
						*/
						
					}
				//}
			}
		}	
		
			
		foreach($arrSkuList as $productSKU=>$editable){
			$product = wc_get_product(wc_get_product_id_by_sku($productSKU));
			$arr_sku['product_id'] = $product->get_id();
			$arr_sku['sku'] = $productSKU;
			$arr_sku['name'] = $product->get_name();
			
			$zh_post_id = 0;
			
			$trid = $sitepress->get_element_trid($product->get_id(), 'post_product');
			
			$translations = $sitepress->get_element_translations($trid, 'product');
			foreach( $translations as $lang=>$translation){
				if($translation->language_code == "zh-hant")
					$zh_post_id = $translation->element_id;
			}			
			$arr_sku['name_zh'] = get_the_title($zh_post_id);
			
			$checkStock = $wpdb->get_results("SELECT `".$productSKU."` FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 ");	
			$stockObj = $checkStock[0];
			
			$arr_sku['remain'] = floatval($stockObj->$productSKU);
			$arr_sku['production'] = get_production_qty($productSKU, $_GET['stock_date']);
			$arr_sku['stock_date'] = $_GET['stock_date'];
			$arr_sku['editable'] = $editable;
			//$arr_sku['init'] = check_stock_init( $productSKU, $stock_date);
			array_push($array_result, $arr_sku);
		}
		
		
		
		
		usort($array_result,function($a,$b){
		  return $b['editable'] <=> $a['editable'] ?: $b['name'] <=> $a['editable'];

		});	
			
	}	
	
	if($section=="update_sku_stock") {
		global $wpdb;			
		if($param['stock_date']==""){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";
			$array_result['message'] = "Stock Date is Missing!";
			$array_result['sku'] = $param['sku'];
			$array_result['stockDate'] = $param['stock_date'];
			$array_result['qty'] = floatval($param['qty']);
		} elseif($param['sku']=="") {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";
			$array_result['message'] = "SKU is Missing!";
			$array_result['sku'] = $param['sku'];
			$array_result['stockDate'] = $param['stock_date'];
			$array_result['qty'] = floatval($param['qty']);		
			
		} elseif($param['qty']==""){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";
			$array_result['message'] = "Qty is Missing!";
			$array_result['sku'] = $param['sku'];
			$array_result['stockDate'] = $param['stock_date'];
			$array_result['qty'] = floatval($param['qty']);		
		} else {
			$sql = "SELECT * FROM sku_stock WHERE stock_date = '".$param['stock_date']."' LIMIT 1";
			$result = $wpdb->get_results($sql);
			$data = (array)$result[0];
			$oqty = floatval($data[$param['sku']]);
						
			if($wpdb->update('sku_stock', array( $param['sku'] => $param['qty']),array('stock_date'=>$param['stock_date']))){

				$product = wc_get_product(wc_get_product_id_by_sku($param['sku']));
				$sql_statement = "UPDATE sku_stock SET `".$param['sku']."` = '".$param['qty']."' WHERE stock_date = '".$param['stock_date']."' LIMIT 1";
				write_log($param['stock_date'], "Adjust Stock", "Back End (Mobile)", "0", $param['sku'], esc_sql($product->get_name()), $oqty, $param['qty'], $param['user_id'], get_client_ip(), $sql_statement);		
				
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Stock Updated";
				$array_result['sku'] = $param['sku'];
				$array_result['stockDate'] = $param['stock_date'];
				$array_result['qty'] = floatval($param['qty']);				
			}else{
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] = "Fail to write data";
				$array_result['sku'] = $param['sku'];
				$array_result['stockDate'] = $param['stock_date'];
				$array_result['qty'] = floatval($param['qty']);	
			}
		}		
	}
	
	
	if($section=="adjust_sku_stock") {
		global $wpdb;		
		
	    //echo str_replace('\"', '"', $_POST['content_data']);
		
		
		$content = json_decode(stripslashes($_POST['content_data']), true);

		foreach($content as $arrContent){
			//echo $arrContent['stock_date']." - ".$arrContent['sku']." - ".$arrContent['qty'];
			//echo "<br>";
			$sql = "SELECT * FROM sku_stock WHERE stock_date = '".$arrContent['stock_date']."' LIMIT 1";
			$result = $wpdb->get_results($sql);
			$data = (array)$result[0];
			$oqty = floatval($data[$arrContent['sku']]);
			
			
			if($wpdb->update('sku_stock', array( $arrContent['sku'] => $arrContent['qty']),array('stock_date'=>$arrContent['stock_date']))){
				$product = wc_get_product(wc_get_product_id_by_sku($arrContent['sku']));
				$sql_statement = "UPDATE sku_stock SET `".$arrContent['sku']."` = '".$arrContent['qty']."' WHERE stock_date = '".$arrContent['stock_date']."' LIMIT 1";
				write_log($arrContent['stock_date'], "Adjust Stock", "Back End (Mobile)", "0", $arrContent['sku'], esc_sql($product->get_name()), $oqty, $arrContent['qty'], $_POST['user_id'], get_client_ip(), $sql_statement);				
			}
			
		}
		
		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "Stock Updated";

	}	
	
	
	if($section=="clear_sku_stock") {		
		$array_result = array();
		$stock_date = isset($param['stock_date']) && $param['stock_date']!=""?$param['stock_date']:date("Y-m-d");		
		$arrSkuList = array();
		$stockRecord = $wpdb->get_results("SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1 ");		
		
		foreach($stockRecord as $dataObj){
			$dataArr = (Array)$dataObj;
			
			//loop all column name in the stock table (except id and stock date), in order to get the sku# automatically
			$skuList = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date','stock_dayofweek')" );
			
			foreach($skuList as $skuObj){				
				//create product object from sku#
				$arr_sku = array(); 				
				if(check_stock_init($skuObj->Field, $dataArr['stock_date'])){ //check if sku is already discontinued	
					//array_push($arrSkuList, $skuObj->Field);
					$arrSkuList[$skuObj->Field] = true;
				} else {					
					$product = wc_get_product(wc_get_product_id_by_sku($skuObj->Field));					
					$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
					$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$stock_date."'");						
					foreach ($result as $order_obj ){
						$order = wc_get_order( $order_obj->ID );
						foreach ( $order->get_items() as $item ) {							
							if($item->get_product()->get_sku() == $product->get_sku()) {
								//array_push($arrSkuList, $product->get_sku());
								$arrSkuList[$skuObj->Field] = false;
							}
						}
					}
				}
			}
		}	
				
		$success = true;		
		foreach($arrSkuList as $productSKU=>$editable){
			$product = wc_get_product(wc_get_product_id_by_sku($productSKU));
			//$arr_sku['product_id'] = $product->get_id();
			//$arr_sku['sku'] = $productSKU;
			//$arr_sku['name'] = $product->get_name();
			$sql = "SELECT * FROM sku_stock WHERE stock_date = '".$stock_date."' LIMIT 1";
			$result = $wpdb->get_results($sql);
			$data = (array)$result[0];
			$oqty = floatval($data[$productSKU]);
			
			if($wpdb->update('sku_stock', array( $productSKU => 0),array('stock_date'=>$stock_date))){
				$sql_statement = "UPDATE sku_stock SET `".$productSKU."` = 0 WHERE stock_date = '".$stock_date."' LIMIT 1";
				write_log($stock_date, "Clear Stock", "Back End (Mobile)", "0", $productSKU, esc_sql($product->get_name()), $oqty, 0, $param['user_id'], get_client_ip(), $sql_statement);	
			} /*else {
				$success = false;
			} */
		}	
		
		if($success==true) {
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Stock Updated";
				$array_result['stockDate'] = $stock_date;					
			
		} else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Error";
				$array_result['message'] = "Fail to write data";
				$array_result['stockDate'] = $stock_date;					
		
		}
		
	}	
	
	
	// no longer used 
	if($section=="daily_production_summary") {
		global $wpdb;					
			
			$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
			$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'");	
			$free_gift = 0;
			$summary = array();
			foreach ($result as $order_obj ){
				//get order object from order id
				$order = wc_get_order( $order_obj->ID );
				$order_type = is_wholesaler_order($order_obj->ID)?"group":"individual";
				/*
				$ship_method = $order->get_shipping_method();
		
				if($ship_method=="送貨" || $ship_method=="Delivery"){					
					$display_ship_method = "Delivery";	
					//$display_delivery_region = true;
				}elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){
					$display_ship_method = "Delivery";
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="自取" || $ship_method=="Pick-up"){
					$display_ship_method = "Pick-up";				
				}elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) {
					$display_ship_method = "Collect";
					//$display_pickup_location = true;
				}else{
					$display_ship_method = $ship_method;		
				}	
				*/				
				$delivery_date = $order->get_meta('delivery_date', true);	

				if($delivery_date == $_GET['delivery_date']){
					
					//free gift period is from 5/2/2021 to 11/2/2021
					$date = new DateTime("02/12/2021");
					
					//check for free gift, order $ >= 300, and order date is before 12/2/2021.
					if($order->get_subtotal() >= 300 && $order->get_date_created()<$date)
						$free_gift++;
					
					$arr_qyt_by_ship_method = array();
					foreach ( $order->get_items() as $item ) { //print each order line item								
						$array_line = array();
						$prod = $item->get_product();
						$sku = $prod->get_sku();
						$variation_id = $item->get_variation_id();
						$variation = new WC_Product_Variation($variation_id); // get variation object from variation id
						$variationName = implode(" / ", $variation->get_variation_attributes()); // get variation name from ariation object							
						$product = wc_get_product(wc_get_product_id_by_sku($sku));
						if($variation_id!=0){
							$id = $product->get_name()." - ".$variationName; // make a unique key
						}else{					
							$id = $product->get_name(); // make a unique key
						}
						$summary[$id]['variationName'] = $variationName;
						$summary[$id]['productID']=$item->get_product_id();
						$summary[$id]['variationID'] = $variation_id;
						
						if (array_key_exists($id, $summary)) { //product id already exist in summary array, then add ordered qty to its corresonding array value
							$summary[$id]['qty']+=$item->get_quantity();
						}else{ 
							$summary[$id]['qty']=$item->get_quantity(); //insert new product id to summary array					
						}				
						
						$summary[$id]['type'][$order_type]+=$item->get_quantity();
						
											
					}
				}
			}	
						
			ksort($summary);
			
			//print_r($summary);
			
			
			$array_data = array();

			foreach($summary as $name => $contentObj){
				$line = array();
				$line['product'] = $name;
				
							
				$trid = $sitepress->get_element_trid($contentObj['productID'], 'post_product');
				$translations = $sitepress->get_element_translations($trid, 'product');
				foreach( $translations as $lang=>$translation){
					if($translation->language_code == "zh-hant")
						$zh_post_id = $translation->element_id;
				}
				
				
				$line['product_id'] = $contentObj['productID'];
				$line['variation_id'] = $contentObj['variationID'];
				$line['product_zh'] = get_the_title($zh_post_id);				
				//$line['post_id'] = $zh_post_id;		
				$line['variation_name'] = $contentObj['variationName'];
				//$line['product_zh'] = $contentObj['productID'];
				$line['total'] = intval($contentObj['qty']);
				
				$line['group'] = intval($contentObj['type']['group']);
				$line['individual'] = intval($contentObj['type']['individual']);				
				
				/*
				$line['method'] = array();
				foreach($contentObj['method'] as $methodName => $qty){
					$method_line = array('name'=>$methodName, 'quantity'=>intval($qty));
					array_push($line['method'], $method_line);
				}
				*/
				array_push($array_data, $line);	
				
			}		
			$array_result = $array_data;
	}	
	
	
	if($section=="production_summary") {
		global $wpdb;					
			
			$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
			$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'");	
			$free_gift = 0;
			$summary = array();
			foreach ($result as $order_obj ){
				//get order object from order id
				$order = wc_get_order( $order_obj->ID );
				$ship_method = $order->get_shipping_method();
		
				if($ship_method=="送貨" || $ship_method=="Delivery"){					
					$display_ship_method = "Delivery";	
					//$display_delivery_region = true;
				}elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){
					$display_ship_method = "Delivery";
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="自取" || $ship_method=="Pick-up"){
					$display_ship_method = "Pick-up";				
				}elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) {
					$display_ship_method = "Collect";
					//$display_pickup_location = true;
				}else{
					$display_ship_method = $ship_method;		
				}	
								
				$delivery_date = $order->get_meta('delivery_date', true);	

				if($delivery_date == $_GET['delivery_date']){
					
					//free gift period is from 5/2/2021 to 11/2/2021
					$date = new DateTime("02/12/2021");
					
					//check for free gift, order $ >= 300, and order date is before 12/2/2021.
					if($order->get_subtotal() >= 300 && $order->get_date_created()<$date)
						$free_gift++;
					
					$arr_qyt_by_ship_method = array();
					foreach ( $order->get_items() as $item ) { //print each order line item								
						$array_line = array();
						$prod = $item->get_product();
						$sku = $prod->get_sku();
						$variation_id = $item->get_variation_id();
						$variation = new WC_Product_Variation($variation_id); // get variation object from variation id
						$variationName = implode(" / ", $variation->get_variation_attributes()); // get variation name from ariation object							
						$product = wc_get_product(wc_get_product_id_by_sku($sku));
						if($variation_id!=0){
							$id = $product->get_name()." - ".$variationName; // make a unique key
						}else{					
							$id = $product->get_name(); // make a unique key
						}
						$summary[$id]['variationName'] = $variationName;
						$summary[$id]['productID']=$item->get_product_id();
						$summary[$id]['variationID'] = $variation_id;
						
						if (array_key_exists($id, $summary)) { //product id already exist in summary array, then add ordered qty to its corresonding array value
							$summary[$id]['qty']+=$item->get_quantity();
						}else{ 
							$summary[$id]['qty']=$item->get_quantity(); //insert new product id to summary array					
						}				
						
						$summary[$id]['method'][$display_ship_method]+=$item->get_quantity();
						
											
					}
				}
			}	
						
			ksort($summary);
			
			//print_r($summary);
			
			
			$array_data = array();

			foreach($summary as $name => $contentObj){
				$line = array();
				$line['product'] = $name;
				
							
				$trid = $sitepress->get_element_trid($contentObj['productID'], 'post_product');
				$translations = $sitepress->get_element_translations($trid, 'product');
				foreach( $translations as $lang=>$translation){
					if($translation->language_code == "zh-hant")
						$zh_post_id = $translation->element_id;
				}
				
				
				$line['product_id'] = $contentObj['productID'];
				$line['variation_id'] = $contentObj['variationID'];
				$line['product_zh'] = get_the_title($zh_post_id);				
				//$line['post_id'] = $zh_post_id;		
				$line['variation_name'] = $contentObj['variationName'];
				//$line['product_zh'] = $contentObj['productID'];
				$line['total'] = intval($contentObj['qty']);
				
				$line['pickup'] = intval($contentObj['method']['Pick-up']);
				$line['collect'] = intval($contentObj['method']['Collect']);
				$line['delivery'] = intval($contentObj['method']['Delivery']);
				
				/*
				$line['method'] = array();
				foreach($contentObj['method'] as $methodName => $qty){
					$method_line = array('name'=>$methodName, 'quantity'=>intval($qty));
					array_push($line['method'], $method_line);
				}
				*/
				array_push($array_data, $line);	
				
			}		
			$array_result = $array_data;				
	}		
	
	// testing for product id (zh<=>en) matching
	if($section=="production_summary_detail_test") {
		global $wpdb;					
			$array_result = array();
			$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
			$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'");	
			$summary = array();
			foreach ($result as $order_obj ){
				//get order object from order id
				$order = wc_get_order( $order_obj->ID );
				$ship_method = $order->get_shipping_method();
		
				if($ship_method=="送貨" || $ship_method=="Delivery"){					
					$display_ship_method = "Delivery";	
					//$display_delivery_region = true;
				}elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){
					$display_ship_method = "Delivery";
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="自取" || $ship_method=="Pick-up"){
					$display_ship_method = "Pick-up";				
				}elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) {
					$display_ship_method = "Collect";
					//$display_pickup_location = true;
				}else{
					$display_ship_method = $ship_method;		
				}	
								
				$delivery_date = $order->get_meta('delivery_date', true);					
					
				$qty = 0;				
				$show = false;
				foreach ( $order->get_items() as $item ) { //print each order line item	
				
				
					if($item->get_product_id()!=0){
						$product_trid = $sitepress->get_element_trid($item->get_product_id(), 'post_product');
						$translations = $sitepress->get_element_translations($product_trid, 'product');
						foreach( $translations as $lang=>$translation){
							if($translation->language_code == "zh-hant")
								$alias_product_id = $translation->element_id;
						}	
					} else {
						$alias_product_id = 0;
					}
				

					if($item->get_variation_id()!=0){
						$variation_trid = $sitepress->get_element_trid($item->get_variation_id(), 'post_product');
						$translations = $sitepress->get_element_translations($variation_trid, 'product');
						foreach( $translations as $lang=>$translation){
							if($translation->language_code == "zh-hant")
								$alias_variation_id = $translation->element_id;
						}	
					} else {
						$alias_variation_id = 0;
					}				
										
					if($item->get_product_id() == $_GET['product_id'] && $item->get_variation_id() == $_GET['variation_id']){
						$show = true;
						$qty = $item->get_quantity();
					}	
					
					if($alias_product_id == $_GET['product_id'] && $alias_variation_id == $_GET['variation_id']){
						$show = true;
						$qty = $item->get_quantity();
					}										
				}
				
				if ($show) {
					$orderArr = array();
					$orderArr['id'] =  $order->get_id();
					$orderArr['number'] =  $order->get_order_number();
					$orderArr['date_created'] = date("Y-m-d\TH:i:s", strtotime($order_obj->post_date));
					$orderArr['delivery_date'] = get_post_meta($order->get_id(), 'delivery_date', true);
					$orderArr['total'] = $order->get_total();
					$orderArr['status'] = $order->get_status();
					$orderArr['ship_method'] = $display_ship_method;
					$orderArr['billing_first_name'] = $order->get_billing_first_name();
					$orderArr['billing_last_name'] = $order->get_billing_last_name();
					$orderArr['billing_company'] = $order->get_billing_company();
					$orderArr['billing_email'] = $order->get_billing_email();
					$orderArr['billing_phone'] = $order->get_billing_phone();
					$orderArr['shipping_phone'] = get_post_meta($order->get_id(), '_shipping_phone', true);
					$orderArr['qty'] = $qty;
					
					array_push($array_result, $orderArr);
				}
				
			}	
						

//			$array_result = $array_data;				
	}	


	if($section=="production_summary_detail") {
		global $wpdb;					
			$array_result = array();
			$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
			$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'");	
			$summary = array();
			foreach ($result as $order_obj ){
				//get order object from order id
				$order = wc_get_order( $order_obj->ID );
				$ship_method = $order->get_shipping_method();
		
				if($ship_method=="送貨" || $ship_method=="Delivery"){					
					$display_ship_method = "Delivery";	
					//$display_delivery_region = true;
				}elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){
					$display_ship_method = "Delivery";
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="自取" || $ship_method=="Pick-up"){
					$display_ship_method = "Pick-up";				
				}elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) {
					$display_ship_method = "Collect";
					//$display_pickup_location = true;
				}else{
					$display_ship_method = $ship_method;		
				}	
								
				$delivery_date = $order->get_meta('delivery_date', true);					
					
				$qty = 0;				
				$show = false;			
				
				foreach ( $order->get_items() as $item ) { //print each order line item							
								
					if($item->get_product_id()!=0){
						$product_trid = $sitepress->get_element_trid($item->get_product_id(), 'post_product');
						$translations = $sitepress->get_element_translations($product_trid, 'product');
						foreach( $translations as $lang=>$translation){
							//if($translation->language_code == "zh-hant")
							if($translation->language_code == "en")
								$product_id = $translation->element_id;
						}	
						foreach( $translations as $lang=>$translation){
							if($translation->language_code == "zh-hant")
							//if($translation->language_code == "en")
								$alias_product_id = $translation->element_id;
						}							
					} else {
						$product_id = 0;
						$alias_product_id = 0;
					}

					
					if($item->get_variation_id()!=0){
						$variation_trid = $sitepress->get_element_trid($item->get_variation_id(), 'post_product');
						$translations = $sitepress->get_element_translations($variation_trid, 'product');
						foreach( $translations as $lang=>$translation){
							//if($translation->language_code == "zh-hant")
							if($translation->language_code == "en")
								$variation_id = $translation->element_id;
						}	
						foreach( $translations as $lang=>$translation){
							if($translation->language_code == "zh-hant")
							//if($translation->language_code == "en")
								$alias_variation_id = $translation->element_id;
						}							
					} else {
						$variation_id = 0;
						$alias_variation_id = 0;
					}
					
						
										
					if($product_id == $_GET['product_id'] && $variation_id == $_GET['variation_id']){
						$show = true;					
						$qty = $item->get_quantity();
					}	
					
					if($alias_product_id == $_GET['product_id'] && $alias_variation_id == $_GET['variation_id']){
						$show = true;										
						$qty = $item->get_quantity();
					}		
													
				}
				
				
				if ($show) {
					$orderArr = array();
					$orderArr['id'] =  $order->get_id();
					$orderArr['number'] =  $order->get_order_number();
					$orderArr['date_created'] = date("Y-m-d\TH:i:s", strtotime($order_obj->post_date));
					$orderArr['delivery_date'] = get_post_meta($order->get_id(), 'delivery_date', true);
					$orderArr['total'] = $order->get_total();
					$orderArr['status'] = $order->get_status();
					$orderArr['ship_method'] = $display_ship_method;
					$orderArr['billing_first_name'] = $order->get_billing_first_name();
					$orderArr['billing_last_name'] = $order->get_billing_last_name();
					$orderArr['billing_company'] = $order->get_billing_company();
					$orderArr['billing_email'] = $order->get_billing_email();
					$orderArr['billing_phone'] = $order->get_billing_phone();
					$orderArr['shipping_phone'] = get_post_meta($order->get_id(), '_shipping_phone', true);
					$orderArr['qty'] = $qty;										
					array_push($array_result, $orderArr);
				}
				
			}			

//			$array_result = $array_data;				
	}	
	

	if($section=="sku_stock_detail") {
		global $wpdb;					
			$array_result = array();
			$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
			$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value = '".$_GET['delivery_date']."'");	
			$summary = array();
			foreach ($result as $order_obj ){
				//get order object from order id
				$order = wc_get_order( $order_obj->ID );
				$ship_method = $order->get_shipping_method();
		
				if($ship_method=="送貨" || $ship_method=="Delivery"){					
					$display_ship_method = "Delivery";	
					//$display_delivery_region = true;
				}elseif($ship_method=="送貨 1" || $ship_method=="Delivery 1"){
					$display_ship_method = "Delivery";
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 2" || $ship_method=="Delivery 2"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 3" || $ship_method=="Delivery 3"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="送貨 4" || $ship_method=="Delivery 4"){
					$display_ship_method = "Delivery";	
					//$display_pickup_location = true;
				}elseif($ship_method=="自取" || $ship_method=="Pick-up"){
					$display_ship_method = "Pick-up";				
				}elseif(strpos($ship_method, '交收') !== false || strpos($ship_method, 'Collect') !== false) {
					$display_ship_method = "Collect";
					//$display_pickup_location = true;
				}else{
					$display_ship_method = $ship_method;		
				}	
								
				$delivery_date = $order->get_meta('delivery_date', true);					
					
				$qty = 0;				
				$show = false;

				$productMaster = wc_get_product($_GET['product_id']);
				$sku = $productMaster->get_sku();

				foreach ( $order->get_items() as $item ) { //print each order line item												
					
					$product = $item->get_product();		
					$stock_sku = get_master_sku($product->get_sku());
					$unit_qty = 1;	
					
					if(has_master_sku($product->get_sku())){
						$unit_qty = get_master_sku_unit_qty($product->get_sku());	//get master sku unit qty 
					}else{
						$variation_id = $item->get_variation_id();										
						if($variation_id!=0){				
							$unit_qty = get_variation_unit_qty($variation_id); //get variation unit qty
						}else{
							$unit_qty = 1;
						}	
					}					
					if($stock_sku == $sku){
						$show = true;
						$qty += $item->get_quantity()*$unit_qty;						
					}
				}
				
				if ($show) {
					$orderArr = array();
					$orderArr['id'] =  $order->get_id();
					$orderArr['number'] =  $order->get_order_number();
					$orderArr['date_created'] = date("Y-m-d\TH:i:s", strtotime($order_obj->post_date));
					$orderArr['delivery_date'] = get_post_meta($order->get_id(), 'delivery_date', true);
					$orderArr['total'] = $order->get_total();
					$orderArr['status'] = $order->get_status();
					$orderArr['ship_method'] = $display_ship_method;
					$orderArr['billing_first_name'] = $order->get_billing_first_name();
					$orderArr['billing_last_name'] = $order->get_billing_last_name();
					$orderArr['billing_company'] = $order->get_billing_company();
					$orderArr['billing_email'] = $order->get_billing_email();
					$orderArr['billing_phone'] = $order->get_billing_phone();
					$orderArr['shipping_phone'] = get_post_meta($order->get_id(), '_shipping_phone', true);
					$orderArr['qty'] = floatval($qty);
					
					array_push($array_result, $orderArr);
				}
				
			}	
						

//			$array_result = $array_data;				
	}	
	

	if($section=="sales_summary") {
		global $wpdb;					
		$array_result = array();
		$post_status = implode("','", array('wc-pending', 'wc-processing', 'wc-completed') );
		$result = $wpdb->get_results("SELECT * FROM wp_posts order_master left join wp_postmeta order_detail ON order_master.ID = order_detail.post_id WHERE order_master.post_type = 'shop_order' AND order_master.post_status IN ('{$post_status}') AND order_detail.meta_key = 'delivery_date' AND order_detail.meta_value LIKE '".$_GET['year']."%'");	
		
		//$array_result = array(10000,11000,12000,33330,44440,22220,50000,70000,72000,67000,80000,0);
		
		$array_result = array(0,0,0,0,0,0,0,0,0,0,0,0);
		
		foreach ($result as $order_obj ){			
			$order = wc_get_order( $order_obj->ID );
			$delivery_date = $order->get_meta('delivery_date', true);
			$month = date("n",strtotime($delivery_date));
			$index = $month - 1;
			$total = $order->get_total();
			$refund = get_post_meta($order_obj->ID, "_refund_amount", true)==""?0:get_post_meta($order_obj->ID, "_refund_amount", true);
			$net_total = $total - $refund;
			$array_result[$index] += $net_total;	
		}
		
	}		
	

	// get order id from order key
	if($section=="retrieve_order_id") {	
		global $wpdb;					
		$array_result = array();	
		$order_id = wc_get_order_id_by_order_key( $_GET['order_key'] );
		if($order_id==0){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Invalid Order Key";
			$array_result['id'] = 0;	
			$array_result['number'] = "";		
		} else {
			$order = wc_get_order( $order_id );
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = "Order #: #".$order->get_order_number();
			$array_result['id'] = intval($order_id);	
			$array_result['number'] = $order->get_order_number();		
		}
	} 		
	
	// testing use only
	if($section=="create_order_test") {	
		sleep(5);
		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "TEST CODE";
		//$array_result['message'] = "Order created: #".$order_id;
		$array_result['message'] = "Order# created: TEST";
		$array_result['id'] = 1111;
		$array_result['number'] = "Test";
	} 			


	// for gift box page
	if($section=="gift_box_2022") {	
		global $wpdb;
		$array_result = array();
		$arr_sku = array("TS-PAL-250","TS-YYP-300","TS-APM-275","GB-CNP-325","GB-CCN-211","GB-CCC-163","GB-CCC-286");
		$begin_date = "2022-01-24";
		$end_date = "2022-01-29";	
		$figure = gift_box_figure_2022($arr_sku,$begin_date,$end_date);
		
		foreach($figure as $skus=>$content){
			$product = wc_get_product(wc_get_product_id_by_sku($skus));

			$zh_post_id = 0;
			$trid = $sitepress->get_element_trid($product->get_id(), 'post_product');
			$translations = $sitepress->get_element_translations($trid, 'product');
			foreach( $translations as $lang=>$translation){
				if($translation->language_code == "zh-hant")
					$zh_post_id = $translation->element_id;
			}				
			$arr_sku_info = array();
			$arr_sku_info['sku'] = $skus;
			$arr_sku_info['name'] = $product->get_name();
			$arr_sku_info['name_zh'] = get_the_title($zh_post_id);	
			
			$arr_content = array();
			foreach($content as $date=>$qty){
				array_push($arr_content, array("deliveryDate"=>$date, "qty"=>intval($qty)));
			}
			$arr_sku_info['figure'] = $arr_content;	
			
						
			array_push($array_result, $arr_sku_info);
			
		}
			
	} 		
	
	
	if($section=="gift_box_2022_live") {	
		global $wpdb;
		$array_result = array();
		$arr_sku = array("TS-PAL-250","TS-YYP-300","TS-APM-275","GB-CNP-325","GB-CCN-211","GB-CCC-163","GB-CCC-286","TS-APM-220","TS-PAL-200");
		$begin_date = "2022-01-24";
		$end_date = "2022-01-29";	
		$figure = gift_box_figure_2022($arr_sku,$begin_date,$end_date);
		
		foreach($figure as $skus=>$content){
			$product = wc_get_product(wc_get_product_id_by_sku($skus));

			$zh_post_id = 0;
			$trid = $sitepress->get_element_trid($product->get_id(), 'post_product');
			$translations = $sitepress->get_element_translations($trid, 'product');
			foreach( $translations as $lang=>$translation){
				if($translation->language_code == "zh-hant")
					$zh_post_id = $translation->element_id;
			}				
			$arr_sku_info = array();
			$arr_sku_info['sku'] = $skus;
			$arr_sku_info['name'] = $product->get_name();
			$arr_sku_info['name_zh'] = get_the_title($zh_post_id);	
			
			$arr_content = array();
			$ttl = 0;
			foreach($content as $date=>$qty){
				$ttl += $qty;
				array_push($arr_content, array("deliveryDate"=>$date, "qty"=>intval($qty)));
			}
			$arr_sku_info['ordered_qty'] = $ttl;
			

			$skuObj = $wpdb->get_results("Select * FROM sku_giftbox_2022 WHERE sku = '".$skus."' LIMIT 1");
			$arr_sku_info['completed_qty'] = intval($skuObj[0]->completed_qty);
			$arr_sku_info['remaining_qty'] = $arr_sku_info['total'] - $arr_sku_info['completed_qty'];
				
			$arr_sku_info['figure'] = $arr_content;	
			
						
			array_push($array_result, $arr_sku_info);
			
		}
			
	} 		
	
	if($section=="get_IPLData") {	
		global $wpdb;

		$dataContent = array();
		$delivery_date = $_GET['delivery_date'];

		$rowData = $wpdb->get_results( "SELECT * FROM sku_stock WHERE stock_date = '".$delivery_date."' LIMIT 1 ");

		//for each found row
		foreach($rowData as $dataObj){
			$dataArr = (Array)$dataObj;
			
			//loop all column name in the stock table (except id and stock date), in order to get the sku# automatically
			$mycolumns = $wpdb->get_results("SHOW COLUMNS FROM sku_stock where Field NOT in ('id','stock_date','stock_dayofweek')" );
			
			foreach($mycolumns as $skuObj){		
				//create product object from sku#
				$product_check = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $skuObj->Field) );
				if ( $product_check ) {
					$salesStatus = check_stock_init($skuObj->Field, $dataArr['stock_date']);
					if($salesStatus>=0){ 
						$style="";
						$skuInitObj = get_sku_init_info($skuObj->Field);
						$productResult = $wpdb->get_results("SELECT * FROM inventory_product WHERE sku_id = '".$skuInitObj->id."' LIMIT 1");
						$productObj = $productResult[0];	
						
						$unit_name = get_unit_name(1, $productObj->id);
						if(empty($unit_name)){ // recipe not set
							$sortStatus = "z";
						}elseif($salesStatus=="0"){ // discontinue
							$sortStatus = "3";
						}elseif($salesStatus=="1"){ // selling
							$sortStatus = "0";
						}elseif($salesStatus=="2"){ // coming soon
							$sortStatus = "1";
						}


						if(getSavedValueFromIPL($dataArr['stock_date'], $productObj->id)>0){
							$showUnitQty = getSavedValueFromIPL($dataArr['stock_date'], $productObj->id);
						} else {
							$showUnitQty = get_production_qty($skuObj->Field, $dataArr['stock_date']);
						}						
						
						$lineData = array(
							"stock_date"=>$dataArr['stock_date'],
							"product_id"=>intval($productObj->id),
							"sku_id"=>intval($skuInitObj->id),
							"sku"=>$skuObj->Field,
							"order_qty"=>floatval(get_production_qty($skuObj->Field, $dataArr['stock_date'])),
							"qty_per_unit"=>intval($skuInitObj->unit_qty),
							"desc"=>$skuInitObj->description,
							"confirmed_production_qty"=>floatval($showUnitQty),
							"confirmed_production_qty_pic"=>floatval(ceil($showUnitQty*$skuInitObj->unit_qty)),
							"status"=>strval($sortStatus)
						);
						
						array_push($dataContent, $lineData);

					}
				}
			}
		}
		
		usort($dataContent,function($a,$b){
			//return $b['confirmed_production_qty'] <=> $a['confirmed_production_qty'] ?: $b['status'] <=> $a['status']
			return $a['status'] <=> $b['status'] ?: $b['confirmed_production_qty'] <=> $a['confirmed_production_qty'];
		});			


		//$dataContent = array_slice($dataContent, 0, 10);


		$array_result = $dataContent;

	}


	if($section=="adjust_ipl_data"){
		global $wpdb;
		$content = json_decode(stripslashes($_POST['content_data']), true);
		
		//$wpdb->query('TRUNCATE TABLE `inventory_preparation_list`');
		$result = $wpdb->delete("inventory_preparation_list", array( 'delivery_date' => $_POST['delivery_date'] ) );
		$test = $wpdb->last_query;//echo $wpdb->last_query;
		//var_dump($result);
		if($result!==false){
			$hash = md5(time());
			$save_time = date("Y-m-d H:i:s");

			foreach($content as $arrContent){
				$wpdb->insert(
					'inventory_preparation_list', 
					array(
						'product_id' => $arrContent['product_id'],
						'sku_id' => $arrContent['sku_id'],
						'sku' => $arrContent['sku'],
						'name' => $arrContent['desc'],
						'order_qty' => $arrContent['order_qty'],
						'qty_per_unit' => $arrContent['qty_per_unit'],
						'confirmed_production_qty' => $arrContent['confirmed_production_qty'],
						'confirmed_production_qty_pic' => $arrContent['confirmed_production_qty_pic'],
						'delivery_date' => $arrContent['stock_date'],
						'hash' => $hash
					)
				);
			}
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = "Data Updated";			

		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Error";
			$array_result['message'] = "Data Update Fail";
			
		}

	}

	if($section=="print_ipl_data"){

		global $wpdb;
		$content = json_decode(stripslashes($_POST['content_data']), true);

		//$a = '[{\"product_id\":14,\"stock_date\":\"2022-10-03\",\"sku_id\":50,\"order_qty\":10,\"sku\":\"BD-JBL-320\",\"confirmed_production_qty_pic\":20,\"status\":\"0\",\"qty_per_unit\":2,\"confirmed_production_qty\":10,\"desc\":\"日式菠蘿油\"},{\"product_id\":6,\"stock_date\":\"2022-10-03\",\"sku_id\":5,\"order_qty\":6,\"sku\":\"BD-JPL-425\",\"confirmed_production_qty_pic\":6,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":6,\"desc\":\"秘密。生吐司\"},{\"product_id\":8,\"stock_date\":\"2022-10-03\",\"sku_id\":27,\"order_qty\":3,\"sku\":\"BD-FPB-300\",\"confirmed_production_qty_pic\":3,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":3,\"desc\":\"無花果碧根果裸麥包\"},{\"product_id\":2,\"stock_date\":\"2022-10-03\",\"sku_id\":3,\"order_qty\":3,\"sku\":\"BD-ABR-180\",\"confirmed_production_qty_pic\":12,\"status\":\"0\",\"qty_per_unit\":4,\"confirmed_production_qty\":3,\"desc\":\"鯷魚鹽可頌\"},{\"product_id\":34,\"stock_date\":\"2022-10-03\",\"sku_id\":15,\"order_qty\":3,\"sku\":\"BD-CBR-180\",\"confirmed_production_qty_pic\":12,\"status\":\"0\",\"qty_per_unit\":4,\"confirmed_production_qty\":3,\"desc\":\"蔡瀾鹹魚醬鹽可頌\"},{\"product_id\":7,\"stock_date\":\"2022-10-03\",\"sku_id\":10,\"order_qty\":3,\"sku\":\"TS-CBS-170\",\"confirmed_production_qty_pic\":6,\"status\":\"0\",\"qty_per_unit\":2,\"confirmed_production_qty\":3,\"desc\":\"芝士煙肉鬆餅\"},{\"product_id\":3,\"stock_date\":\"2022-10-03\",\"sku_id\":18,\"order_qty\":2,\"sku\":\"TS-HCT-100\",\"confirmed_production_qty_pic\":2,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":2,\"desc\":\"蜜糖牛油脆粒\"},{\"product_id\":1,\"stock_date\":\"2022-10-03\",\"sku_id\":6,\"order_qty\":2,\"sku\":\"BD-SBR-180\",\"confirmed_production_qty_pic\":8,\"status\":\"0\",\"qty_per_unit\":4,\"confirmed_production_qty\":2,\"desc\":\"鹽可頌\"},{\"product_id\":4,\"stock_date\":\"2022-10-03\",\"sku_id\":16,\"order_qty\":2,\"sku\":\"BD-RBL-460\",\"confirmed_production_qty_pic\":2,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":2,\"desc\":\"紅豆方包\"},{\"product_id\":11,\"stock_date\":\"2022-10-03\",\"sku_id\":30,\"order_qty\":2,\"sku\":\"BD-FCB-210\",\"confirmed_production_qty_pic\":4,\"status\":\"0\",\"qty_per_unit\":2,\"confirmed_production_qty\":2,\"desc\":\"四重芝士包\"},{\"product_id\":13,\"stock_date\":\"2022-10-03\",\"sku_id\":12,\"order_qty\":1.5,\"sku\":\"BD-WNL-460\",\"confirmed_production_qty_pic\":2,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":1.5,\"desc\":\"合桃方包\"},{\"product_id\":12,\"stock_date\":\"2022-10-03\",\"sku_id\":19,\"order_qty\":1,\"sku\":\"BD-WLR-300\",\"confirmed_production_qty_pic\":1,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":1,\"desc\":\"合桃桂圓包\"},{\"product_id\":70,\"stock_date\":\"2022-10-03\",\"sku_id\":53,\"order_qty\":0,\"sku\":\"CM-ISP-620\",\"confirmed_production_qty_pic\":0,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"Custom - Inu Shokupan\"},{\"product_id\":5,\"stock_date\":\"2022-10-03\",\"sku_id\":46,\"order_qty\":0,\"sku\":\"BD-CMB-300\",\"confirmed_production_qty_pic\":0,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"紅莓多穀裸麥包\"},{\"product_id\":10,\"stock_date\":\"2022-10-03\",\"sku_id\":8,\"order_qty\":0,\"sku\":\"TS-CCC-163\",\"confirmed_production_qty_pic\":0,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"椰子薄脆\"},{\"product_id\":22,\"stock_date\":\"2022-10-03\",\"sku_id\":7,\"order_qty\":0,\"sku\":\"TS-CAN-260\",\"confirmed_production_qty_pic\":0,\"status\":\"0\",\"qty_per_unit\":20,\"confirmed_production_qty\":0,\"desc\":\"軟杏仁紅莓鳥結糖\"},{\"product_id\":9,\"stock_date\":\"2022-10-03\",\"sku_id\":4,\"order_qty\":0,\"sku\":\"BD-BAG-300\",\"confirmed_production_qty_pic\":0,\"status\":\"0\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"法包\"},{\"product_id\":16,\"stock_date\":\"2022-10-03\",\"sku_id\":24,\"order_qty\":2,\"sku\":\"BD-CCR-160\",\"confirmed_production_qty_pic\":4,\"status\":\"1\",\"qty_per_unit\":2,\"confirmed_production_qty\":2,\"desc\":\"椰絲卷\"},{\"product_id\":28,\"stock_date\":\"2022-10-03\",\"sku_id\":44,\"order_qty\":0,\"sku\":\"BD-KCB-340\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"韓國蒜蓉芝士包\"},{\"product_id\":17,\"stock_date\":\"2022-10-03\",\"sku_id\":26,\"order_qty\":0,\"sku\":\"BD-CSB-160\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"芝心棒\"},{\"product_id\":73,\"stock_date\":\"2022-10-03\",\"sku_id\":56,\"order_qty\":0,\"sku\":\"BD-NNS-330\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"Neko Neko Shokupan\"},{\"product_id\":21,\"stock_date\":\"2022-10-03\",\"sku_id\":22,\"order_qty\":0,\"sku\":\"BD-CRC-200\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"特濃朱古力脆皮包\"},{\"product_id\":71,\"stock_date\":\"2022-10-03\",\"sku_id\":54,\"order_qty\":0,\"sku\":\"BD-SRL-176\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"英式豬肉卷\"},{\"product_id\":23,\"stock_date\":\"2022-10-03\",\"sku_id\":13,\"order_qty\":0,\"sku\":\"BD-BRL-460\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"黑糖提子方包\"},{\"product_id\":18,\"stock_date\":\"2022-10-03\",\"sku_id\":11,\"order_qty\":0,\"sku\":\"BD-CMR-085\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"玉桂卷\"},{\"product_id\":72,\"stock_date\":\"2022-10-03\",\"sku_id\":55,\"order_qty\":0,\"sku\":\"BD-FPB-155\",\"confirmed_production_qty_pic\":0,\"status\":\"1\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"法式布丁包\"},{\"product_id\":41,\"stock_date\":\"2022-10-03\",\"sku_id\":51,\"order_qty\":0,\"sku\":\"BD-HMC-240\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"港式奶茶可頌瑪芬\"},{\"product_id\":69,\"stock_date\":\"2022-10-03\",\"sku_id\":52,\"order_qty\":0,\"sku\":\"BD-PPB-260\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"剝皮辣椒豬肉包\"},{\"product_id\":19,\"stock_date\":\"2022-10-03\",\"sku_id\":49,\"order_qty\":0,\"sku\":\"BD-LCB-320\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"檸檬金寶包\"},{\"product_id\":39,\"stock_date\":\"2022-10-03\",\"sku_id\":37,\"order_qty\":0,\"sku\":\"TS-PAL-250\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春 - 蝴蝶酥\"},{\"product_id\":20,\"stock_date\":\"2022-10-03\",\"sku_id\":48,\"order_qty\":0,\"sku\":\"BD-GML-400\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"蔥蒜肉鬆扭紋包\"},{\"product_id\":24,\"stock_date\":\"2022-10-03\",\"sku_id\":47,\"order_qty\":0,\"sku\":\"BD-CMC-200\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"忌廉芝士麻辣雞包\"},{\"product_id\":15,\"stock_date\":\"2022-10-03\",\"sku_id\":45,\"order_qty\":0,\"sku\":\"BD-MMB-125\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"小山園抹茶麻糬包\"},{\"product_id\":66,\"stock_date\":\"2022-10-03\",\"sku_id\":41,\"order_qty\":0,\"sku\":\"GB-CCC-163\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春禮盒(細)椰子薄脆\"},{\"product_id\":65,\"stock_date\":\"2022-10-03\",\"sku_id\":40,\"order_qty\":0,\"sku\":\"GB-CCC-286\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春禮盒(大)椰子薄脆\"},{\"product_id\":67,\"stock_date\":\"2022-10-03\",\"sku_id\":1,\"order_qty\":0,\"sku\":\"GB-CCN-211\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春禮盒(細)\"},{\"product_id\":68,\"stock_date\":\"2022-10-03\",\"sku_id\":36,\"order_qty\":0,\"sku\":\"GB-CNP-325\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春禮盒(大)\"},{\"product_id\":27,\"stock_date\":\"2022-10-03\",\"sku_id\":25,\"order_qty\":0,\"sku\":\"BD-KRB-230\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"咖啡包\"},{\"product_id\":33,\"stock_date\":\"2022-10-03\",\"sku_id\":9,\"order_qty\":0,\"sku\":\"BD-SSB-430\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"芝麻法包\"},{\"product_id\":25,\"stock_date\":\"2022-10-03\",\"sku_id\":14,\"order_qty\":0,\"sku\":\"TS-CHS-170\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"辣肉腸鬆餅\"},{\"product_id\":30,\"stock_date\":\"2022-10-03\",\"sku_id\":20,\"order_qty\":0,\"sku\":\"BD-BGL-200\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"貝果\"},{\"product_id\":31,\"stock_date\":\"2022-10-03\",\"sku_id\":21,\"order_qty\":0,\"sku\":\"BD-SPB-200\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"芝麻罌粟籽貝果\"},{\"product_id\":32,\"stock_date\":\"2022-10-03\",\"sku_id\":23,\"order_qty\":0,\"sku\":\"BD-CJB-280\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"忌廉芝士墨西哥辣椒貝果\"},{\"product_id\":26,\"stock_date\":\"2022-10-03\",\"sku_id\":29,\"order_qty\":0,\"sku\":\"BD-CSP-440\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"特濃朱古力生吐司\"},{\"product_id\":38,\"stock_date\":\"2022-10-03\",\"sku_id\":34,\"order_qty\":0,\"sku\":\"CM-HSP-330\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"Custom - HaRu Shokupan\"},{\"product_id\":35,\"stock_date\":\"2022-10-03\",\"sku_id\":31,\"order_qty\":0,\"sku\":\"CK-SRC-390\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"秘密。卷蛋\"},{\"product_id\":40,\"stock_date\":\"2022-10-03\",\"sku_id\":35,\"order_qty\":0,\"sku\":\"TS-YYP-300\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春 - 如意玉桂蝴蝶酥\"},{\"product_id\":29,\"stock_date\":\"2022-10-03\",\"sku_id\":28,\"order_qty\":0,\"sku\":\"BD-CST-200\",\"confirmed_production_qty_pic\":0,\"status\":\"3\",\"qty_per_unit\":2,\"confirmed_production_qty\":0,\"desc\":\"牛角酥\"},{\"product_id\":0,\"stock_date\":\"2022-10-03\",\"sku_id\":38,\"order_qty\":0,\"sku\":\"TS-APM-275\",\"confirmed_production_qty_pic\":0,\"status\":\"z\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春 - 雜錦蝴蝶酥\"},{\"product_id\":0,\"stock_date\":\"2022-10-03\",\"sku_id\":2,\"order_qty\":0,\"sku\":\"GB-CAN-357\",\"confirmed_production_qty_pic\":0,\"status\":\"z\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"gift box (L)\"},{\"product_id\":37,\"stock_date\":\"2022-10-03\",\"sku_id\":32,\"order_qty\":0,\"sku\":\"CE-GBM-20\",\"confirmed_production_qty_pic\":0,\"status\":\"z\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"薑餅人\"},{\"product_id\":36,\"stock_date\":\"2022-10-03\",\"sku_id\":33,\"order_qty\":0,\"sku\":\"CK-PCC-624\",\"confirmed_production_qty_pic\":0,\"status\":\"z\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"粉紅絲絨聖誕卷蛋\"},{\"product_id\":0,\"stock_date\":\"2022-10-03\",\"sku_id\":43,\"order_qty\":0,\"sku\":\"TS-PAL-200\",\"confirmed_production_qty_pic\":0,\"status\":\"z\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春 - 蝴蝶酥(紙盒裝)\"},{\"product_id\":0,\"stock_date\":\"2022-10-03\",\"sku_id\":42,\"order_qty\":0,\"sku\":\"TS-APM-220\",\"confirmed_production_qty_pic\":0,\"status\":\"z\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"新春 - 雜錦蝴蝶酥(紙盒裝)\"},{\"product_id\":0,\"stock_date\":\"2022-10-03\",\"sku_id\":17,\"order_qty\":0,\"sku\":\"SC-CSF-175\",\"confirmed_production_qty_pic\":0,\"status\":\"z\",\"qty_per_unit\":1,\"confirmed_production_qty\":0,\"desc\":\"蔡瀾鹹魚醬\"}]';
		//$content = json_decode(stripslashes($a), true);

		$arr_data = array();
		$arr_data['input']=$content;
		$weekarray = array("日","一","二","三","四","五","六");	

		// set product summary data
		foreach($arr_data['input'] as $idx=>$productArr){
			if($arr_data['input'][$idx]['order_qty']>0){
				//$arr_data['output']['summary'][]=array("name"=>$productArr['desc'],"unit_qty"=>intval($productArr['qty_per_unit']),"qty"=>floatval($productArr['order_qty']));
				$arr_data['output']['summary'][]=array("name"=>$productArr['desc'],"unit_qty"=>intval($productArr['order_qty']),"qty"=>intval($productArr['confirmed_production_qty_pic']));
			}
		}

		$arr_temp_data = array();

		//foreach($arr_data['input']['order_qty'] as $qty_idx=>$qty){
		foreach($arr_data['input'] as $idx=>$productArr){

			//$skuObj = get_sku_init_info_by_id($arr_data['input']['sku_id'][$qty_idx]);
			$skuObj = get_sku_init_info_by_id($productArr['sku_id']);

			if(!empty($productArr['order_qty']) && $skuObj->show_in_preparation_list=="Y"){

				$temp_data = getIngredientDataArrayNew(1,$productArr['product_id'],ceil($productArr['order_qty']*$productArr['qty_per_unit']));

				if(!isset($temp_data['extra'])){  
					$arr_temp_data[] = $temp_data;	
				}  else {
					$temp_data_copy = $temp_data;
					unset($temp_data['extra']);
					$arr_temp_data[] = $temp_data;					

					foreach($temp_data_copy['extra'] as $extra_product_first_level) {  // 1st level
						if(!isset($extra_product_first_level['extra'])){
							$arr_temp_data[] = $extra_product_first_level;	
						} else {
							$extra_product_first_level_copy = $extra_product_first_level;
							unset($extra_product_first_level['extra']);
							$arr_temp_data[] = $extra_product_first_level;		

							foreach($extra_product_first_level_copy['extra'] as $extra_product_second_level) {  // 2nd level
								if(!isset($extra_product_second_level['extra'])){
									$arr_temp_data[] = $extra_product_second_level;	
								} else {
									$extra_product_second_level_copy = $extra_product_second_level;
									unset($extra_product_second_level['extra']);
									$arr_temp_data[] = $extra_product_second_level;		

									foreach($extra_product_second_level_copy['extra'] as $extra_product_third_level) {  // 3rd level
										if(!isset($extra_product_third_level['extra'])){
											$arr_temp_data[] = $extra_product_third_level;	
										} else {
											$extra_product_third_level_copy = $extra_product_third_level;
											unset($extra_product_third_level['extra']);
											$arr_temp_data[] = $extra_product_third_level;		

											foreach($extra_product_third_level_copy['extra'] as $extra_product_forth_level) {  // 4th level
												if(!isset($extra_product_forth_level['extra'])){
													$arr_temp_data[] = $extra_product_forth_level;	
												} else {
													$extra_product_forth_level_copy = $extra_product_forth_level;
													unset($extra_product_forth_level['extra']);
													$arr_temp_data[] = $extra_product_forth_level;	
												}
											} // end 4th level
										}
									} // end 3rd level
								}
							} // end 2nd level
						} 
					}	// end first level		
				} 
			}
		}

		// sum up qty of the same sfproduct item
		$resultArr = array();
		foreach($arr_temp_data as $dataArr) {
			$key = array_search($dataArr['product_name'], array_column($resultArr, 'product_name'));    
			if($key!==false){
				$resultArr[$key]['product_qty'] += $dataArr['product_qty'];
				foreach($resultArr[$key]['items'] as $idx=>$lineItem){					
					$resultArr[$key]['items'][$idx]['product_qty'] += $dataArr['items'][$idx]['product_qty'];
				}				
			} else {
				$resultArr[] = $dataArr;
			}
		}

		// 分類
		foreach($resultArr as $result_idx=>$itemData){
			if($itemData['component_type_id']==1) {
				$arr_data['output']['recipe'][] = $itemData;
			} elseif($itemData['component_type_id']==2) {
				$arr_data['output']['sfproduct'][] = $itemData;
			}
		}

		// sorting (input)
		usort($arr_data['input'],function($a,$b){
			return $b['order_qty'] <=> $a['order_qty']
			?: $a['desc'] <=> $b['desc'];
		});	

		// sorting (product summary)
		usort($arr_data['output']['summary'],function($a,$b){
			return $b['unit_qty'] <=> $a['unit_qty'];
		});	

		// sorting (sf product)
		usort($arr_data['output']['sfproduct'],function($a,$b){
			return $a['group'] <=> $b['group']
			?: $a['product_name'] <=> $b['product_name'];
		});	

		// sorting (recipe)
		usort($arr_data['output']['recipe'],function($a,$b){
			return $a['group'] <=> $b['group']
			?: $a['product_name'] <=> $b['product_name'];
		});	

		unset($arr_data['input']);
		$arr_data['input'] = array();
		$arr_data['input']['delivery_date'] = date('j/n',strtotime($_POST['delivery_date']));
		$arr_data['input']['delivery_weekday'] = $weekarray[date("w", strtotime($_POST['delivery_date']))];

		
		//unset($arr_data['output']['summary']);
		//unset($arr_data['output']['sfproduct']);
		//unset($arr_data['output']['recipe']);
		//$arr_data['output']['recipe'] = array_slice($arr_data['output']['recipe'], 0,1 );

		$array_result = $arr_data;

	}

	if($section=="get_store_date_range"){
		$today = date("Y-m-d");
		if(date('H') >= 16){
			$today = date('Y-m-d',  strtotime("+1 day"));
		}		
		if(isset($_GET['date'])){
			if($_GET['date']<$today){
				$date = $today;
			} else {
				$date = $_GET['date'];
			}
		} else {
			$date = $today;
		}


		$date_list = array();
		$info = get_custom_calendar_date_info($date);

		$max_date = $info['maxdate'];

		$holiday_list = get_holiday_list();
		
		for($i=strtotime($date); $i<=strtotime($max_date); $i+=86400){

			if(  (date("N", $i)!=7) && !in_array(date("Y-m-d", $i), $holiday_list) ) {
				$date_list[] = array("date"=>date("Y-m-d", $i));
			}

		}

		$array_result['data'] = $date_list;

	}
	
	if($section=="notification_list"){
		$result = $wpdb->get_results("SELECT * FROM `bsb_notification_center` WHERE user_id = '".$_GET['user_id']."' AND status = 'Y' ORDER BY id DESC ");
		
		if(count($result)>0){
			foreach ($result as $notificationInfo) {			
				$arr_data = array(
					'id' => intval($notificationInfo->id ),
					/*'hash' => $notificationInfo->hash,*/
					'user_id' => intval($notificationInfo->user_id),
					'title' => $notificationInfo->title,
					'message' => $notificationInfo->message,
					/*'device_token' => $notificationInfo->device_token,*/
					'reference_type' => $notificationInfo->type,
					'reference_id' => intval($notificationInfo->reference_id),
					'push_time' => $notificationInfo->push_time,
				);			
				$array_result['data'][] = $arr_data;		
			}
		} else {
			$array_result['data'] = array();
		}
	}

	// Action - remove notification
	if($section=="remove_notification"){

		if(empty($_POST['id'])){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Notification ID is missing";
		} else {
			$result = $wpdb->get_results("SELECT * FROM `bsb_notification_center` WHERE id = '".$_POST['id']."' AND status = 'Y' LIMIT 1");

			if(count($result)==0){
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Notification ID is invalid";
			} else {
				$wpdb->update('bsb_notification_center', array( 'status' => 'N' ), array( 'id' => $_POST['id'] ) );
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Message is removed";					
			}

		}
	}	


	if($section=="scan_order_qrcode_confirm"){

		$code = $_POST['code'];

		if (!empty($code)) {
						
			parse_str($code, $output);	

			if(isset($_POST['user_id']) && !empty($_POST['user_id'])){
				
				$user = new WC_Customer( $_POST['user_id'] );
				$is_satff = $user->get_role()=="customer"?false:true;
				
				if(!$is_staff){
					
					if(isset($output['key']) && !empty($output['key'])){

						$order_id = wc_get_order_id_by_order_key($output['key']);
						
						if($order_id!=0){
							//$order = new WC_Order( $order_id );					
							if(isset($output['action']) && !empty($output['action'])){
								if(in_array($output['action'], array('pending','processing','completed','cancelled','shipping'))){							
									$order = new WC_Order( $order_id );
									$currentStatusIndex = get_order_status_index($order_id);									

									if($output['action']=='completed'){

										$array_result['success'] = true;
										$array_result['statusCode'] = 200;
										$array_result['code'] = "Success";
										$array_result['current_status_index'] = $currentStatusIndex;
										$array_result['result_status_index'] = intval(4);								

									} elseif($output['action']=='shipping'){
										$array_result['success'] = true;
										$array_result['statusCode'] = 200;
										$array_result['code'] = "Success";
										$array_result['current_status_index'] = $currentStatusIndex;
										$array_result['result_status_index'] = intval(3);
									}

								} else {
									$array_result['success'] = false;
									$array_result['statusCode'] = 200;
									$array_result['code'] = "Fail";
									$array_result['message'] = "Invalid Action";
									$array_result['current_status_index'] = intval(0);
									$array_result['result_status_index'] = intval(0);								
								}

							} else {
								$array_result['success'] = false;
								$array_result['statusCode'] = 200;
								$array_result['code'] = "Fail";
								$array_result['message'] = "Invalid Action";
								$array_result['current_status_index'] = intval(0);
								$array_result['result_status_index'] = intval(0);							
							}
							

						} else {
							$array_result['success'] = false;
							$array_result['statusCode'] = 200;
							$array_result['code'] = "Fail";
							$array_result['message'] = "Invalid Order Key";	
							$array_result['current_status_index'] = intval(0);
							$array_result['result_status_index'] = intval(0);
						}
						
					} else {
						$array_result['success'] = false;
						$array_result['statusCode'] = 200;
						$array_result['code'] = "Fail";
						$array_result['message'] = "Invalid Order Key";	
						$array_result['current_status_index'] = intval(0);
						$array_result['result_status_index'] = intval(0);
					} 
				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Fail";
					$array_result['message'] = "Unauthorized Access";	
					$array_result['current_status_index'] = intval(0);
					$array_result['result_status_index'] = intval(0);										
				}
				
			} else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Invalid User ID";	
				$array_result['current_status_index'] = intval(0);
				$array_result['result_status_index'] = intval(0);								
			}
		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Invalid Code";	
			$array_result['current_status_index'] = intval(0);
			$array_result['result_status_index'] = intval(0);			
		}
	}

	
	if($section=="scan_order_qrcode"){

		$code = $_POST['code'];

		if (!empty($code)) {
						
			parse_str($code, $output);	
			
			if(isset($output['key']) && !empty($output['key'])){

				$order_id = wc_get_order_id_by_order_key($output['key']);
				if($order_id!=0){
					//$order = new WC_Order( $order_id );
					if(isset($output['action']) && !empty($output['action'])){
						if(in_array($output['action'], array('pending','processing','completed','cancelled','shipping'))){							
							$order = new WC_Order( $order_id );
							$order_number = $order->get_order_number();
							$customer_id = $order->get_customer_id();
							$device_token = get_user_meta($customer_id, "device_token", true);

							if($output['action']=='completed'){
								if(!$order->has_status('completed') && !$order->has_status('cancelled')){
									
									$order->update_status("wc-completed", 'Completed', TRUE);

									$title = "Bread Secret Bakery (TEST)";
									$message = "Order #".$order_number." is completed";			
									$type = "update_order";
									$ref_id = $order_id;
									$wpdb->insert(
										'bsb_notification_center', 
										array(
											'hash'=>wp_generate_uuid4(),
											'user_id'=>$customer_id,
											'title'=>$title,
											'message'=>$message,
											'device_token'=>$device_token,
											'type'=>$type,	
											'reference_id'=>$ref_id
										)
									);		
									$notification_id = $wpdb->insert_id;		
									initPushNotificationAppDevice($title, $message, $device_token, $type, $ref_id, $notification_id);

									$array_result['success'] = true;
									$array_result['statusCode'] = 200;
									$array_result['code'] = "Success";
									$array_result['message'] ="Order is marked as completed";
									$array_result['id'] = intval($order_id);
								} else {
									$array_result['success'] = false;
									$array_result['statusCode'] = 200;
									$array_result['code'] = "Fail";
									$array_result['message'] = "Order cannot be completed";
								}
							} elseif($output['action']=='shipping'){
								update_post_meta($order_id, "packed", "1");

								$title = "Bread Secret Bakery (TEST)";
								$message = "Order #".$order_number." is ready and delivering to destination";
								$type = "update_order";
								$ref_id = $order_id;
								$wpdb->insert(
									'bsb_notification_center', 
									array(
										'hash'=>wp_generate_uuid4(),
										'user_id'=>$customer_id,
										'title'=>$title,
										'message'=>$message,
										'device_token'=>$device_token,
										'type'=>$type,	
										'reference_id'=>$ref_id
									)
								);		
								$notification_id = $wpdb->insert_id;		
								initPushNotificationAppDevice($title, $message, $device_token, $type, $ref_id, $notification_id);


								$array_result['success'] = true;
								$array_result['statusCode'] = 200;
								$array_result['code'] = "Success";
								$array_result['message'] ="Order is marked as shipping";
								$array_result['id'] = intval($order_id);								

							}

						} else {
							$array_result['success'] = false;
							$array_result['statusCode'] = 200;
							$array_result['code'] = "Fail";
							$array_result['message'] = "Invalid Action";
						}

					} else {
						$array_result['success'] = false;
						$array_result['statusCode'] = 200;
						$array_result['code'] = "Fail";
						$array_result['message'] = "Invalid Action";
					}

				} else {
					$array_result['success'] = false;
					$array_result['statusCode'] = 200;
					$array_result['code'] = "Fail";
					$array_result['message'] = "Invalid Order Key";	
				}

			} else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Invalid Order Key";	
			}

		} else {
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Invalid Code";	
		}
		

	}


	if($section=="banner_list"){

		$data = array();

		// for ingredient page
		$ingredient_en = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_title = 'Ingredients' AND post_status = 'publish' AND post_type = 'page'");

		$id_en = $ingredient_en[0]->ID;

		$content_json_en = get_post_meta($id_en, "tipi_builder_data", true);

		$arr_content_en = json_decode($content_json_en, true);
		
		$data_en = array();

		foreach($arr_content_en as $idx_en=>$content_obj_en){
			
			if($idx_en%2==0){
				$data[] = array(
					"type"=>"page", 
					"image"=>$content_obj_en['img_bg'], 
					"label"=>$content_obj_en['label'], 
					"text"=>strip_tags($content_obj_en['cta_content']), 
					"product_id"=>0
				);
			}
			
		}

		$id_zh = 0;
		$trid = $sitepress->get_element_trid($id_en, 'post_product');
		$translations = $sitepress->get_element_translations($trid, 'product');
		foreach( $translations as $lang=>$translation){
			if($translation->language_code == "zh-hant")
				$id_zh = $translation->element_id;
		}				
		
		$content_json_zh = get_post_meta($id_zh, "tipi_builder_data", true);

		$arr_content_zh = json_decode($content_json_zh, true);
		
		$data_zh = array();
		
		foreach($arr_content_zh as $idx_zh=>$content_obj_zh){
			
			if($idx_zh%2==0){			
				
				$idx = $idx_zh / 2;

				$data[$idx]['label_zh'] = $content_obj_zh['label']; 
				$data[$idx]['text_zh'] = strip_tags($content_obj_zh['cta_content']);
			}
			
		}	
		

		

		// for featured product 
		/*
		$products = wc_get_products(['featured' => true]);		
		foreach($products as $product) {			
			

			$page = get_page($product->get_id());
			if ($page->post_status == 'publish') {
				$image = wp_get_attachment_image_src( get_post_thumbnail_id( $product->get_id() ), 'single-post-thumbnail' );
				if(isset($image[0]) && $image[0]!=""){	
					
					$zh_post_id = 0;
					$trid = $sitepress->get_element_trid($product->get_id(), 'post_product');
					$translations = $sitepress->get_element_translations($trid, 'product');
					foreach( $translations as $lang=>$translation){
						if($translation->language_code == "zh-hant")
							$zh_post_id = $translation->element_id;
					}				
	
					$data[] = array("type"=>"product", "image"=>$image[0], "text"=>$product->get_name(), "text_zh"=>get_the_title($zh_post_id), "ref_id"=>$product->get_id());
				}
		  
			}	
			
		}
		*/

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = count($data)." records returned";
		$array_result['data'] = $data;

	}

	if($section=="news_list"){

		$data = array();

		$args = array(
			'post_type' =>  'post',
			'category' => 'news',
			'post_status' => "publish",
			'numberposts'    => -1
		); 
		
		$news = get_posts( $args );

		foreach($news as $idx=>$news_obj){
			if($idx%2==0){

				$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($news_obj->ID),'single-post-thumbnail');
				
				$data[] = array(				
					"image"=>$featured_image[0], 
					"title_zh"=>$news_obj->post_title,
					"content_zh"=>str_replace("\n\n", "<br><br>", preg_replace('/<!--(.|\s)*?-->/', '', $news_obj->post_content))
					
					//str_replace("\n", "<br>",$news_obj->post_content)
				);			
			} else {

				$ids = $idx / 2;
				$data[$ids]['title'] = $news_obj->post_title;
				$data[$ids]['content'] = str_replace("\n\n", "<br><br>",preg_replace('/<!--(.|\s)*?-->/', '', $news_obj->post_content));

			}
		}


		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = count($data)." records returned";
		$array_result['data'] = $data;		

	}


	if($section=="instruction_list"){

		$type = $_GET['type'];

		if(!empty($type)){
			$result = $wpdb->get_results("SELECT * FROM `custom_instruction` WHERE type = '".$type."' AND status = 1");

			$data = array();
			foreach($result as $faq) {
				$data[] = array(
					"id"=>intval($faq->id),
					"question"=>$faq->question,
					"question_zh"=>$faq->question_zh,
					"answer"=>$faq->answer,
					"answer_zh"=>$faq->answer_zh
				);			
			}
	
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = count($data)." records returned";
			$array_result['data'] = $data;

		} else {

			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Input Type";
			$array_result['data'] = $data;			
			
		}

	}


	if($section=="company_contact"){

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "Success";
		$array_result['data'] = array(
			"name"=>get_custom_value("contact_company_name"), 
			"email"=>get_custom_value("contact_company_email"), 
			"phone"=>get_custom_value("contact_company_phone"), 
			"whatsapp"=>get_custom_value("contact_company_whatsapp"),
			"address"=>get_custom_value("contact_company_address"),
			"address_zh"=>get_custom_value("contact_company_address_zh"),			
			"business_hour"=>get_custom_value("contact_company_business_hour"),
			"business_hour_zh"=>get_custom_value("contact_company_business_hour_zh"),
			"pickup_time"=>get_custom_value("contact_company_order_pickup_time"),
			"pickup_time_zh"=>get_custom_value("contact_company_order_pickup_time_zh"),
			"extra_info"=>get_custom_value("contact_company_extra_info"),
			"extra_info_zh"=>get_custom_value("contact_company_extra_info_zh")
		);

	}	


	if($section=="leave_message"){

		if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['subject']) || empty($_POST['message'])){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Either name, email, subject or message is empty";
		} else {

			define("MAIL_HOST","mail.winghung.com");
			define("MAIL_PORT","2525");
			define("MAIL_USER","admin@winghung.com");
			define("MAIL_PASSWORD","IdRbc(0wxD4#");
			define("MAIL_ADMIN","admin@winghung.com");
			define("MAIL_SENDER","Bread Secret Bakery");
			define("MAIL_TO","samiel_tsang@winghung.com");
			define("MAIL_CC","benton_tsang@winghung.com");

			date_default_timezone_set('Etc/UTC');
			require_once('/var/www/html/breadsecret.com/vendor/PHPMailer-master/PHPMailerAutoload.php');

			$subject = "[Breadsecret] INCOMING MESSAGE FROM CONTACT US FORM";
			$ordHead  = "<style type='text/css'>
			.tg  {border-collapse:collapse; border: 1px solid black; width:100%}
			.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;overflow:hidden;word-break:normal;border-color:#aaa;color:#333;background-color:#fff;}
			.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:0px;overflow:hidden;word-break:normal;border-color:#aaa;color:#fff;background-color:#00bbd9;}
			.tg .tg-j2zy{background-color:#eee;vertical-align:top}
			.tg .tg-baqh{text-align:center;vertical-align:top}
			.tg .tg-zczf{background-color:#eee;text-align:right;vertical-align:top}
			.tg .tg-lqy6{text-align:right;vertical-align:top}
			.tg .tg-yw4l{vertical-align:top}</style>";
			
			$message = $ordHead;					   
			$message .= "<table class='tg' border='1'>";
			
			$message .= "<tr>";
				$message .= "<th colspan='2' class='tg-baqh'>Message Content</th>";
			$message .= "</tr>";
			

			$message .= "<tr>";
					$message .= "<td class='tg-yw4l'>Date:</td>";
					$message .= "<td class='tg-yw4l'>".date("Y-m-d H:i:s")."</td>";	
				$message .= "</tr>";	

				$message .= "<tr>";
					$message .= "<td class='tg-yw4l'>Name:</td>";
					$message .= "<td class='tg-yw4l'>".$_POST['name']."</td>";	
				$message .= "</tr>";	

				$message .= "<tr>";
					$message .= "<td class='tg-yw4l'>Email:</td>";
					$message .= "<td class='tg-yw4l'>".$_POST['email']."</td>";	
				$message .= "</tr>";
				
				$message .= "<tr>";
					$message .= "<td class='tg-yw4l'>Subject:</td>";
					$message .= "<td class='tg-yw4l'>".$_POST['subject']."</td>";	
				$message .= "</tr>";
				
				$message .= "<tr>";
					$message .= "<td class='tg-yw4l'>Message:</td>";
					$message .= "<td class='tg-yw4l'>".$_POST['message']."</td>";	
				$message .= "</tr>";

			$message .= "<tr>";
				$message .= "<td colspan='2' class='tg-yw4l'><b>www.breadsecret.com</b></td>";														
				$message .= "</tr>";	

			$message .= "</table>";




			$mail = new PHPMailer;
			$mail->CharSet = 'UTF-8';
			$mail->isSMTP();
			$mail->SMTPDebug = 0;
			$mail->Debugoutput = 'html';
			$mail->Host = MAIL_HOST;
			$mail->Port = MAIL_PORT;
			$mail->SMTPAuth = true;
			$mail->Username = MAIL_USER;
			$mail->Password = MAIL_PASSWORD;					  
			$mail->setFrom(MAIL_ADMIN, MAIL_SENDER);
			//$mail->addAttachment($path.$filename.'.xls');
			$mail->addAddress(MAIL_TO, MAIL_TO);		
			$mail->addCC(MAIL_CC, MAIL_CC);		
			//$mail->addAddress($email, $email);
			//$mail->addCC($cc, $cc);
			// $mail->addBCC($bcc, $bcc);
			$mail->Subject = $subject;
			$mail->isHTML(true);
			$mail->Body = $message;
			$mail->AltBody = $message;
			if($mail->send()){
				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Message Sent. Thank you!";
			} else {
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Message cannot be sent. Please try again later";
			}

		}

	}


	if ($section=="update_default_language") {

		if(empty($_POST['user_id']) || empty($_POST['language'])){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "Unable to update default language. Please try again later";
		} else {
			update_user_meta($_POST['user_id'], "default_language", trim($_POST['language']));
			$array_result['success'] = true;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Success";
			$array_result['message'] = "Default language is updated to ".$_POST['language'];
		}		

	}



	if ($section=="check_availability") {
		
		$product_id = $_GET['product_id'];
		$product = wc_get_product($product_id);
		$sku = $product->get_sku();
		$stock_sku = get_master_sku($sku);

		$unit_qty = 1;
		if(has_master_sku($sku)){			
			$unit_qty = get_master_sku_unit_qty($sku);					
		}
		//echo $unit_qty;

		$date = date("Y-m-d");
		if(date('H', time()) >= 16){
			$date = date('Y-m-d',  strtotime("+1 day"));
		}
		$date_list = array();
		$info = get_custom_calendar_date_info($date);
		$max_date = $info['maxdate'];
		$holiday_list = get_holiday_list();
		
		for($i=strtotime($date); $i<=strtotime($max_date); $i+=86400){

			if((date("N", $i)!=7) && !in_array(date("Y-m-d", $i), $holiday_list) ) {
				
				$stock_remain = get_sku_stock_by_date($stock_sku,date('Y-m-d', $i));				
				
				if(($stock_remain*10)%($unit_qty*10)==0){
					$display_stock_qty = floatval($stock_remain/$unit_qty);
				} else {
					$display_stock_qty = floatval(floor($stock_remain/$unit_qty));
				}				
				
				$seq = get_sequence($stock_sku, date('Y-m-d', $i));						
				
				if($display_stock_qty>0){
					if($seq == 2 || $seq == 1)
						$date_list[] = array("date"=>date("Y-m-d", $i), "stock_qty"=>$display_stock_qty);
				}
			}

		}

		$array_result['data'] = $date_list;		


	}	

	if ($section=="compare_availability") {
				
		$arr_product = json_decode($_POST['products'],true);
		//$arr_product = array(198253,199689,669);
		$date = date("Y-m-d");
		if(date('H') >= 16){
			$date = date('Y-m-d',  strtotime("+1 day"));
		}
		$info = get_custom_calendar_date_info($date);
		$max_date = $info['maxdate'];
		$holiday_list = get_holiday_list();

		$data_content = array();

		foreach($arr_product as $product_id){		
		
			$product = wc_get_product($product_id);
			$sku = $product->get_sku();
			$stock_sku = get_master_sku($sku);

			$unit_qty = 1;
			if(has_master_sku($sku)){			
				$unit_qty = get_master_sku_unit_qty($sku);					
			}
			//echo $unit_qty;

			$date_list = array();
			
			for($i=strtotime($date); $i<=strtotime($max_date); $i+=86400){

				if((date("N", $i)!=7) && !in_array(date("Y-m-d", $i), $holiday_list) ) {
					
					$stock_remain = get_sku_stock_by_date($stock_sku,date('Y-m-d', $i));				
					
					if(($stock_remain*10)%($unit_qty*10)==0){
						$display_stock_qty = floatval($stock_remain/$unit_qty);
					} else {
						$display_stock_qty = floatval(floor($stock_remain/$unit_qty));
					}				
					
					$seq = get_sequence($stock_sku, date('Y-m-d', $i));						
					
					if($display_stock_qty>0){
						if($seq == 2 || $seq == 1)
							$date_list[] = array("date"=>date("Y-m-d", $i), "stock_qty"=>$display_stock_qty);
					}
				}

			}

			$data_content[] = array("product_id"=>$product_id, "available_date" => $date_list);
			
		}		

		$array_result['data'] = $data_content;

	}	


	if ($section=="release_stock") {

		if(empty($_POST['order_id']) || empty($_POST['order_id'])){
			$array_result['success'] = false;
			$array_result['statusCode'] = 200;
			$array_result['code'] = "Fail";
			$array_result['message'] = "ID is missing";
		} else {
			$order_id = $_POST['order_id'];
			$order = wc_get_order($_POST['order_id']);			
			
			if(!$order){
				$array_result['success'] = false;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Fail";
				$array_result['message'] = "Invalid Order";

			} else {

				$type = "App";
				$action = "Release Stock";
				
				$delivery_date = get_post_meta( $order_id, 'delivery_date', true );
				$adjust_stock = get_post_meta($order_id, 'adjust_stock', true);	
				$stock_out = get_post_meta($order_id, 'stock_out', true);	
				
				foreach ( $order->get_items() as $item_id => $item ) {
			
					$product = $item->get_product();
					$sku = $product->get_sku();	
					
					$stock_sku = get_master_sku($sku);
					$unit_qty = 1;
					if(has_master_sku($sku)){
						$description = $product->get_name(); 
						$unit_qty = get_master_sku_unit_qty($sku);	
					}else{			
						$variation_id = $item->get_variation_id();								
						$product = wc_get_product(wc_get_product_id_by_sku($sku));
						
						if($variation_id!=0){
							$description = get_name_from_variation_id($product->get_name(),$variation_id);
							$unit_qty = get_variation_unit_qty($variation_id);
						}else{					
							$description = $product->get_name(); // make a unique key
							$unit_qty = 1;
						}	
					}
						
				   $quantity = $item->get_quantity()*$unit_qty;
				   $qty_from = get_sku_stock_by_date($stock_sku, $delivery_date);
				   $qty_to = $qty_from + $quantity;
				   if($adjust_stock=="Y") {
						   if($stock_out == 1) {
							$sql_update = "UPDATE sku_stock SET `".$stock_sku."` = '".$qty_to."' WHERE stock_date = '".sanitize_text_field($delivery_date)."' LIMIT 1";
							if($wpdb->query($sql_update)){
								write_log($delivery_date, $action, $type, $order_id, $stock_sku, $description, $qty_from, $qty_to, get_current_user_id(), get_client_ip(), $sql_update); 		
								update_post_meta($order_id, 'stock_out','0');
							}
						}	   
				   }
				}

				$array_result['success'] = true;
				$array_result['statusCode'] = 200;
				$array_result['code'] = "Success";
				$array_result['message'] = "Stock is released";

			}
		}		
	}

	if($section=="TEST"){
		$stock_sku = $_GET['stock_sku'];
		$date = $_GET['date'];
		$a = get_product_sorting_info($stock_sku, $date);
		echo "<pre>";
			var_dump($a);
		echo "</pre>";
	}
	
	if($section=="cart_item_detail"){
		/*
		echo "<pre>";
			print_r($_POST['cart']);
		echo "</pre>";
		*/
		$arr_content = array();

		foreach($_POST['cart'] as $cart_item){

			$arr_product_info = array();
			$product_list = json_decode($cart_item['products'],true);
			foreach($product_list as $product_id){
				$productInfo = get_product_detail($product_id);
				$arr_product_info[] = $productInfo;
			}

			$arr_content[] = array("date"=>$cart_item['date'], "products"=>$arr_product_info);

		}

		$array_result['success'] = true;
		$array_result['statusCode'] = 200;
		$array_result['code'] = "Success";
		$array_result['message'] = "Stock is released";
		$array_result['data'] = $arr_content;
		
	}	

}
echo json_encode($array_result);

?>