Esempio n. 1
0
                }
                restore_current_blog();
            }
        }
    } else {
        $allOrders = $wpdb->get_results("SELECT order_ini FROM " . $wpdb->prefix . $this->pluginOrderTable . " WHERE payment_status='COMPLETED' ");
    }
    if (is_array($allOrders) && count($allOrders) > 0) {
        foreach ($allOrders as $orders) {
            /**add to total ordered amount of shown items**/
            $orderDet = maybe_unserialize($orders->order_ini);
            $totalPriceAll += (double) $orderDet['total'];
            /*******************************************/
        }
    }
    $obj['totals'] = __('total all orders', $this->pluginLocale) . ': ' . $this->pluginOptions['order']['currency_symbol'] . ' ' . wppizza_output_format_price($totalPriceAll) . '';
    print "" . json_encode($obj) . "";
    exit;
}
/********************************************
*
*
*	[order history -> update order status]
*
*
********************************************/
if ($_POST['vars']['field'] == 'orderstatuschange' && isset($_POST['vars']['id']) && $_POST['vars']['id'] >= 0) {
    global $wpdb;
    /**distinct blogid set**/
    if ($_POST['vars']['blogid'] != '') {
        $wpdb->prefix = $wpdb->prefix . $_POST['vars']['blogid'] . '_';
function wppizza_order_summary($session, $options, $module = null, $ajax = null)
{
    global $blog_id;
    /**allow filtering of options and session**/
    $session = apply_filters('wppizza_filter_order_summary_session', $session);
    $options = apply_filters('wppizza_filter_order_summary_options', $options);
    /***************************************************
    		[in i some vars if undefined]
    	***************************************************/
    if (!isset($session['total_price_calc_delivery'])) {
        $session['total_price_calc_delivery'] = 0;
    }
    /****************************************************
    		[set the original free delivery min_total value as a var
    		to be able to compare against further down and deisplay appropriate
    		text if min order value has also been set
    	******************************************************/
    $orderMinTotalSet = $options['order']['delivery']['minimum_total']['min_total'];
    /****************************************************
    		[get currency]
    	****************************************************/
    $summary['currency'] = '' . $options['order']['currency_symbol'] . '';
    /*do not add any spans or anything else to this as it gets stored in the db */
    $summary['currencyiso'] = '' . wppizza_validate_letters_only($options['order']['currency'], 3) . '';
    //strip any -alt identifiers (serbian currency for example has 2 display options but the same ISO code)
    /****************************************************
    		[set currency positions]
    	****************************************************/
    $summary['currency_left'] = $summary['currency'] . ' ';
    $summary['currency_right'] = '';
    if ($options['layout']['currency_symbol_position'] == 'right') {
        /*right aligned*/
        $summary['currency_left'] = '';
        $summary['currency_right'] = ' ' . $summary['currency'];
    }
    /****************************************************
    		[hide decimals?]
    	****************************************************/
    $optionsDecimals = $options['layout']['hide_decimals'];
    /****************************************************
    		[get cart items as grouped array]
    	****************************************************/
    $cartItems = array();
    //ini array
    $cartItemsCount = 0;
    //count all items
    $groupedItems = array();
    //ini array
    $summary['items'] = array();
    //ini array
    /**lets group items by id and sizes***/
    foreach ($session['items'] as $groupid => $groupitems) {
        foreach ($groupitems as $v) {
            $excludeFromCount = false;
            /**allow items to be excluded from count when calculating delivery prices per item**/
            $excludeFromCount = apply_filters('wppizza_filter_order_summary_exclude_item_from_count', $excludeFromCount, $v);
            if (!$excludeFromCount) {
                $cartItemsCount++;
                //advance counter if not excluded (in case we want to not charge per item on this )
            }
            /**really only for legacy reasons, future versions will only have extend key**/
            if (!isset($v['additionalinfo'])) {
                $v['additionalinfo'] = array();
            }
            if (!isset($v['extend'])) {
                $v['extend'] = array();
            }
            if (!isset($v['extenddata'])) {
                $v['extenddata'] = array();
            }
            /*if not set , add current*/
            if (!isset($v['blogid'])) {
                $v['blogid'] = $blog_id;
            }
            $cartItems['' . $groupid . ''][] = array('sortname' => $v['sortname'], 'size' => $v['size'], 'sizename' => $v['sizename'], 'printname' => $v['printname'], 'price' => $v['price'], 'additionalinfo' => $v['additionalinfo'], 'extend' => $v['extend'], 'extenddata' => $v['extenddata'], 'postId' => $v['id'], 'blogid' => $v['blogid']);
            /**conditional just used to not break other extensions/plugins that have not been updated yet to add selected category id.*/
            if (isset($v['catIdSelected'])) {
                $catIdSelected['' . $groupid . ''] = $v['catIdSelected'];
            } else {
                $catIdSelected['' . $groupid . ''] = '';
            }
        }
    }
    foreach ($cartItems as $k => $v) {
        $groupedItems[$k] = array('sortname' => $cartItems[$k][0]['sortname'], 'size' => $cartItems[$k][0]['size'], 'sizename' => $cartItems[$k][0]['sizename'], 'printname' => $cartItems[$k][0]['printname'], 'price' => $cartItems[$k][0]['price'], 'count' => count($cartItems[$k]), 'total' => count($cartItems[$k]) * $cartItems[$k][0]['price'], 'additionalinfo' => $cartItems[$k][0]['additionalinfo'], 'extend' => $cartItems[$k][0]['extend'], 'extenddata' => $cartItems[$k][0]['extenddata'], 'postId' => $cartItems[$k][0]['postId'], 'catIdSelected' => $catIdSelected[$k], 'blogid' => $cartItems[$k][0]['blogid']);
    }
    asort($groupedItems);
    /**output items sorted by name and size**/
    foreach ($groupedItems as $k => $v) {
        /*in a multisite setup we need to sitch to the right blog if necessary**/
        if (is_multisite() && $v['blogid'] != $blog_id) {
            switch_to_blog($v['blogid']);
        }
        /*get categories**/
        $catObj = get_the_terms($v['postId'], WPPIZZA_TAXONOMY);
        /*restore blog if needed*/
        if (is_multisite() && $v['blogid'] != $blog_id) {
            restore_current_blog();
        }
        /*get categories**/
        $catObj = get_the_terms($v['postId'], WPPIZZA_TAXONOMY);
        $catArray = json_decode(json_encode($catObj), true);
        /*get meta value**/
        $objMeta = get_post_meta($v['postId'], WPPIZZA_SLUG);
        $taxRate = $options['order']['item_tax'];
        // check if we are using alt tax value
        if (!empty($objMeta[0]['item_tax_alt'])) {
            $taxRate = $options['order']['item_tax_alt'];
        }
        /*******************************************************************************************
        			if other extensions have yet to add selcatid, just add the first one
        			the item is categorised in.
        			90% of the time there will only be one anyway, so this would be correct.
        			worst case scenario, an unexpected (although not wrong) category will be displayed
        			all of this is only relevant anyway if "show category for emails etc" is enabled in layout
        		*******************************************************************************************/
        if ($v['catIdSelected'] == '') {
            /*make sure a category was also actually assigned*/
            if (is_array($catArray)) {
                $firstCat = reset($catArray);
                $v['catIdSelected'] = $firstCat['term_id'];
            } else {
                $v['catIdSelected'] = '';
            }
        }
        $summary['items'][$k] = array('name' => $v['printname'], 'count' => $v['count'], 'size' => $v['sizename'], 'price' => wppizza_output_format_price($v['price'], $optionsDecimals), 'pricetotal' => wppizza_output_format_price($v['total'], $optionsDecimals), 'categories' => $catArray, 'taxrate' => $taxRate, 'additionalinfo' => $v['additionalinfo'], 'extend' => $v['extend'], 'extenddata' => $v['extenddata'], 'postId' => $v['postId'], 'catIdSelected' => $v['catIdSelected'], 'blogid' => $v['blogid']);
    }
    /****************************************************
    		[if ajax request get items from template to keep formatting consistent]
    	****************************************************/
    if ($ajax) {
        $summary['itemsajax'] = do_shortcode('[wppizza type="cart" request="ajax"]');
    }
    /**********************************
    		[discounts]
    	**********************************/
    /** no discount**/
    $discountLabel = '';
    $discountValue = '';
    $discountValuePrint = '';
    if ($options['order']['discount_selected'] == 'none') {
        $discountApply = 0;
    }
    /*loose php notice**/
    $session['total_price_calc_discount'] = isset($session['total_price_calc_discount']) ? $session['total_price_calc_discount'] : $session['total_price_items'];
    /** percentage discount**/
    if ($options['order']['discount_selected'] == 'percentage') {
        /**sort highest to lowest and check if it aplies, if it does, apply and stop loop (only want to appply one!**/
        $discountApply = 0;
        /**get most relevant discount to apply to price***/
        rsort($options['order']['discounts']['percentage']['discounts']);
        foreach ($options['order']['discounts']['percentage']['discounts'] as $k => $v) {
            if ($session['total_price_calc_discount'] >= $v['min_total']) {
                $discountApply = round($session['total_price_calc_discount'] / 100 * $v['discount'], 2);
                break;
            }
        }
        /**get all available discounts to display***/
        sort($options['order']['discounts']['percentage']['discounts']);
        foreach ($options['order']['discounts']['percentage']['discounts'] as $k => $v) {
            if ($v['discount'] > 0) {
                // && $v['min_total']>0
                $summary['pricing_discounts'][] = "" . $options['localization']['spend']['lbl'] . " <span>" . $summary['currency_left'] . "" . wppizza_output_format_price($v['min_total'], $optionsDecimals) . "" . $summary['currency_right'] . "</span> " . $options['localization']['save']['lbl'] . " <span>" . $v['discount'] . "%</span>";
            }
        }
    }
    /** value discount**/
    if ($options['order']['discount_selected'] == 'standard') {
        /**sort highest to lowest and check if it aplies, if it does, apply and stop loop (only want to appply one!**/
        $discountApply = 0;
        /**get most relevant discount to apply to price***/
        rsort($options['order']['discounts']['standard']['discounts']);
        foreach ($options['order']['discounts']['standard']['discounts'] as $k => $v) {
            if ($session['total_price_calc_discount'] >= $v['min_total']) {
                $discountApply = $v['discount'];
                break;
            }
        }
        /**get all available discounts to display***/
        sort($options['order']['discounts']['standard']['discounts']);
        foreach ($options['order']['discounts']['standard']['discounts'] as $k => $v) {
            if ($v['discount'] > 0) {
                //&& $v['min_total']>0
                $summary['pricing_discounts'][] = "" . $options['localization']['spend']['lbl'] . " <span>" . $summary['currency_left'] . " " . wppizza_output_format_price($v['min_total'], $optionsDecimals) . "" . $summary['currency_right'] . "</span> " . $options['localization']['save']['lbl'] . " <span>" . $summary['currency_left'] . "" . wppizza_output_format_float($v['discount']) . "" . $summary['currency_right'] . "</span>";
            }
        }
    }
    /***self pickup discount added to other discounts (if any)**/
    if ($options['order']['order_pickup_discount'] > 0 && isset($session['selfPickup'])) {
        $discountApply = $discountApply + $session['total_price_calc_discount'] / 100 * $options['order']['order_pickup_discount'];
    }
    /**allow filtering of discounts**/
    $discountApply = apply_filters('wppizza_filter_discount', $discountApply, $session, $module);
    if (isset($discountApply) && $discountApply > 0) {
        $discountLabel = $options['localization']['discount']['lbl'];
        $discountValue = wppizza_output_format_float($discountApply);
        $discountValuePrint = wppizza_output_format_price($discountValue, $optionsDecimals);
    }
    /**********************************
    				[delivery]
    			**********************************/
    $deliveryLabel = $options['localization']['free_delivery']['lbl'];
    //initialize var
    $deliveryCharges = '';
    if ($options['order']['delivery_selected'] == 'no_delivery') {
        /*delivery disabled*/
        $deliveryCharges = '';
        /*set to empty to hide*/
        $deliveryLabel = '';
        /*set to empty to hide*/
        /*set flag for 'no delivery'*/
        $summary['no_delivery'] = 1;
        $summary['self_pickup_enabled'] = 1;
        $summary['selfPickup'] = 2;
        /**set to >1 to not display self pickup note/text in emails and order page*/
        /**disable self pickup checkboxes*/
        $options['order']['order_pickup'] = false;
    }
    if ($options['order']['delivery_selected'] == 'standard') {
        //standard (i.e. fixed delivery charges)
        /**delivery settings to display with discount options somewhere*/
        if ($options['order']['delivery']['standard']['delivery_charge'] > 0) {
            $deliveryLabel = $options['localization']['delivery_charges']['lbl'];
            $deliveryCharges = wppizza_output_format_float($options['order']['delivery']['standard']['delivery_charge']);
        }
    }
    if ($options['order']['delivery_selected'] == 'minimum_total') {
        //minimum total
        if ($options['order']['delivery']['minimum_total']['deliver_below_total']) {
            if ($session['total_price_calc_delivery'] < $options['order']['delivery']['minimum_total']['min_total']) {
                $deliveryLabel = $options['localization']['delivery_charges']['lbl'];
                $deliveryCharges = wppizza_output_format_float($options['order']['delivery']['minimum_total']['min_total'] - $session['total_price_calc_delivery']);
            }
        }
        /**fixed price set if below free delivery: overrides "deliver_below_total" **/
        if ($options['order']['delivery']['minimum_total']['deliverycharges_below_total'] > 0) {
            if ($session['total_price_calc_delivery'] < $options['order']['delivery']['minimum_total']['min_total']) {
                $deliveryLabel = $options['localization']['delivery_charges']['lbl'];
                $deliveryCharges = wppizza_output_format_float($options['order']['delivery']['minimum_total']['deliverycharges_below_total']);
            }
        }
        /**if we are hiding decimals recalc/round delivery charges or we might get rounding errors**/
        if ($deliveryCharges > 0 && $optionsDecimals) {
            $recalc = wppizza_output_format_float($deliveryCharges, 'hidedecimals');
            if ($recalc <= 0) {
                $deliveryLabel = $options['localization']['free_delivery']['lbl'];
                $deliveryCharges = '';
            } else {
                $deliveryCharges = $recalc;
            }
        }
        /**delivery settings to display with discount options somewhere*/
        if ($options['order']['delivery']['minimum_total']['min_total'] > 0) {
            $summary['pricing_delivery'] = "" . $options['localization']['free_delivery_for_orders_of']['lbl'] . " <span>" . $summary['currency_left'] . "" . wppizza_output_format_price($options['order']['delivery']['minimum_total']['min_total'], $optionsDecimals) . "" . $summary['currency_right'] . "</span>";
        } else {
            $summary['pricing_delivery'] = "" . $options['localization']['free_delivery']['lbl'] . "";
        }
    }
    if ($options['order']['delivery_selected'] == 'per_item') {
        /*delivery charges on a per item basis*/
        /**free delivery isset>0**/
        if ($options['order']['delivery']['per_item']['delivery_per_item_free'] > 0) {
            /*value not reached for free delivery*/
            if ($session['total_price_calc_delivery'] < $options['order']['delivery']['per_item']['delivery_per_item_free']) {
                /*number of items*deliverycharges per item*/
                if ($cartItemsCount > 0 && $options['order']['delivery']['per_item']['delivery_charge_per_item'] > 0) {
                    $deliveryCharges = wppizza_output_format_float($cartItemsCount * $options['order']['delivery']['per_item']['delivery_charge_per_item']);
                }
            }
        } else {
            /*no free delivery set (i.e set to 0)*/
            /*number of items*deliverycharges per item*/
            if ($cartItemsCount > 0) {
                $deliveryCharges = wppizza_output_format_float($cartItemsCount * $options['order']['delivery']['per_item']['delivery_charge_per_item']);
            }
        }
        /*label next to delivery charges if>0 otherwise default above->free*/
        if ($deliveryCharges > 0) {
            $deliveryLabel = $options['localization']['delivery_charges']['lbl'];
        }
        /**delivery settings to display with discount options somewhere*/
        if ($options['order']['delivery']['per_item']['delivery_per_item_free'] > 0) {
            $summary['pricing_delivery'] = "" . $options['localization']['delivery_charges_per_item']['lbl'] . " <span>" . $summary['currency_left'] . "" . wppizza_output_format_price($options['order']['delivery']['per_item']['delivery_charge_per_item'], $optionsDecimals) . "" . $summary['currency_right'] . "</span>";
            $summary['pricing_delivery_per_item_free'] = "" . $options['localization']['free_delivery_for_orders_of']['lbl'] . " <span>" . $summary['currency_left'] . "" . wppizza_output_format_price($options['order']['delivery']['per_item']['delivery_per_item_free'], $optionsDecimals) . "" . $summary['currency_right'] . "</span>";
        } else {
            $summary['pricing_delivery'] = "" . $options['localization']['delivery_charges_per_item']['lbl'] . " <span>" . $summary['currency_left'] . "" . wppizza_output_format_price($options['order']['delivery']['per_item']['delivery_charge_per_item'], $optionsDecimals) . "" . $summary['currency_right'] . "</span>";
        }
    }
    /*******************************************
     *	admin enabled self pickup on the frontend
     ******************************************/
    if ($options['order']['order_pickup']) {
        $summary['self_pickup_enabled'] = 1;
        $summary['order_self_pickup'] = $options['localization']['order_self_pickup']['lbl'];
        $summary['order_self_pickup_cart'] = $options['localization']['order_self_pickup_cart']['lbl'];
        $summary['order_page_self_pickup'] = $options['localization']['order_page_self_pickup']['lbl'];
        /*check where we want to display self pickup checkbox*/
        if ($options['order']['order_pickup_display_location'] == 1 || $options['order']['order_pickup_display_location'] == 3) {
            $summary['self_pickup_cart'] = 1;
        }
        if ($options['order']['order_pickup_display_location'] == 2 || $options['order']['order_pickup_display_location'] == 3) {
            $summary['self_pickup_order_page'] = 1;
        }
        $summary['selfPickup'] = 0;
        /*default off*/
        /*customer chose self pickup. set appropriate values in cart*/
        if (isset($session['selfPickup'])) {
            $summary['selfPickup'] = 1;
            /*indicate that self pcikup chosen*/
            $deliveryCharges = 0;
            /*set delivery charges to 0*/
        }
        /**set id for checkbox to see if we have enabled js alerts**/
        if ($options['order']['order_pickup_alert']) {
            $summary['selfPickupId'] = 'wppizza-order-pickup-js';
        } else {
            $summary['selfPickupId'] = 'wppizza-order-pickup-sel';
        }
    }
    /**allow filtering of delivery charges**/
    $deliveryCharges = apply_filters('wppizza_filter_delivery_charges', $deliveryCharges, $session, $options, $module);
    /*******************************************
     *	set min order values (delivery/pickup)
     ******************************************/
    /**minimum order value set but not reached -> on delivery - as long as its not set to $options['order']['delivery_selected']==no_delivery***/
    if (!isset($session['selfPickup']) && $options['order']['delivery_selected'] != 'no_delivery') {
        if ($options['order']['order_min_for_delivery'] > 0 && $options['order']['order_min_for_delivery'] > $session['total_price_calc_delivery']) {
            /*disable place order button**/
            $placeOrderDisabled = true;
            /**set min_total value to be min order for delivery**/
            $options['order']['delivery']['minimum_total']['min_total'] = $options['order']['order_min_for_delivery'];
            /**set min order info txt**/
            $options['localization']['minimum_order']['lbl'] = $options['localization']['minimum_order_delivery']['lbl'];
        }
    }
    /**minimum order value set but not reached -> on pickup or if set to pickup only***/
    if (isset($session['selfPickup']) || $options['order']['delivery_selected'] == 'no_delivery') {
        /**minimum order value set but not reached -> self pickup***/
        if ($options['order']['order_min_for_pickup'] > 0 && $options['order']['order_min_for_pickup'] > 0 && $options['order']['order_min_for_pickup'] > $session['total_price_calc_delivery']) {
            /*disable place order button**/
            $placeOrderDisabled = true;
            /**set min_total value to be min order for pickup**/
            $options['order']['delivery']['minimum_total']['min_total'] = $options['order']['order_min_for_pickup'];
            /**set min order info txt**/
            $options['localization']['minimum_order']['lbl'] = $options['localization']['minimum_order']['lbl'];
        }
    }
    /*************************************************************************
     *
     *
     *	[Taxes]
     *
     *
     *************************************************************************/
    /****************************************************
    				[tax on sum of all items BEFORE discounts. currently not in use]
    			****************************************************/
    $itemTax = 0;
    /**ini as 0**/
    $taxesIncluded = 0;
    /**ini as 0**/
    $summary['taxrate'] = $options['order']['item_tax'];
    /*capture/set taxrate**/
    $summary['taxrate_alt'] = $options['order']['item_tax_alt'];
    /*capture/set alternative taxrate**/
    /**********************************************************
     *
     *	[tax NOT included in set prices]
     *
     **********************************************************/
    if (!$options['order']['taxes_included']) {
        /***********************************************************
         *	as we may have different taxrates on different items
         *	and need to make sure that dicounts - as they are before tax -
         *	are applied correctly, we must calculate the resulting taxrate
         ***********************************************************/
        $calcTaxSum = 0;
        $calcItemsSum = 0;
        foreach ($groupedItems as $giKey => $item) {
            /*
            	taxrate from summary as it does not exist in grouped items yet
            */
            $itemTaxRate = $summary['items'][$giKey]['taxrate'];
            $calcTaxSum += $item['total'] / 100 * $itemTaxRate;
            $calcItemsSum += $item['total'];
        }
        /***if cart is empty, use defaults to avoid division by zero notice***/
        if ($calcItemsSum <= 0) {
            $avgTaxRate = 0;
        } else {
            $avgTaxRate = $calcTaxSum / ($calcItemsSum / 100);
        }
        $summary['taxrate_avg'] = $avgTaxRate;
        /*capture/set average taxrate**/
        /****************************************************
        				[set var for ident later if necessary]
        			****************************************************/
        $summary['tax_applied'] = 'items_only';
        /****************************************************
        				[item tax AFTER discounts]
        			****************************************************/
        if ($options['order']['item_tax'] > 0 || $options['order']['item_tax_alt'] > 0) {
            $summary['tax_enabled'] = 1;
            $totalSales = $session['total_price_items'] - (double) $discountValue;
            /*round up decimals**/
            $itemTax = wppizza_round_up($totalSales / 100 * $avgTaxRate, 2);
            /****************************************************
            				[add tax to shipping too]
            			****************************************************/
            if ($options['order']['shipping_tax']) {
                $summary['tax_applied'] = 'items_and_shipping';
                /*set location*/
            }
            if ($options['order']['shipping_tax'] && $deliveryCharges != '' && (int) $deliveryCharges > 0) {
                // ???????????? check
                $itemTax = wppizza_round_up($totalSales / 100 * $avgTaxRate + $deliveryCharges / 100 * $options['order']['shipping_tax_rate'], 2);
            }
        }
    }
    /**********************************************************
     *
     *	[tax IS included in prices !!!]
     *
     **********************************************************/
    if ($options['order']['taxes_included']) {
        /***********************************************************
         *	as we may have different taxrates on different items
         *	and need to make sure that dicounts - as they are before tax -
         *	are applied correctly, we must calculate the resulting taxrate
         *	
         *	as $summary['items'] might already by formatted to have prices 
         *	with commas, use the prices from grouped items
         ***********************************************************/
        $calcTaxSum = 0;
        $calcItemsSumBeforeTax = 0;
        foreach ($groupedItems as $giKey => $item) {
            /*
            	taxrate from summary as it does not exist in grouped items yet
            */
            $itemTaxRate = $summary['items'][$giKey]['taxrate'];
            $calcTaxItem = $item['total'] / (100 + $itemTaxRate) * $itemTaxRate;
            /*tax on this item**/
            $calcTaxSum += $calcTaxItem;
            $calcItemsSumBeforeTax += $item['total'] - $calcTaxItem;
        }
        /***if cart is empty, use defaults to avoid division by zero notice***/
        if ($calcItemsSumBeforeTax <= 0) {
            $avgTaxRate = 0;
        } else {
            $avgTaxRate = $calcTaxSum / ($calcItemsSumBeforeTax / 100);
        }
        /**we need to recalculate the tax included if we are also applying a discount to the total (alrady taxed) items***/
        if ((double) $discountValue > 0) {
            $calcTaxSum -= $discountValue / (100 + $avgTaxRate) * $avgTaxRate;
            //take the average tax and use it to get the included tax on the discount to substract
        }
        /****************************************************
        				[set var for ident later if necessary]
        			****************************************************/
        $summary['tax_applied'] = 'taxes_included';
        /****************************************************
        				[add tax to items only]
        			****************************************************/
        if ($options['order']['item_tax'] > 0 || $options['order']['item_tax_alt'] > 0) {
            $summary['tax_enabled'] = 1;
            $totalSales = $session['total_price_items'] - (double) $discountValue;
            $taxesIncluded = wppizza_round_up($calcTaxSum, 2);
        }
        /****************************************************
        				[add tax to shipping too]
        			****************************************************/
        if ($options['order']['shipping_tax'] && $deliveryCharges != '' && (int) $deliveryCharges > 0) {
            if ($options['order']['shipping_tax_rate'] > 0) {
                /***avoid division by zero notice***/
                $deliveryChargesTax = $deliveryCharges / (100 + $options['order']['shipping_tax_rate']) * $options['order']['shipping_tax_rate'];
            } else {
                $deliveryChargesTax = 0;
            }
            $taxesIncluded = wppizza_round_up($calcTaxSum + $deliveryChargesTax, 2);
        }
    }
    /*********************************************************************
     *
     *
     *	[surcharges handling charges]
     *
     *
     **********************************************************************/
    /****************************************************
    				[total order before tips]
    			****************************************************/
    $totalOrderBeforeTips = $session['total_price_items'] - (double) $discountValue + (double) $deliveryCharges + (double) $itemTax;
    /****************************************************
    				[surcharges]
    			****************************************************/
    $surcharges = 0;
    $surchargePcVal = $session['gateway-selected']['surchargePc'];
    $surchargeFixedVal = $session['gateway-selected']['surchargeFixed'];
    /*charges percent*/
    if ($surchargePcVal > 0) {
        $surcharges += $totalOrderBeforeTips / 100 * abs($surchargePcVal);
    }
    /*charges fixed*/
    if ($surchargeFixedVal > 0) {
        $surcharges += $surchargeFixedVal;
    }
    /**round*/
    if ($surcharges > 0) {
        $surcharges = wppizza_round_up($surcharges, 2);
    }
    /*********************************************************************
     *
     *
     *	[gratuities]
     *
     *
     **********************************************************************/
    $gratuities = 0;
    if (isset($session['tips']) && $session['tips'] > 0) {
        $gratuities = wppizza_output_format_price($session['tips'], $optionsDecimals);
        $summary['tips'] = array('lbl' => $options['localization']['tips']['lbl'], 'val' => $gratuities);
    }
    /****************************************************
    		[get total order value]
    	****************************************************/
    $totalOrder = $session['total_price_items'] - (double) $discountValue + (double) $deliveryCharges + (double) $itemTax + (double) $gratuities;
    /**if customer chose self pickup, display only label that states self pickup . no need for value**/
    $deliveryValue = wppizza_output_format_price($deliveryCharges, $optionsDecimals);
    $summary['order_value'] = array('item_tax' => array('lbl' => $options['localization']['item_tax_total']['lbl'], 'val' => wppizza_output_format_price($itemTax, $optionsDecimals)), 'taxes_included' => array('lbl' => sprintf('' . $options['localization']['taxes_included']['lbl'] . '', $options['order']['item_tax']), 'val' => wppizza_output_format_price($taxesIncluded, $optionsDecimals)), 'total_price_items' => array('lbl' => $options['localization']['order_items']['lbl'], 'val' => wppizza_output_format_price(wppizza_output_format_float($session['total_price_items']), $optionsDecimals)), 'delivery_charges' => array('lbl' => $deliveryLabel, 'val' => $deliveryValue), 'discount' => array('lbl' => $discountLabel, 'val' => $discountValuePrint), 'total' => array('lbl' => $options['localization']['order_total']['lbl'], 'val' => wppizza_output_format_price(wppizza_output_format_float($totalOrder), $optionsDecimals)));
    /*******************************************************
    		[gateways must handle surcharges themselves and
    		update the db accordingly. However, to display
    		surcharges on gateway change in the orderpage
    		we overwrite the total here for display before
    		actually processing and without adding them to the db]
    	*******************************************************/
    if ($surcharges > 0 && ($module == 'orderpage' || $module == 'confirmationpage')) {
        $summary['order_value']['total'] = array('lbl' => $options['localization']['order_total']['lbl'], 'val' => wppizza_output_format_price(wppizza_output_format_float($totalOrder + $surcharges), $optionsDecimals));
        $summary['order_value']['handling_charge'] = array('lbl' => $options['localization']['order_page_handling']['lbl'], 'val' => wppizza_output_format_price(wppizza_output_format_float($surcharges), $optionsDecimals));
    }
    if ($session['gateway-selected']['surchargeAtCheckout'] && ($module == 'orderpage' || $module == 'confirmationpage')) {
        $summary['order_value']['handling_charge'] = array('lbl' => $options['localization']['order_page_handling']['lbl'], 'str' => $options['localization']['order_page_handling_oncheckout']['lbl']);
    }
    /****************************************************
    		[check if we are open]
    	****************************************************/
    if (!isset($options['opening_times_custom'])) {
        $options['opening_times_custom'] = array();
    }
    /*get rid of some php notices*/
    if (!isset($options['times_closed_standard'])) {
        $options['times_closed_standard'] = array();
    }
    /*get rid of some php notices*/
    $isOpen = wpizza_are_we_open($options['opening_times_standard'], $options['opening_times_custom'], $options['times_closed_standard']);
    /***allow filtering of is_open**/
    $options = apply_filters('wppizza_filter_order_summary_options_open', $options, $isOpen);
    $session = apply_filters('wppizza_filter_order_summary_session_open', $session, $isOpen);
    $isOpen = apply_filters('wppizza_filter_is_open', $isOpen);
    $summary['shopopen'] = $isOpen;
    $summary['button'] = '';
    $summary['nocheckout'] = '';
    if ($isOpen == 0) {
        //closed -> display closed in cart element
        $summary['innercartinfo'] = $options['localization']['closed']['lbl'];
    }
    if ($isOpen == 1) {
        //open
        if (count($summary['items']) <= 0) {
            //open but nothing in cart -> display 'cart is empty' in cart element
            $summary['innercartinfo'] = $options['localization']['cart_is_empty']['lbl'];
        }
        if (count($summary['items']) > 0) {
            //open and stuff in cart -> check min value reached in do/dont display button and info
            if (($options['order']['delivery_selected'] == 'minimum_total' && ($options['order']['delivery']['minimum_total']['deliver_below_total'] || !$options['order']['delivery']['minimum_total']['deliver_below_total'] && $session['total_price_calc_delivery'] >= $options['order']['delivery']['minimum_total']['min_total']) || $options['order']['delivery_selected'] == 'standard' || $options['order']['delivery_selected'] == 'no_delivery' || $options['order']['delivery_selected'] == 'per_item') && !isset($placeOrderDisabled)) {
                if ($options['order']['orderpage']) {
                    //go to order page
                    /**wpml select of order page**/
                    if (function_exists('icl_object_id')) {
                        $options['order']['orderpage'] = icl_object_id($options['order']['orderpage'], 'page');
                        /*confirmation page -> amend order link**/
                        if ($options['confirmation_form_amend_order_link'] > 0) {
                            $options['confirmation_form_amend_order_link'] = icl_object_id($options['confirmation_form_amend_order_link'], 'page');
                        }
                    }
                    $summary['orderpagelink'] = get_page_link($options['order']['orderpage']);
                    /*confirmation page -> amend order link**/
                    if ($options['confirmation_form_amend_order_link'] > 0) {
                        $summary['amendorderlink'] = get_page_link($options['confirmation_form_amend_order_link']);
                    } else {
                        $summary['amendorderlink'] = '';
                    }
                    $summary['button'] = '<a href="' . $summary['orderpagelink'] . '">';
                    $summary['button'] .= '<input class="btn btn-primary" type="button" value="' . $options['localization']['place_your_order']['lbl'] . '" />';
                    $summary['button'] .= '</a>';
                }
            } else {
                /**free delivery and charges > min order value*/
                if ($options['order']['delivery_selected'] == 'minimum_total' && $orderMinTotalSet == $options['order']['delivery']['minimum_total']['min_total']) {
                    //&& $orderMinTotalSet>=$options['order']['delivery']['minimum_total']['min_total']
                    $summary['nocheckout'] = '' . $options['localization']['minimum_order_delivery']['lbl'] . ' ';
                } else {
                    $summary['nocheckout'] = '' . $options['localization']['minimum_order']['lbl'] . ' ';
                }
                $summary['nocheckout'] .= '' . $summary['currency_left'] . '' . wppizza_output_format_price($options['order']['delivery']['minimum_total']['min_total'], $optionsDecimals) . '' . $summary['currency_right'] . '';
            }
        }
        /****************************************************
        			[empty cart button, show/hide depending if enabled or no of items]
        		*****************************************************/
        if (!empty($options['layout']['empty_cart_button']) && count($summary['items']) > 0) {
            $summary['button'] .= '<input class="wppizza-empty-cart-button btn btn-primary" type="button" value="' . $options['localization']['empty_cart']['lbl'] . '" />';
        }
    }
    /**enable increase/decrease in cart**/
    if ($options['layout']['cart_increase']) {
        $summary['increase_decrease'] = 1;
    }
    $summary = apply_filters('wppizza_filter_summary', $summary);
    return $summary;
}
Esempio n. 3
0
            ?>
' class='<?php 
            echo $post_type;
            ?>
-article-price <?php 
            echo $priceClass;
            ?>
' <?php 
            echo $priceTitle;
            ?>
>
	    		<span><?php 
            if ($options['layout']['show_currency_with_price'] == 1) {
                echo $currency . " ";
            }
            echo wppizza_output_format_price($meta['prices'][$k], $optionsDecimals);
            if ($options['layout']['show_currency_with_price'] == 2) {
                echo " " . $currency;
            }
            ?>
</span>
	    		<?php 
            if (!isset($hidePricetier) || count($options['sizes'][$meta['sizes']]) > 1) {
                ?>
	    		<div class='<?php 
                echo $post_type;
                ?>
-article-price-lbl<?php 
                echo $hideCartIcon;
                ?>
'><?php 
$str .= "<div class='" . $this->pluginSlug . "_option'>";
$str .= "<div class='wppizza-meta-label'>" . __('price tier and prices', $this->pluginLocale) . ":</div> ";
$str .= "<select name='" . $this->pluginSlug . "[sizes]' class='wppizza_pricetier_select'>";
foreach ($optionsSizes as $l => $m) {
    if ($l == $meta_values['sizes']) {
        $sel = " selected='selected'";
    } else {
        $sel = '';
    }
    $ident = !empty($options['sizes'][$l][0]['lbladmin']) && $options['sizes'][$l][0]['lbladmin'] != '' ? $options['sizes'][$l][0]['lbladmin'] : 'ID:' . $l . '';
    $str .= "<option value='" . $l . "'" . $sel . ">" . implode(", ", $m['lbl']) . " [" . $ident . "]</option>";
}
$str .= "</select>";
$str .= "<span class='wppizza_pricetiers'>";
foreach ($meta_values['prices'] as $k => $v) {
    $str .= "<input name='" . $this->pluginSlug . "[prices][]' size='5' type='text' value='" . wppizza_output_format_price($v, $optionsDecimals) . "' />" . $optionsCurrency . "";
}
$str .= "</span>";
$str .= "</div>";
if (isset($options['additives']) && is_array($options['additives']) && count($options['additives']) > 0) {
    /*->*** which additives in item ***/
    $str .= "<div class='" . $this->pluginSlug . "_option'>";
    $str .= "<div class='wppizza-meta-label'>" . __('contains additives', $this->pluginLocale) . ":</div> ";
    asort($options['additives']);
    //sort but keep index
    foreach ($options['additives'] as $s => $o) {
        if (!is_array($o)) {
            $lbl = $o;
        } else {
            $lbl = '' . $o['name'];
        }
Esempio n. 5
0
 function wppizza_filter_order_db_return($oDetails)
 {
     $orderDetails = $oDetails;
     //$orderDetails['items']=array();
     foreach ($oDetails['item'] as $k => $v) {
         $orderDetails['item'][$k]['postId'] = $v['postId'];
         $orderDetails['item'][$k]['count'] = $v['count'];
         $orderDetails['item'][$k]['quantity'] = $v['count'];
         /*legacy*/
         $orderDetails['item'][$k]['name'] = $v['name'];
         $orderDetails['item'][$k]['size'] = $v['size'];
         $orderDetails['item'][$k]['price'] = wppizza_output_format_price($v['price'], $this->pluginOptions['layout']['hide_decimals']);
         $orderDetails['item'][$k]['pricetotal'] = wppizza_output_format_price($v['pricetotal'], $this->pluginOptions['layout']['hide_decimals']);
         $orderDetails['item'][$k]['categories'] = $v['categories'];
         $orderDetails['item'][$k]['additionalinfo'] = $v['additionalinfo'];
         $orderDetails['item'][$k]['extend'] = $v['extend'];
         $orderDetails['item'][$k]['catIdSelected'] = $v['catIdSelected'];
     }
     $orderDetails['total_price_items'] = wppizza_output_format_price($oDetails['total_price_items'], $this->pluginOptions['layout']['hide_decimals']);
     $orderDetails['discount'] = wppizza_output_format_price($oDetails['discount'], $this->pluginOptions['layout']['hide_decimals']);
     $orderDetails['item_tax'] = wppizza_output_format_price($oDetails['item_tax'], $this->pluginOptions['layout']['hide_decimals']);
     $orderDetails['taxes_included'] = wppizza_output_format_price($oDetails['taxes_included'], $this->pluginOptions['layout']['hide_decimals']);
     $orderDetails['delivery_charges'] = !empty($oDetails['delivery_charges']) ? wppizza_output_format_price($oDetails['delivery_charges'], $this->pluginOptions['layout']['hide_decimals']) : '';
     $orderDetails['selfPickup'] = !empty($oDetails['selfPickup']) ? wppizza_validate_int_only($oDetails['selfPickup']) : 0;
     $orderDetails['total'] = wppizza_output_format_price($oDetails['total'], $this->pluginOptions['layout']['hide_decimals']);
     if (isset($oDetails['handling_charge'])) {
         $orderDetails['handling_charge'] = wppizza_output_format_price($oDetails['handling_charge'], $this->pluginOptions['layout']['hide_decimals']);
     }
     if (isset($tips['tips'])) {
         $orderDetails['tips'] = wppizza_output_format_price($tips['tips'], $this->pluginOptions['layout']['hide_decimals']);
     }
     return $orderDetails;
 }
             echo "" . __('If order total >', $this->pluginLocale) . ":";
             echo "<input name='" . $this->pluginSlug . "[order][" . $field . "][" . $k . "][discounts][" . $l . "][min_total]' size='3' type='text' value='" . wppizza_output_format_price($options['order'][$field][$k]['discounts'][$l]['min_total'], $optionsDecimals) . "' />";
             echo "" . __('discount', $this->pluginLocale) . ":";
             echo "<input name='" . $this->pluginSlug . "[order][" . $field . "][" . $k . "][discounts][" . $l . "][discount]' size='5' type='text' value='" . wppizza_output_format_float($options['order'][$field][$k]['discounts'][$l]['discount'], 'percent') . "' />";
             echo "" . __('percent', $this->pluginLocale) . "";
             echo "<br />";
         }
     }
     if ($k == 'standard') {
         echo "" . __('Standard Discount [money off]', $this->pluginLocale) . ":";
         echo "<br />";
         foreach ($v['discounts'] as $l => $m) {
             echo "" . __('If order total >', $this->pluginLocale) . ":";
             echo "<input name='" . $this->pluginSlug . "[order][" . $field . "][" . $k . "][discounts][" . $l . "][min_total]' size='3' type='text' value='" . wppizza_output_format_price($options['order'][$field][$k]['discounts'][$l]['min_total'], $optionsDecimals) . "' />";
             echo "" . __('get', $this->pluginLocale) . ":";
             echo "<input name='" . $this->pluginSlug . "[order][" . $field . "][" . $k . "][discounts][" . $l . "][discount]' size='3' type='text' value='" . wppizza_output_format_price($options['order'][$field][$k]['discounts'][$l]['discount'], $optionsDecimals) . "' />";
             echo "" . __('off', $this->pluginLocale) . "";
             echo "<br />";
         }
     }
     echo "</span>";
 }
 /**Exclude following menu items when calculating  discounts**/
 echo "<span class='wppizza_option' style='margin:20px 0'>";
 echo " " . __('<b>Exclude</b> following menu items when calculating discounts', $this->pluginLocale) . " :<br />";
 echo "<select name='" . $this->pluginSlug . "[order][discount_calculation_exclude_item][]' multiple='multiple' data-placeholder='" . __('N/A', $this->pluginLocale) . "' class='wppizza_discount_calculation_exclude_item'>";
 $args = array('post_type' => '' . WPPIZZA_POST_TYPE . '', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC');
 $query = new WP_Query($args);
 foreach ($query->posts as $pKey => $pVal) {
     echo "<option value='" . $pVal->ID . "' ";
     if (isset($options['order']['discount_calculation_exclude_item']) && isset($options['order']['discount_calculation_exclude_item'][$pVal->ID])) {
 private function getOrderDetails($orderFields, $oDetails, $pOptions, $currency, $nolabel = false)
 {
     /**********************************
     				exclude some labels in front of output
     			**********************************/
     if (!$nolabel || !is_array($nolabel)) {
         $nolabel['order_date'] = true;
         //i think we should omit label for order date as it's obvious
     }
     /***********************
     				format some variables
     			***********************/
     /**mk timestamp*/
     $oDateTimeStamp = strtotime($orderFields->order_date);
     $uDateTimeStamp = strtotime($orderFields->order_update);
     /***********************
     				format dates
     			***********************/
     $order_date = "" . date_i18n(get_option('date_format'), $oDateTimeStamp) . " " . date_i18n(get_option('time_format'), $oDateTimeStamp) . "";
     //format by set wordpress date/time
     $order_update = "" . date_i18n(get_option('date_format'), $uDateTimeStamp) . " " . date_i18n(get_option('time_format'), $uDateTimeStamp) . "";
     //format by set wordpress date/time
     /***********************
     				add gateway name/label as payment_type to single order vars
     			***********************/
     $gateways = new WPPIZZA_GATEWAYS();
     $gateways->wppizza_instanciate_gateways_frontend();
     $gateways->wppizza_wpml_localization_gateways();
     $gwIni = strtoupper($orderFields->initiator);
     /*payment method*/
     $gw_payment_method = 'CC';
     /*ini as cc payment*/
     if ($gwIni == 'COD') {
         /*COD is always cash*/
         $gw_payment_method = 'CASH';
     }
     /**ini just using the simple initiator value*/
     $payment_type = $orderFields->initiator;
     /**use full label if exists*/
     if (isset($gateways->pluginGateways[$gwIni])) {
         $payment_type = !empty($gateways->pluginGateways[$gwIni]->gatewayOptions['gateway_label']) ? $gateways->pluginGateways[$gwIni]->gatewayOptions['gateway_label'] : $orderFields->initiator;
         /*in case a customised non CC gateway was added, set back to Cash*/
         if (!empty($gateways->pluginGateways[$gwIni]->gatewayTypeSubmit) && $gateways->pluginGateways[$gwIni]->gatewayTypeSubmit == 'ajax') {
             $gw_payment_method = 'CASH';
         }
     }
     /**get string for paymnt method used*/
     $payment_method = $pOptions['localization']['common_value_order_credit_card']['lbl'];
     if ($gw_payment_method == 'CASH') {
         $payment_method = $pOptions['localization']['common_value_order_cash']['lbl'];
     }
     /***********************
     				payment due (if credit card->0)
     			***********************/
     $payment_due = $currency['left'] . wppizza_output_format_price(0, $pOptions['layout']['hide_decimals']) . $currency['right'];
     if ($gw_payment_method == 'CASH') {
         $payment_due = $currency['left'] . wppizza_output_format_price($oDetails['total'], $pOptions['layout']['hide_decimals']) . $currency['right'];
     }
     /***********************
     				pickup or delivery
     			***********************/
     $pickup_delivery = $pOptions['localization']['common_value_order_delivery']['lbl'];
     if (isset($oDetails['selfPickup']) && $oDetails['selfPickup'] >= 1) {
         $pickup_delivery = $pOptions['localization']['common_value_order_pickup']['lbl'];
     }
     /***********************
     				return array
     			***********************/
     $orderDetails = array();
     /*ini*/
     /*wp user id - currently unused*/
     $orderDetails['wp_user_id'] = array('label' => !empty($nolabel['wp_user_id']) ? '' : $pOptions['localization']['common_label_order_wp_user_id']['lbl'], 'value' => $orderFields->wp_user_id);
     /**order id*/
     $orderDetails['id'] = array('label' => !empty($nolabel['id']) ? '' : $pOptions['localization']['common_label_order_order_id']['lbl'], 'value' => $orderFields->id);
     $orderDetails['order_id'] = array('label' => !empty($nolabel['order_id']) ? '' : $pOptions['localization']['common_label_order_order_id']['lbl'], 'value' => $orderFields->id);
     /**transaction_id*/
     $orderFields->transaction_id = apply_filters('wppizza_filter_order_details_transaction_id', $orderFields->transaction_id, $orderFields->id);
     $orderDetails['transaction_id'] = array('label' => !empty($nolabel['transaction_id']) ? '' : $pOptions['localization']['common_label_order_transaction_id']['lbl'], 'value' => $orderFields->transaction_id);
     /**order_date*/
     $orderDetails['order_date'] = array('label' => !empty($nolabel['order_date']) ? '' : $pOptions['localization']['common_label_order_order_date']['lbl'], 'value' => $order_date);
     /**payment_type*/
     $orderDetails['payment_type'] = array('label' => !empty($nolabel['payment_type']) ? '' : $pOptions['localization']['common_label_order_payment_type']['lbl'], 'value' => $payment_type);
     /**payment_status*/
     $orderDetails['payment_method'] = array('label' => !empty($nolabel['payment_method']) ? '' : $pOptions['localization']['common_label_order_payment_method']['lbl'], 'value' => $payment_method);
     /**payment_due*/
     $orderDetails['payment_due'] = array('label' => !empty($nolabel['payment_due']) ? '' : $pOptions['localization']['common_label_order_payment_outstanding']['lbl'], 'value' => $payment_due);
     /**currency - in use but without label*/
     $orderDetails['currency'] = array('label' => !empty($nolabel['currency']) ? '' : $pOptions['localization']['common_label_order_currency']['lbl'], 'value' => $currency['currency']);
     $orderDetails['currencyiso'] = array('label' => !empty($nolabel['currencyiso']) ? '' : $pOptions['localization']['common_label_order_currency']['lbl'], 'value' => $currency['currencyiso']);
     /**pickup/delivery**/
     $orderDetails['pickup_delivery'] = array('label' => !empty($nolabel['pickup_delivery']) ? '' : $pOptions['localization']['common_label_order_delivery_type']['lbl'], 'value' => $pickup_delivery);
     /*total add here too, might be useful*/
     $orderDetails['total'] = array('label' => !empty($nolabel['total']) ? '' : $pOptions['localization']['order_total']['lbl'], 'value' => $currency['left'] . wppizza_output_format_price($oDetails['total'], $pOptions['layout']['hide_decimals']) . $currency['right']);
     /*
     	currently unused variables without labels defined yet in localization
     	might come in useful somewhere one day
     */
     //notes
     $orderDetails['notes'] = array('label' => '', 'value' => $orderFields->notes);
     //payment_status
     $orderDetails['payment_status'] = array('label' => '', 'value' => $orderFields->payment_status);
     //order_update
     $orderDetails['order_update'] = array('label' => '', 'value' => $order_update);
     //initiator
     $orderDetails['initiator'] = array('label' => '', 'value' => $orderFields->initiator);
     return $orderDetails;
 }
 function gateway_order_on_thankyou_process($res, $options = false)
 {
     $output = '';
     /**legacy**/
     if (!$options) {
         $options = $this->pluginOptions;
     }
     /**check if we are displaying the order on the thank you page**/
     if ($options['gateways']['gateway_showorder_on_thankyou']) {
         /*if we are only passing the id, try and get the order from the db first**/
         if (!is_object($res) && is_numeric($res)) {
             global $wpdb;
             $res = $wpdb->get_row("SELECT id,transaction_id,order_ini,customer_ini,initiator FROM " . $wpdb->prefix . $this->pluginOrderTable . " WHERE id='" . $res . "' ");
         }
         /**********************************************************
         				[get relevant vars out of db
         			**********************************************************/
         $thisCustomerDetails = maybe_unserialize($res->customer_ini);
         $thisOrderDetails = maybe_unserialize($res->order_ini);
         $thisOrderDetails = apply_filters('wppizza_filter_order_db_return', $thisOrderDetails);
         /**********************************************************
         				[organize vars to make them easier to use in template]
         			**********************************************************/
         $order['transaction_id'] = $res->transaction_id;
         /**filter as required**/
         $order['transaction_id'] = apply_filters('wppizza_email_filter_transaction_id', $order['transaction_id'], $res->id, 'order on thank you');
         $order['transaction_date_time'] = "" . date_i18n(get_option('date_format'), $thisOrderDetails['time']) . " " . date_i18n(get_option('time_format'), $thisOrderDetails['time']) . "";
         $order['gatewayUsed'] = $res->initiator;
         /**get gateway frontend label instead of just COD or similar**/
         $order['gatewayLabel'] = $res->initiator;
         $wppizzaGateways = new WPPIZZA_GATEWAYS();
         $this->pluginGateways = $wppizzaGateways->wppizza_instanciate_gateways_frontend();
         /**
         					get wpml vars of gatewway (label and info essentially)- should be done better one day using action hooks), but for the moment this will have to do.
         				**/
         $wppizzaGateways->wppizza_wpml_localization_gateways();
         $gwIni = strtoupper($res->initiator);
         if (isset($this->pluginGateways[$gwIni])) {
             $order['gatewayLabel'] = !empty($this->pluginGateways[$gwIni]->gatewayOptions['gateway_label']) ? $this->pluginGateways[$gwIni]->gatewayOptions['gateway_label'] : $order['gatewayLabel'];
         }
         /**********************/
         $order['currency'] = $thisOrderDetails['currency'];
         /****************************************************
         				[set currency positions]
         			****************************************************/
         $order['currency_left'] = $thisOrderDetails['currency'] . ' ';
         $order['currency_right'] = '';
         if ($options['layout']['currency_symbol_position'] == 'right') {
             /*right aligned*/
             $order['currency_left'] = '';
             $order['currency_right'] = ' ' . $thisOrderDetails['currency'];
         }
         $order['currencyiso'] = $thisOrderDetails['currencyiso'];
         /***********************************************
         				[set localization vars]
         			************************************************/
         $orderlbl = array();
         foreach ($options['localization'] as $k => $v) {
             if ($k == 'taxes_included') {
                 $orderlbl[$k] = sprintf('' . $v['lbl'] . '', $options['order']['item_tax']);
             } else {
                 $orderlbl[$k] = $v['lbl'];
             }
         }
         /***********************************************
         				[customer details]
         				[we should make this into a filter at some point
         				in conjuction with wppizza_filter_customer_details_html
         				used above]
         			***********************************************/
         $customer = array();
         $customerlbl = array();
         $protectedKeys = array();
         foreach ($options['order_form'] as $k => $v) {
             $protectedKeys[$v['key']] = $v;
         }
         $protectedKeys = apply_filters('wppizza_filter_order_form_fields', $protectedKeys);
         foreach ($thisCustomerDetails as $k => $v) {
             /*****default input fields of this plugin*****/
             if (isset($protectedKeys[$k])) {
                 $customerlbl[$k] = $protectedKeys[$k]['lbl'];
                 if ($protectedKeys[$k]['type'] != 'textarea') {
                     $customer[$k] = $v;
                 } else {
                     $customer[$k] = '<div class="wppizza-order-textarea">' . nl2br($v) . '</div>';
                 }
             }
             /**********************************************************************************************************
              *
              *
              *	THIS BIT BELOW SHOULD NOW BE REDUNDANT NOW AS WE CAN UST USE THE FILTER ABOVE TO ADD TO THE - SO CALLED - PROTECTED KEYS
              *	let's leave it here for now, but it will probably be removed in future versions, as it has never been documnted publicly anyway
              *	as far as i know......
              *
              **********************************************************************************************************/
             if (!isset($protectedKeys[$k]) && is_array($v) && isset($v['label']) && isset($v['value'])) {
                 $customer['' . $v['label'] . ''] = $v['value'];
                 $customerlbl['' . $v['label'] . ''] = $v['label'];
             }
         }
         /***********************************************
         				[order items]
         			***********************************************/
         $items = $thisOrderDetails['item'];
         /**filter old legacy additional info keys**/
         $items = apply_filters('wppizza_filter_order_additional_info', $items);
         /**filter new/current extend additional info keys**/
         $items = apply_filters('wppizza_filter_order_extend', $items);
         /**can be run by other plugins**/
         /**return items with html additional info**/
         $items = apply_filters('wppizza_filter_order_items_html', $items, 'additionalInfo');
         /***********************************************
         				[order summary
         			***********************************************/
         $summary['total_price_items'] = $thisOrderDetails['total_price_items'];
         $summary['discount'] = $thisOrderDetails['discount'];
         $summary['item_tax'] = $thisOrderDetails['item_tax'];
         $summary['taxes_included'] = $thisOrderDetails['taxes_included'];
         if ($options['order']['delivery_selected'] != 'no_delivery') {
             /*delivery disabled*/
             $summary['delivery_charges'] = $thisOrderDetails['delivery_charges'];
         }
         $summary['total_price_items'] = $thisOrderDetails['total_price_items'];
         $summary['selfPickup'] = $thisOrderDetails['selfPickup'];
         $summary['total'] = $thisOrderDetails['total'];
         $summary['tax_applied'] = 'items_only';
         if ($options['order']['shipping_tax']) {
             $summary['tax_applied'] = 'items_and_shipping';
         }
         if ($options['order']['taxes_included']) {
             $summary['tax_applied'] = 'taxes_included';
         }
         if (isset($thisOrderDetails['handling_charge']) && $thisOrderDetails['handling_charge'] > 0) {
             $summary['handling_charge'] = wppizza_output_format_price($thisOrderDetails['handling_charge'], $options['layout']['hide_decimals']);
         }
         if (isset($thisOrderDetails['tips']) && $thisOrderDetails['tips'] > 0) {
             $summary['tips'] = wppizza_output_format_price($thisOrderDetails['tips'], $options['layout']['hide_decimals']);
         }
         /***allow some filtering of order and summary***/
         $order = apply_filters('wppizza_filter_order_show_order_page', $order, $thisOrderDetails);
         $summary = apply_filters('wppizza_filter_summary_show_order_page', $summary, $thisOrderDetails);
         /***********************************************
         				[if template copied to theme directory use
         				that one otherwise use default]
         			***********************************************/
         ob_start();
         if (file_exists($this->pluginTemplateDir . '/wppizza-show-order.php')) {
             include $this->pluginTemplateDir . '/wppizza-show-order.php';
         } else {
             include WPPIZZA_PATH . 'templates/wppizza-show-order.php';
         }
         $output .= ob_get_clean();
     }
     return $output;
 }
function wppizza_report_dataset($options, $locale, $orderTable)
{
    if (version_compare(PHP_VERSION, '5.3', '<')) {
        print "<div style='text-align:center;margin:50px 0'>Sorry, reporting is only available with php >=5.3</div>";
        exit;
    }
    global $wpdb, $blog_id;
    $wpTime = current_time('timestamp');
    $reportCurrency = $options['order']['currency_symbol'];
    $reportCurrencyIso = $options['order']['currency'];
    $hideDecimals = $options['layout']['hide_decimals'];
    $dateformat = get_option('date_format');
    $processOrder = array();
    /************************************************************************
    				overview query. do not limit by date to get totals
    				any other query, add date range to query
    			************************************************************************/
    $reportTypes = array('ytd' => array('lbl' => __('year to date', $locale)), 'ly' => array('lbl' => __('last year', $locale)), 'tm' => array('lbl' => __('this month', $locale)), 'lm' => array('lbl' => __('last month', $locale)), '12m' => array('lbl' => __('last 12 month', $locale)), '7d' => array('lbl' => __('last 7 days', $locale)), '14d' => array('lbl' => __('last 14 days', $locale)));
    $overview = empty($_GET['report']) || !in_array($_GET['report'], array_keys($reportTypes)) ? true : false;
    $customrange = !empty($_GET['from']) && !empty($_GET['to']) ? true : false;
    /******************************
     *
     *	[overview]
     *
     ******************************/
    if ($overview && !$customrange) {
        $granularity = 'Y-m-d';
        /*days*/
        $daysSelected = 30;
        $xaxisFormat = 'D, d M';
        $serieslines = 'true';
        $seriesbars = 'false';
        $seriespoints = 'true';
        $hoverOffsetLeft = 5;
        $hoverOffsetTop = 15;
        $firstDateTimestamp = mktime(date('H', $wpTime), date('i', $wpTime), date('s', $wpTime), date('m', $wpTime), date('d', $wpTime) - $daysSelected + 1, date('Y', $wpTime));
        $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
        $lastDateReport = "" . date('Y', $wpTime) . "-" . date('m', $wpTime) . "-" . date('d', $wpTime) . " 23:59:59";
        $oQuery = '';
        /***graph label**/
        $graphLabel = "" . __('Details last 30 days', $locale) . " : ";
    }
    /******************************
     *
     *	[custom range]
     *
     ******************************/
    if ($customrange) {
        $selectedReport = 'customrange';
        $from = explode('-', $_GET['from']);
        $to = explode('-', $_GET['to']);
        $firstDateTs = mktime(0, 0, 0, $from[1], $from[2], $from[0]);
        $lastDateTs = mktime(23, 59, 59, $to[1], $to[2], $to[0]);
        /*invert dates if end<start**/
        if ($firstDateTs > $lastDateTs) {
            $firstDateTimestamp = $lastDateTs;
            $lastDateTimestamp = $firstDateTs;
        } else {
            $firstDateTimestamp = $firstDateTs;
            $lastDateTimestamp = $lastDateTs;
        }
        $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
        $lastDateReport = "" . date('Y-m-d H:i:s', $lastDateTimestamp) . "";
        /*override get vars**/
        $_GET['from'] = $firstDateReport;
        $_GET['to'] = date('Y-m-d', $lastDateTimestamp);
        /**from/to formatted**/
        $fromFormatted = date($dateformat, $firstDateTimestamp);
        $toFormatted = date($dateformat, $lastDateTimestamp);
        $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
        /***graph label**/
        $graphLabel = "" . $fromFormatted . " - " . $toFormatted . " : ";
    }
    /******************************
     *
     *	[predefined reports]
     *
     ******************************/
    if (!$overview) {
        $selectedReport = $_GET['report'];
        $oQuery = '';
        /************************
        				year to date
        			************************/
        if ($selectedReport == 'ytd') {
            $firstDateTimestamp = mktime(0, 0, 0, 1, 1, date('Y', $wpTime));
            $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
            $lastDateReport = "" . date('Y', $wpTime) . "-" . date('m', $wpTime) . "-" . date('d', $wpTime) . " 23:59:59";
            $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
            /***graph label**/
            $graphLabel = "" . __('Year to date', $locale) . " : ";
        }
        /************************
        				last year
        			************************/
        if ($selectedReport == 'ly') {
            $firstDateTimestamp = mktime(0, 0, 0, 1, 1, date('Y', $wpTime) - 1);
            $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
            $lastDateReport = date('Y-m-d H:i:s', mktime(23, 59, 59, 12, 31, date('Y', $wpTime) - 1));
            $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
            /***graph label**/
            $graphLabel = "" . __('Last Year', $locale) . " : ";
        }
        /************************
        				this month
        			************************/
        if ($selectedReport == 'tm') {
            $firstDateTimestamp = mktime(0, 0, 0, date('m', $wpTime), 1, date('Y', $wpTime));
            $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
            $lastDateReport = "" . date('Y-m-d H:i:s', mktime(23, 59, 59, date('m', $wpTime) + 1, 0, date('Y', $wpTime))) . "";
            $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
            /***graph label**/
            $graphLabel = "" . __('This Month', $locale) . " : ";
        }
        /************************
        				last month
        			************************/
        if ($selectedReport == 'lm') {
            $firstDateTimestamp = mktime(0, 0, 0, date('m', $wpTime) - 1, 1, date('Y', $wpTime));
            $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
            $lastDateReport = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m', $wpTime), 0, date('Y', $wpTime)));
            $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
            /***graph label**/
            $graphLabel = "" . __('Last Month', $locale) . " : ";
        }
        /************************
        				last 12month
        			************************/
        if ($selectedReport == '12m') {
            $firstDateTimestamp = mktime(0, 0, 0, date('m', $wpTime) - 12, date('d', $wpTime) + 1, date('Y', $wpTime));
            $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
            $lastDateReport = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m', $wpTime), date('d', $wpTime), date('Y', $wpTime)));
            $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
            /***graph label**/
            $graphLabel = "" . __('Last 12 Month', $locale) . " : ";
        }
        /************************
        				last 7 days
        			************************/
        if ($selectedReport == '7d') {
            $firstDateTimestamp = mktime(0, 0, 0, date('m', $wpTime), date('d', $wpTime) - 6, date('Y', $wpTime));
            $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
            $lastDateReport = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m', $wpTime), date('d', $wpTime), date('Y', $wpTime)));
            $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
            /***graph label**/
            $graphLabel = "" . __('Last 7 days', $locale) . " : ";
        }
        /************************
        				last 14 days
        			************************/
        if ($selectedReport == '14d') {
            $firstDateTimestamp = mktime(0, 0, 0, date('m', $wpTime), date('d', $wpTime) - 13, date('Y', $wpTime));
            $firstDateReport = "" . date('Y-m-d', $firstDateTimestamp) . "";
            $lastDateReport = date('Y-m-d H:i:s', mktime(23, 59, 59, date('m', $wpTime), date('d', $wpTime), date('Y', $wpTime)));
            /***graph label**/
            $oQuery = "AND order_date >='" . $firstDateReport . "'  AND order_date <= '" . $lastDateReport . "' ";
            $graphLabel = "" . __('Last 14 days', $locale) . " : ";
        }
    }
    if (!$overview || $customrange) {
        $firstDate = new DateTime($firstDateReport);
        $firstDateFormatted = $firstDate->format($dateformat);
        $lastDate = new DateTime($lastDateReport);
        $lastDateFormatted = $lastDate->format($dateformat);
        $dateDifference = $firstDate->diff($lastDate);
        $daysSelected = $dateDifference->days + 1;
        $monthAvgDivider = $dateDifference->m + 1;
        $monthsSelected = $dateDifference->m;
        $yearsSelected = $dateDifference->y;
        /*set granularity to months if months>0 or years>0*/
        if ($monthsSelected > 0 || $yearsSelected > 0) {
            $granularity = 'Y-m';
            /*months*/
            $xaxisFormat = 'M Y';
            $serieslines = 'false';
            $seriesbars = 'true';
            $seriespoints = 'false';
            $hoverOffsetLeft = -22;
            $hoverOffsetTop = 2;
        } else {
            $granularity = 'Y-m-d';
            /*days*/
            $xaxisFormat = 'D, d M';
            $serieslines = 'true';
            $seriesbars = 'false';
            $seriespoints = 'true';
            $hoverOffsetLeft = 5;
            $hoverOffsetTop = 15;
        }
    }
    /************************************************************************
    				multisite install
    				all orders of all sites (blogs)
    				but only for master blog and if enabled (settings)
    			************************************************************************/
    if (is_multisite() && $blog_id == BLOG_ID_CURRENT_SITE && $options['plugin_data']['wp_multisite_reports_all_sites']) {
        $ordersQueryRes = array();
        $blogs = $wpdb->get_results("SELECT blog_id FROM {$wpdb->blogs}", ARRAY_A);
        if ($blogs) {
            foreach ($blogs as $blog) {
                switch_to_blog($blog['blog_id']);
                /************************
                				[make and run query]
                			*************************/
                $ordersQuery = wppizza_report_mkquery($wpdb->prefix, $orderTable, $oQuery);
                $ordersQuery = $wpdb->get_results($ordersQuery);
                /**merge array**/
                $ordersQueryRes = array_merge($ordersQuery, $ordersQueryRes);
                restore_current_blog();
            }
        }
    } else {
        /************************
        				[make and run query]
        			*************************/
        $ordersQuery = wppizza_report_mkquery($wpdb->prefix, $orderTable, $oQuery);
        $ordersQueryRes = $wpdb->get_results($ordersQuery);
    }
    /**************************
    				ini dates
    			**************************/
    $graphDates = array();
    for ($i = 0; $i < $daysSelected; $i++) {
        $dayFormatted = mktime(date('H', $firstDateTimestamp), date('i', $firstDateTimestamp), date('s', $firstDateTimestamp), date('m', $firstDateTimestamp), date('d', $firstDateTimestamp) + $i, date('Y', $firstDateTimestamp));
        $graphDates[] = date($granularity, $dayFormatted);
    }
    /******************************************************************************************************************************************************
     *
     *
     *
     *	[create dataset from orders]
     *
     *
     *
     ******************************************************************************************************************************************************/
    /**********************************************
     *
     *	[get and tidy up order first]
     *
     **********************************************/
    foreach ($ordersQueryRes as $k => $order) {
        if ($order->order_ini != '') {
            $orderDetails = maybe_unserialize($order->order_ini);
            /**unserialize order details**/
            /*************************************************************************************
            				some collations - especially if importing from other/older db's that were still
            				ISO instead of UTF may get confused by the collation and throw serialization errors
            				the following *trys* to fix this , but is not 100% guaranteed to work in all cases
            				99% of the time though this won't happen anyway, as it should only ever
            				possibly be the case with very early versions of wppizza or if importing from early
            				versions that have a different charset.
            				....worth a try though regardless
            			************************************************************************************/
            if (!isset($orderDetails['total'])) {
                //print"".PHP_EOL.$order->id." | ". $order->oDate." | ".$orderDetails['total'];
                $orderDetails = $order->order_ini;
                /**convert currency symbols individuallly first to UTF*/
                $convCurr = iconv("ISO-8859-1", "UTF-8", $reportCurrency);
                $orderDetails = str_replace($reportCurrency, $convCurr, $orderDetails);
                /**convert to ISO **/
                $encoding = mb_detect_encoding($orderDetails);
                $orderDetails = iconv($encoding, "ISO-8859-1//IGNORE", $orderDetails);
                /**unseralize**/
                $orderDetails = maybe_unserialize($orderDetails);
                /**if we still have unrescuable errors we *could*  catch them somewhere */
                if (!isset($orderDetails['total'])) {
                    //$encoding   = mb_detect_encoding($order->order_ini);
                    //$errors=wppizza_serialization_errors($order->order_ini);
                    //file_put_contents('','.$order->id.': ['.$encoding.'] '.print_r($order->order_ini,true).' '.print_r($errors,true).PHP_EOL.PHP_EOL,FILE_APPEND);
                }
            }
            if (isset($orderDetails['total'])) {
                /**tidy up a bit and get rid of stuff we do not need**/
                unset($orderDetails['currencyiso']);
                unset($orderDetails['currency']);
                unset($orderDetails['discount']);
                unset($orderDetails['item_tax']);
                unset($orderDetails['delivery_charges']);
                unset($orderDetails['tips']);
                unset($orderDetails['selfPickup']);
                unset($orderDetails['time']);
                /**add new**/
                $orderDetails['order_date'] = substr($order->oDate, 0, 10);
                $orderDetails['order_date_formatted'] = date($granularity, $order->order_date);
                $orderDetails['order_items_count'] = 0;
                /**sanitize the items**/
                $itemDetails = array();
                if (isset($orderDetails['item'])) {
                    foreach ($orderDetails['item'] as $k => $uniqueItems) {
                        //$itemDetails[$k]['postId']=$uniqueItems['postId'];
                        $itemDetails[$k]['name'] = $uniqueItems['name'];
                        $itemDetails[$k]['size'] = $uniqueItems['size'];
                        $itemDetails[$k]['quantity'] = $uniqueItems['quantity'];
                        $itemDetails[$k]['price'] = $uniqueItems['price'];
                        $itemDetails[$k]['pricetotal'] = $uniqueItems['pricetotal'];
                        /**add count of items in this order**/
                        $orderDetails['order_items_count'] += $uniqueItems['quantity'];
                    }
                }
                /**add relevant item info to array**/
                $orderDetails['item'] = $itemDetails;
                $processOrder[] = $orderDetails;
            }
        }
    }
    /**********************************************************************************
     *
     *
     *	lets do the calculations, to get the right dataset
     *
     *
     **********************************************************************************/
    /**************************************
    				[initialize array and values]
    			**************************************/
    $datasets = array();
    $datasets['sales_value_total'] = 0;
    /**total of sales/orders INCLUDING taxes, discounts, charges etc**/
    $datasets['sales_count_total'] = 0;
    /**total count of sales**/
    $datasets['items_value_total'] = 0;
    /**total of items EXLUDING taxes, discounts, charges etc**/
    $datasets['items_count_total'] = 0;
    /**total count of items**/
    $datasets['sales'] = array();
    /*holds data on a per day/month basis*/
    $datasets['bestsellers'] = array('by_volume' => array(), 'by_value' => array());
    /**************************************
    				[loop through orders and do things]
    			**************************************/
    $j = 1;
    foreach ($processOrder as $k => $order) {
        /****************************************************
        				if we are not setting a defined range
        				like a whole month, week , or whatever
        				(i.e in overview) lets get first and last day
        				we have orders for to be able to calc averages
        			****************************************************/
        if ($j == 1) {
            $datasets['first_date'] = $order['order_date'];
        }
        //if($j==count($processOrder)){$datasets['last_date']=$order['order_date'];}
        /****************************************************
        				set garnularity (i.e by day, month or year)
        			****************************************************/
        $dateResolution = $order['order_date_formatted'];
        /**set garnularity (i.e by day, month or year)**/
        /****************************************************
        				[get/set totals]
        			****************************************************/
        $datasets['sales_value_total'] += $order['total'];
        $datasets['sales_count_total']++;
        $datasets['items_value_total'] += $order['total_price_items'];
        $datasets['items_count_total'] += $order['order_items_count'];
        /****************************************************
        				[get/set items to sort for bestsellers]
        			****************************************************/
        foreach ($order['item'] as $iK => $oItems) {
            $uniqueKeyX = explode('|', $iK);
            /**make a unique key by id and name in case an items name was changed */
            $uKey = MD5($uniqueKeyX[0] . $oItems['name'] . $oItems['size']);
            if (!isset($datasets['bestsellers']['by_volume'][$uKey])) {
                /**lets do by valume and by value at the same time**/
                $datasets['bestsellers']['by_value'][$uKey] = array('price' => $oItems['pricetotal'], 'single_price' => $oItems['price'], 'quantity' => $oItems['quantity'], 'name' => '' . $oItems['name'] . ' [' . $oItems['size'] . ']');
                $datasets['bestsellers']['by_volume'][$uKey] = array('quantity' => $oItems['quantity'], 'price' => $oItems['pricetotal'], 'single_price' => $oItems['price'], 'name' => '' . $oItems['name'] . ' [' . $oItems['size'] . ']');
            } else {
                $datasets['bestsellers']['by_volume'][$uKey]['quantity'] += $oItems['quantity'];
                $datasets['bestsellers']['by_volume'][$uKey]['price'] += $oItems['pricetotal'];
            }
        }
        /****************************************************
        				[get/set totals [per granularity]
        			****************************************************/
        /**initialize arrays**/
        if (!isset($datasets['sales'][$dateResolution])) {
            $datasets['sales'][$dateResolution]['sales_value_total'] = 0;
            $datasets['sales'][$dateResolution]['sales_count_total'] = 0;
            $datasets['sales'][$dateResolution]['items_value_total'] = 0;
            $datasets['sales'][$dateResolution]['items_count_total'] = 0;
        }
        $datasets['sales'][$dateResolution]['sales_value_total'] += $order['total'];
        $datasets['sales'][$dateResolution]['sales_count_total']++;
        $datasets['sales'][$dateResolution]['items_value_total'] += $order['total_price_items'];
        $datasets['sales'][$dateResolution]['items_count_total'] += $order['order_items_count'];
        $j++;
    }
    /*******************************
    				sort and splice bestsellers
    			*******************************/
    arsort($datasets['bestsellers']['by_volume']);
    arsort($datasets['bestsellers']['by_value']);
    if (!isset($_GET['b'])) {
        $bCount = 10;
    } else {
        $bCount = abs((int) $_GET['b']);
    }
    array_splice($datasets['bestsellers']['by_volume'], $bCount);
    array_splice($datasets['bestsellers']['by_value'], $bCount);
    /************************************************************
    				construct bestsellers html
    			*************************************************************/
    $htmlBsVol = '<ul>';
    /*by volume*/
    foreach ($datasets['bestsellers']['by_volume'] as $bsbv) {
        $htmlBsVol .= '<li>' . $bsbv['quantity'] . ' x ' . $bsbv['name'] . '</li>';
    }
    $htmlBsVol .= '</ul>';
    $htmlBsVal = '<ul>';
    /*by value*/
    foreach ($datasets['bestsellers']['by_value'] as $bsbv) {
        $htmlBsVal .= '<li>' . $bsbv['name'] . ' <span>' . $reportCurrency . '' . wppizza_output_format_price($bsbv['price'], $hideDecimals) . '</span><br /> [' . $bsbv['quantity'] . ' x ' . $reportCurrency . '' . wppizza_output_format_price($bsbv['single_price'], $hideDecimals) . '] <span>' . round($bsbv['price'] / $datasets['items_value_total'] * 100, 2) . '%</span></li>';
    }
    $htmlBsVal .= '</ul>';
    /**********************************************************
    				get number of months and days in results array
    			***********************************************************/
    if ($overview && !$customrange) {
        /**in case we have an empty results set**/
        if (!isset($datasets['first_date'])) {
            $datasets['first_date'] = "" . date('Y', $wpTime) . "-" . date('m', $wpTime) . "-" . date('d', $wpTime) . " 00:00:00";
        }
        $firstDate = new DateTime($datasets['first_date']);
        $firstDateFormatted = $firstDate->format($dateformat);
        $lastDate = new DateTime("" . date('Y', $wpTime) . "-" . date('m', $wpTime) . "-" . date('d', $wpTime) . " 23:59:59");
        $lastDateFormatted = $lastDate->format($dateformat);
        $dateDifference = $firstDate->diff($lastDate);
        $daysSelected = $dateDifference->days + 1;
        $monthAvgDivider = $dateDifference->m + 1;
    }
    /*****************************************************************
    				averages
    			******************************************************************/
    /*per day*/
    $datasets['sales_count_average'] = round($datasets['sales_count_total'] / $daysSelected, 2);
    $datasets['sales_item_average'] = round($datasets['items_count_total'] / $daysSelected, 2);
    $datasets['sales_value_average'] = round($datasets['sales_value_total'] / $daysSelected, 2);
    /*per month*/
    $datasets['sales_count_average_month'] = round($datasets['sales_count_total'] / $monthAvgDivider, 2);
    $datasets['sales_item_average_month'] = round($datasets['items_count_total'] / $monthAvgDivider, 2);
    $datasets['sales_value_average_month'] = round($datasets['sales_value_total'] / $monthAvgDivider, 2);
    /******************************************************************************************************************************************************
     *
     *
     *	[sidebar boxes]
     *
     *
     ******************************************************************************************************************************************************/
    $box = array();
    $boxrt = array();
    if ($overview && !$customrange) {
        $box[] = array('id' => 'wppizza-report-val-total', 'lbl' => __('All Sales: Total', $locale), 'val' => '<p>' . $reportCurrency . ' ' . wppizza_output_format_price($datasets['sales_value_total'], $hideDecimals) . '<br /><span class="description">' . __('incl. taxes, charges and discounts', $locale) . '</span></p>');
        $box[] = array('id' => 'wppizza-report-val-avg', 'lbl' => __('All Sales: Averages', $locale), 'val' => '<p>' . $reportCurrency . ' ' . wppizza_output_format_price($datasets['sales_value_average'], $hideDecimals) . ' ' . __('per day', $locale) . '<br />' . $reportCurrency . ' ' . wppizza_output_format_price($datasets['sales_value_average_month'], $hideDecimals) . ' ' . __('per month', $locale) . '</p>');
        $box[] = array('id' => 'wppizza-report-count-total', 'lbl' => __('All Orders/Items: Total', $locale), 'val' => '<p>' . $datasets['sales_count_total'] . ' ' . __('Orders', $locale) . ': ' . $reportCurrency . ' ' . $datasets['items_value_total'] . '<br />(' . $datasets['items_count_total'] . ' ' . __('items', $locale) . ')<br /><span class="description">' . __('before taxes, charges and discounts', $locale) . '</span></p>');
        $box[] = array('id' => 'wppizza-report-count-avg', 'lbl' => __('All Orders/Items: Averages', $locale), 'val' => '<p>' . $datasets['sales_count_average'] . ' ' . __('Orders', $locale) . ' (' . $datasets['sales_item_average'] . ' ' . __('items', $locale) . ') ' . __('per day', $locale) . '<br />' . $datasets['sales_count_average_month'] . ' ' . __('Orders', $locale) . ' (' . $datasets['sales_item_average_month'] . ' items) ' . __('per month', $locale) . '</p>');
        $box[] = array('id' => 'wppizza-report-info', 'lbl' => __('Range', $locale), 'val' => '<p>' . $firstDateFormatted . ' - ' . $lastDateFormatted . '<br />' . $daysSelected . ' ' . __('days', $locale) . '<br />' . $monthAvgDivider . ' ' . __('months', $locale) . '</p>');
        $boxrt[] = array('id' => 'wppizza-report-top10-volume', 'lbl' => __('Bestsellers by Volume - All', $locale), 'val' => $htmlBsVol);
        $boxrt[] = array('id' => 'wppizza-report-top10-volume', 'lbl' => __('Bestsellers by Value - All (percent of order total)', $locale), 'val' => $htmlBsVal);
    }
    if (!$overview || $customrange) {
        $box[] = array('id' => 'wppizza-report-val-total', 'lbl' => __('Sales Total [in range]', $locale), 'val' => '<p>' . $reportCurrency . ' ' . wppizza_output_format_price($datasets['sales_value_total'], $hideDecimals) . '<br /><span class="description">' . __('incl. taxes, charges and discounts', $locale) . '</span></p>');
        $box[] = array('id' => 'wppizza-report-val-avg', 'lbl' => __('Sales Averages [in range]', $locale), 'val' => '<p>' . $reportCurrency . ' ' . wppizza_output_format_price($datasets['sales_value_average'], $hideDecimals) . ' ' . __('per day', $locale) . '<br />' . $reportCurrency . ' ' . wppizza_output_format_price($datasets['sales_value_average_month'], $hideDecimals) . ' ' . __('per month', $locale) . '</p>');
        $box[] = array('id' => 'wppizza-report-count-total', 'lbl' => __('Orders/Items Total [in range]', $locale), 'val' => '<p>' . $datasets['sales_count_total'] . ' ' . __('Orders', $locale) . ': ' . $reportCurrency . ' ' . $datasets['items_value_total'] . '<br /> (' . $datasets['items_count_total'] . ' ' . __('items', $locale) . ')<br /><span class="description">' . __('before taxes, charges and discounts', $locale) . '</span></p>');
        $box[] = array('id' => 'wppizza-report-count-avg', 'lbl' => __('Orders/Items Averages [in range]', $locale), 'val' => '<p>' . $datasets['sales_count_average'] . ' ' . __('Orders', $locale) . ' (' . $datasets['sales_item_average'] . ' ' . __('items', $locale) . ') ' . __('per day', $locale) . '<br />' . $datasets['sales_count_average_month'] . ' ' . __('Orders', $locale) . ' (' . $datasets['sales_item_average_month'] . ' items) ' . __('per month', $locale) . '</p>');
        $box[] = array('id' => 'wppizza-report-info', 'lbl' => __('Range', $locale), 'val' => '<p>' . $firstDateFormatted . ' - ' . $lastDateFormatted . '<br />' . $daysSelected . ' ' . __('days', $locale) . '<br />' . $monthAvgDivider . ' ' . __('months', $locale) . '</p>');
        $boxrt[] = array('id' => 'wppizza-report-top10-volume', 'lbl' => __('Bestsellers by Volume [in range]', $locale), 'val' => $htmlBsVol);
        $boxrt[] = array('id' => 'wppizza-report-top10-volume', 'lbl' => __('Bestsellers by Value [percent of all orders in range]', $locale), 'val' => $htmlBsVal);
    }
    /******************************************************************************************************************************************************
     *
     *
     *	[graph data]
     *
     *
     ******************************************************************************************************************************************************/
    /***graph data sales value**/
    $grSalesValue = array();
    foreach ($graphDates as $date) {
        $str2t = strtotime($date . ' 12:00:00');
        $xaxis = date($xaxisFormat, $str2t);
        $val = !empty($datasets['sales'][$date]['sales_value_total']) ? $datasets['sales'][$date]['sales_value_total'] : 0;
        $grSalesValue[] = '["' . $xaxis . '",' . $val . ']';
    }
    $graph['sales_value'] = 'label:"' . __('sales value', $locale) . '",data:[' . implode(',', $grSalesValue) . ']';
    /***graph data sales count**/
    $grSalesCount = array();
    foreach ($graphDates as $date) {
        $str2t = strtotime($date . ' 12:00:00');
        $xaxis = date($xaxisFormat, $str2t);
        $val = !empty($datasets['sales'][$date]['sales_count_total']) ? $datasets['sales'][$date]['sales_count_total'] : 0;
        $grSalesCount[] = '["' . $xaxis . '",' . $val . ']';
    }
    $graph['sales_count'] = 'label:"' . __('number of sales', $locale) . '",data:[' . implode(',', $grSalesCount) . '], yaxis: 2';
    /***graph data items count**/
    $grItemsCount = array();
    foreach ($graphDates as $date) {
        $str2t = strtotime($date . ' 12:00:00');
        $xaxis = date($xaxisFormat, $str2t);
        $val = !empty($datasets['sales'][$date]['items_count_total']) ? $datasets['sales'][$date]['items_count_total'] : 0;
        $grItemsCount[] = '["' . $xaxis . '",' . $val . ']';
    }
    $graph['items_count'] = 'label:"' . __('items sold', $locale) . '",data:[' . implode(',', $grItemsCount) . '], yaxis: 3';
    /************************************
    			make array to return
    		*************************************/
    $data = array();
    $data['currency'] = $reportCurrency;
    $data['dataset'] = $datasets;
    $data['graphs'] = array('data' => $graph, 'label' => $graphLabel, 'hoverOffsetTop' => $hoverOffsetTop, 'hoverOffsetLeft' => $hoverOffsetLeft, 'series' => array('lines' => $serieslines, 'bars' => $seriesbars, 'points' => $seriespoints));
    $data['boxes'] = $box;
    $data['boxesrt'] = $boxrt;
    $data['reportTypes'] = $reportTypes;
    $data['view'] = $overview && !$customrange ? 'ini' : 'custom';
    return $data;
}