/**
 * Output the coupons overview stats.
 *
 * @access public
 * @return void
 */
function woocommerce_coupons_overview()
{
    global $start_date, $end_date, $woocommerce, $wpdb;
    $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : '';
    $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : '';
    if (!$start_date) {
        $start_date = date('Ymd', strtotime(date('Ym', current_time('timestamp')) . '01'));
    }
    if (!$end_date) {
        $end_date = date('Ymd', current_time('timestamp'));
    }
    $start_date = strtotime($start_date);
    $end_date = strtotime($end_date);
    $total_order_count = apply_filters('woocommerce_reports_coupons_overview_total_order_count', absint($wpdb->get_var("\n\t\tSELECT COUNT( DISTINCT posts.ID ) as order_count\n\t\tFROM {$wpdb->posts} AS posts\n\t\tLEFT JOIN {$wpdb->term_relationships} AS rel ON posts.ID = rel.object_ID\n\t\tLEFT JOIN {$wpdb->term_taxonomy} AS tax USING( term_taxonomy_id )\n\t\tLEFT JOIN {$wpdb->terms} AS term USING( term_id )\n\t\tWHERE \tterm.slug IN ('" . implode("','", apply_filters('woocommerce_reports_order_statuses', array('completed', 'processing', 'on-hold'))) . "')\n\t\tAND \tposts.post_status \t= 'publish'\n\t\tAND \ttax.taxonomy\t\t= 'shop_order_status'\n\t\tAND \tpost_date > '" . date('Y-m-d', $start_date) . "'\n\t\tAND \tpost_date < '" . date('Y-m-d', strtotime('+1 day', $end_date)) . "'\n\t")));
    $coupon_totals = apply_filters('woocommerce_reports_coupons_overview_totals', $wpdb->get_row("\n\t\tSELECT COUNT( DISTINCT posts.ID ) as order_count, SUM( order_item_meta.meta_value ) as total_discount\n\t\tFROM {$wpdb->prefix}woocommerce_order_items as order_items\n\t\tLEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id\n\t\tLEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID\n\t\tLEFT JOIN {$wpdb->term_relationships} AS rel ON posts.ID = rel.object_ID\n\t\tLEFT JOIN {$wpdb->term_taxonomy} AS tax USING( term_taxonomy_id )\n\t\tLEFT JOIN {$wpdb->terms} AS term USING( term_id )\n\t\tWHERE \tterm.slug IN ('" . implode("','", apply_filters('woocommerce_reports_order_statuses', array('completed', 'processing', 'on-hold'))) . "')\n\t\tAND \tposts.post_status \t= 'publish'\n\t\tAND \ttax.taxonomy\t\t= 'shop_order_status'\n\t\tAND \torder_items.order_item_type = 'coupon'\n\t\tAND \torder_item_meta.meta_key = 'discount_amount'\n\t\tAND \tpost_date > '" . date('Y-m-d', $start_date) . "'\n\t\tAND \tpost_date < '" . date('Y-m-d', strtotime('+1 day', $end_date)) . "'\n\t"));
    $coupons_by_count = apply_filters('woocommerce_reports_coupons_overview_coupons_by_count', $wpdb->get_results("\n\t\tSELECT COUNT( order_items.order_id ) as count, order_items.*\n\t\tFROM {$wpdb->prefix}woocommerce_order_items as order_items\n\t\tLEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id\n\t\tLEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID\n\t\tLEFT JOIN {$wpdb->term_relationships} AS rel ON posts.ID = rel.object_ID\n\t\tLEFT JOIN {$wpdb->term_taxonomy} AS tax USING( term_taxonomy_id )\n\t\tLEFT JOIN {$wpdb->terms} AS term USING( term_id )\n\t\tWHERE \tterm.slug IN ('" . implode("','", apply_filters('woocommerce_reports_order_statuses', array('completed', 'processing', 'on-hold'))) . "')\n\t\tAND \tposts.post_status \t= 'publish'\n\t\tAND \ttax.taxonomy\t\t= 'shop_order_status'\n\t\tAND \torder_items.order_item_type = 'coupon'\n\t\tAND \torder_item_meta.meta_key = 'discount_amount'\n\t\tAND \torder_items.order_item_name != ''\n\t\tAND \tpost_date > '" . date('Y-m-d', $start_date) . "'\n\t\tAND \tpost_date < '" . date('Y-m-d', strtotime('+1 day', $end_date)) . "'\n\t\tGROUP BY order_items.order_item_name\n\t\tORDER BY count DESC\n\t\tLIMIT 15\n\t"));
    $coupons_by_amount = apply_filters('woocommerce_reports_coupons_overview_coupons_by_count', $wpdb->get_results("\n\t\tSELECT SUM( order_item_meta.meta_value ) as amount, order_items.*\n\t\tFROM {$wpdb->prefix}woocommerce_order_items as order_items\n\t\tLEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id\n\t\tLEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID\n\t\tLEFT JOIN {$wpdb->term_relationships} AS rel ON posts.ID = rel.object_ID\n\t\tLEFT JOIN {$wpdb->term_taxonomy} AS tax USING( term_taxonomy_id )\n\t\tLEFT JOIN {$wpdb->terms} AS term USING( term_id )\n\t\tWHERE \tterm.slug IN ('" . implode("','", apply_filters('woocommerce_reports_order_statuses', array('completed', 'processing', 'on-hold'))) . "')\n\t\tAND \tposts.post_status \t= 'publish'\n\t\tAND \ttax.taxonomy\t\t= 'shop_order_status'\n\t\tAND \torder_items.order_item_type = 'coupon'\n\t\tAND \torder_item_meta.meta_key = 'discount_amount'\n\t\tAND \torder_items.order_item_name != ''\n\t\tAND \tpost_date > '" . date('Y-m-d', $start_date) . "'\n\t\tAND \tpost_date < '" . date('Y-m-d', strtotime('+1 day', $end_date)) . "'\n\t\tGROUP BY order_items.order_item_name\n\t\tORDER BY amount DESC\n\t\tLIMIT 15\n\t"));
    ?>
	<form method="post" action="">
		<p><label for="from"><?php 
    _e('From:', 'woocommerce');
    ?>
</label> <input type="text" name="start_date" id="from" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $start_date));
    ?>
" /> <label for="to"><?php 
    _e('To:', 'woocommerce');
    ?>
</label> <input type="text" name="end_date" id="to" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $end_date));
    ?>
" /> <input type="submit" class="button" value="<?php 
    _e('Show', 'woocommerce');
    ?>
" /></p>
	</form>

	<div id="poststuff" class="woocommerce-reports-wrap">
		<div class="woocommerce-reports-sidebar">
			<div class="postbox">
				<h3><span><?php 
    _e('Total orders containing coupons', 'woocommerce');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    if ($coupon_totals->order_count > 0) {
        echo absint($coupon_totals->order_count);
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>
			<div class="postbox">
				<h3><span><?php 
    _e('Percent of orders containing coupons', 'woocommerce');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    if ($coupon_totals->order_count > 0) {
        echo round($coupon_totals->order_count / $total_order_count * 100, 2) . '%';
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>
			<div class="postbox">
				<h3><span><?php 
    _e('Total coupon discount', 'woocommerce');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    if ($coupon_totals->total_discount > 0) {
        echo woocommerce_price($coupon_totals->total_discount);
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>
		</div>
		<div class="woocommerce-reports-main">
			<div class="woocommerce-reports-left">
				<div class="postbox">
					<h3><span><?php 
    _e('Most popular coupons', 'woocommerce');
    ?>
</span></h3>
					<div class="inside">
						<ul class="wc_coupon_list wc_coupon_list_block">
							<?php 
    if ($coupons_by_count) {
        foreach ($coupons_by_count as $coupon) {
            $post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' LIMIT 1;", $coupon->order_item_name));
            $link = $post_id ? admin_url('post.php?post=' . $post_id . '&action=edit') : admin_url('edit.php?s=' . esc_url($coupon->order_item_name) . '&post_status=all&post_type=shop_coupon');
            echo '<li><a href="' . $link . '" class="code"><span><span>' . esc_html($coupon->order_item_name) . '</span></span></a> - ' . sprintf(_n('Used 1 time', 'Used %d times', $coupon->count, 'woocommerce'), absint($coupon->count)) . '</li>';
        }
    } else {
        echo '<li>' . __('No coupons found', 'woocommerce') . '</li>';
    }
    ?>
						</ul>
					</div>
				</div>
			</div>
			<div class="woocommerce-reports-right">
				<div class="postbox">
					<h3><span><?php 
    _e('Greatest discount amount', 'woocommerce');
    ?>
</span></h3>
					<div class="inside">
						<ul class="wc_coupon_list wc_coupon_list_block">
							<?php 
    if ($coupons_by_amount) {
        foreach ($coupons_by_amount as $coupon) {
            $post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_type = 'shop_coupon' AND post_status = 'publish' LIMIT 1;", $coupon->order_item_name));
            $link = $post_id ? admin_url('post.php?post=' . $post_id . '&action=edit') : admin_url('edit.php?s=' . esc_url($coupon->order_item_name) . '&post_status=all&post_type=shop_coupon');
            echo '<li><a href="' . $link . '" class="code"><span><span>' . esc_html($coupon->order_item_name) . '</span></span></a> - ' . sprintf(__('Discounted %s', 'woocommerce'), woocommerce_price($coupon->amount)) . '</li>';
        }
    } else {
        echo '<li>' . __('No coupons found', 'woocommerce') . '</li>';
    }
    ?>
						</ul>
					</div>
				</div>
			</div>
		</div>
	</div>
	<script type="text/javascript">
		jQuery(function(){
			<?php 
    woocommerce_datepicker_js();
    ?>
		});
	</script>
	<?php 
}
/**
 *
 * 
 */
function woocommerce_carts_overview()
{
    global $start_date, $end_date, $woocommerce, $wpdb, $wp_locale;
    $current_month = date("j/n/Y", mktime(0, 0, 0, 1, date("m"), date("Y")));
    $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : '';
    $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : '';
    if (!$start_date) {
        $start_date = $current_month;
    }
    if (!$end_date) {
        $end_date = strtotime(date('Ymd', current_time('timestamp')));
    }
    $start_date = strtotime($start_date);
    $end_date = strtotime($end_date);
    //$start_date = strtotime(date('Ymd', strtotime( date('Ym', current_time('timestamp')).'01' )));
    $end_date = strtotime(date('Ymd', current_time('timestamp')));
    // Get orders to display in widget
    $args = array('numberposts' => -1, 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'carts', 'post_status' => 'publish', 'suppress_filters' => false, 'tax_query' => array(array('taxonomy' => 'shop_cart_status', 'terms' => apply_filters('woocommerce_reports_cart_statuses', array('open')), 'field' => 'slug', 'operator' => 'IN')));
    add_filter('posts_where', 'carts_abandoned_within_range');
    $open_carts = get_posts($args);
    $args = array('numberposts' => -1, 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'carts', 'post_status' => 'publish', 'suppress_filters' => false, 'tax_query' => array(array('taxonomy' => 'shop_cart_status', 'terms' => apply_filters('woocommerce_reports_cart_statuses', array('converted')), 'field' => 'slug', 'operator' => 'IN')));
    $converted_carts = get_posts($args);
    $converted_counts = array();
    $updated_counts = array();
    $total_converted = 0;
    $total_updated = 0;
    // Blank date ranges to begin
    $count = 0;
    $days = ($end_date - $start_date) / (60 * 60 * 24);
    if ($days == 0) {
        $days = 1;
    }
    while ($count < $days + 1) {
        $time = strtotime(date('Ymd', strtotime('+ ' . $count . ' DAY', $start_date))) . '000';
        $converted_counts[$time] = 0;
        $updated_counts[$time] = 0;
        $count++;
    }
    if ($converted_carts) {
        foreach ($converted_carts as $converted_cart) {
            $time = strtotime(date('Ymd', strtotime($converted_cart->post_date))) . '000';
            if (isset($converted_counts[$time])) {
                $converted_counts[$time]++;
                $total_converted++;
            } else {
                $converted_counts[$time] = 1;
            }
        }
    }
    if ($open_carts) {
        foreach ($open_carts as $open_cart) {
            $time = strtotime(date('Ymd', strtotime($open_cart->post_date))) . '000';
            if (isset($updated_counts[$time])) {
                $updated_counts[$time]++;
                $total_updated++;
            } else {
                $updated_counts[$time] = 1;
            }
        }
    }
    remove_filter('posts_where', 'carts_abandoned_within_range');
    /* Script variables */
    $params = array('currency_symbol' => get_woocommerce_currency_symbol(), 'number_of_converted_carts' => __('Converted Carts', 'woocommerce'), 'number_of_updated_carts' => __('Open and Abandoned Carts', 'woocommerce'));
    $converted_counts_array = array();
    foreach ($converted_counts as $key => $count) {
        $converted_counts_array[] = array($key, $count);
    }
    $updated_counts_array = array();
    foreach ($updated_counts as $key => $amount) {
        $updated_counts_array[] = array($key, $amount);
    }
    $cart_data = array('converted_counts' => $converted_counts_array, 'updated_counts' => $updated_counts_array);
    $cart_data_json = json_encode($cart_data);
    ?>
	

<form method="post" action="">
		<p><label for="from"><?php 
    _e('From:', 'woocommerce');
    ?>
</label> <input type="text" name="start_date" id="from" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $start_date));
    ?>
" /> <label for="to"><?php 
    _e('To:', 'woocommerce');
    ?>
</label> <input type="text" name="end_date" id="to" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $end_date));
    ?>
" /> <input type="submit" class="button" value="<?php 
    _e('Show', 'woocommerce');
    ?>
" /></p>
	</form>
<div id="poststuff" class="woocommerce-reports-wrap">
		<div class="woocommerce-reports-sidebar">
			<div class="postbox">
<?php 
    $link = add_query_arg(array('post_type' => 'carts', 'mv' => 'OandA', 'start_date' => date('Y-m-d', time() - 60 * 60 * 24 * $days), 'end_date' => date('Y-m-d', time())), get_admin_url(null, 'edit.php'));
    $num_updated = '<a style = "color:#333;" href="' . $link . '">' . $total_updated . '</a>';
    ?>
				<h3><span><?php 
    _e('Open & Abandoned Carts In Range', 'woocommerce');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    if ($total_updated != '') {
        echo $num_updated . ' Carts';
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>
			<div class="postbox">
<?php 
    $link = add_query_arg(array('post_type' => 'carts', 'mv' => 'Converted', 'start_date' => date('Y-m-d', time() - 60 * 60 * 24 * $days), 'end_date' => date('Y-m-d', time())), get_admin_url(null, 'edit.php'));
    $num_converted = '<a style = "color:#333;"href="' . $link . '">' . $total_converted . '</a>';
    ?>
				<h3><span><?php 
    _e('Converted Carts In Range', 'woocommerce');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    sizeof($total_converted);
    if ($total_converted != '') {
        echo $num_converted . ' Carts';
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>

		</div>
		<div class="woocommerce-reports-main">
			<div class="postbox">
				<h3><span><?php 
    _e('Open & Abandoned Carts vs. Converted Carts', 'woocommerce');
    ?>
</span></h3>
				<div class="inside chart">
					<div id="placeholder" style="width:100%; overflow:hidden; height:568px; position:relative;"></div>
				</div>
			</div>
		</div>
	</div>
	<?php 
    ?>
	
		<script type="text/javascript">
		jQuery(function(){
			var cart_data = jQuery.parseJSON( '<?php 
    echo $cart_data_json;
    ?>
' );
		
			var d = cart_data.converted_counts;
		    var d2 = cart_data.updated_counts;
			
			for (var i = 0; i < d.length; ++i) d[i][0] += 60 * 60 * 1000;
		    for (var i = 0; i < d2.length; ++i) d2[i][0] += 60 * 60 * 1000;
			
			var placeholder = jQuery("#placeholder");
			 
			var plot = jQuery.plot(placeholder, [ { label: "<?php 
    echo esc_js(__('Converted Carts', 'woocommerce'));
    ?>
", data: d }, { label: "<?php 
    echo esc_js(__('Open & Abandoned Carts', 'woocommerce'));
    ?>
", data: d2, yaxis: 1 } ], {
				 series: {
            	stack:true,
                lines: {
                	fill: true,
                    show: !0
                },
                points: {
                    show: 0
                }
            },
				grid: {
					show: true,
					aboveData: false,
					color: '#ccc',
					backgroundColor: '#fff',
					borderWidth: 2,
					borderColor: '#ccc',
					clickable: false,
					hoverable: true,
					markings: weekendAreas
				},
				xaxis: { 
					mode: "time",
					timeformat: "%d %b", 
					monthNames: <?php 
    echo json_encode(array_values($wp_locale->month_abbrev));
    ?>
,
					tickLength: 1,
					minTickSize: [1, "day"]
				},
				yaxes: [{
				position: "right",
                min: 0,
                tickSize: 10,
                tickDecimals: 0
            }, {
                position: "right",
                min: 0,
                tickDecimals: 2
            }],
            
            colors: [ "green","red"]
		 	});
		 	
		 	placeholder.resize();
	 	
			<?php 
    woocommerce_weekend_area_js();
    ?>
			<?php 
    woocommerce_tooltip_js_carts();
    ?>
			<?php 
    woocommerce_datepicker_js();
    ?>
		});
	</script>
<?php 
    wp_enqueue_script('carts-flot-carts-resize', get_bloginfo('url') . '/wp-content/plugins/woocommerce-cart-reports/assets/js/jquery.flot.resize.js');
    wp_enqueue_script('flot-stack', get_bloginfo('url') . '/wp-content/plugins/woocommerce-cart-reports/assets/js/jquery.flot.stack.min.js');
}
/**
 * Output the top earners chart.
 *
 * @access public
 * @return void
 */
function woocommerce_top_earners()
{
    global $start_date, $end_date, $woocommerce;
    $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : '';
    $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : '';
    if (!$start_date) {
        $start_date = date('Ymd', strtotime(date('Ym', current_time('timestamp')) . '01'));
    }
    if (!$end_date) {
        $end_date = date('Ymd', current_time('timestamp'));
    }
    $start_date = strtotime($start_date);
    $end_date = strtotime($end_date);
    // Get orders to display in widget
    add_filter('posts_where', 'orders_within_range');
    $args = array('numberposts' => -1, 'orderby' => 'post_date', 'order' => 'ASC', 'post_type' => 'shop_order', 'post_status' => 'publish', 'suppress_filters' => 0, 'tax_query' => array(array('taxonomy' => 'shop_order_status', 'terms' => array('completed', 'processing', 'on-hold'), 'field' => 'slug', 'operator' => 'IN')));
    $orders = get_posts($args);
    $found_products = array();
    if ($orders) {
        foreach ($orders as $order) {
            $order_items = (array) get_post_meta($order->ID, '_order_items', true);
            foreach ($order_items as $item) {
                if (isset($item['line_total'])) {
                    $row_cost = $item['line_total'];
                } else {
                    $row_cost = $item['cost'] * $item['qty'];
                }
                $found_products[$item['id']] = isset($found_products[$item['id']]) ? $found_products[$item['id']] + $row_cost : $row_cost;
            }
        }
    }
    asort($found_products);
    $found_products = array_reverse($found_products, true);
    $found_products = array_slice($found_products, 0, 25, true);
    reset($found_products);
    remove_filter('posts_where', 'orders_within_range');
    ?>
	<form method="post" action="">
		<p><label for="from"><?php 
    _e('From:', 'woocommerce');
    ?>
</label> <input type="text" name="start_date" id="from" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $start_date));
    ?>
" /> <label for="to"><?php 
    _e('To:', 'woocommerce');
    ?>
</label> <input type="text" name="end_date" id="to" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $end_date));
    ?>
" /> <input type="submit" class="button" value="<?php 
    _e('Show', 'woocommerce');
    ?>
" /></p>
	</form>
	<table class="bar_chart">
		<thead>
			<tr>
				<th><?php 
    _e('Product', 'woocommerce');
    ?>
</th>
				<th colspan="2"><?php 
    _e('Sales', 'woocommerce');
    ?>
</th>
			</tr>
		</thead>
		<tbody>
			<?php 
    $max_sales = current($found_products);
    foreach ($found_products as $product_id => $sales) {
        $width = $sales > 0 ? round($sales) / round($max_sales) * 100 : 0;
        $product = get_post($product_id);
        if ($product) {
            $product_name = '<a href="' . get_permalink($product->ID) . '">' . $product->post_title . '</a>';
            $orders_link = admin_url('edit.php?s&post_status=all&post_type=shop_order&action=-1&s=' . urlencode($product->post_title) . '&shop_order_status=completed,processing,on-hold');
        } else {
            $product_name = __('Product no longer exists', 'woocommerce');
            $orders_link = admin_url('edit.php?s&post_status=all&post_type=shop_order&action=-1&s=&shop_order_status=completed,processing,on-hold');
        }
        echo '<tr><th>' . $product_name . '</th><td width="1%"><span>' . woocommerce_price($sales) . '</span></td><td class="bars"><a href="' . $orders_link . '" style="width:' . $width . '%">&nbsp;</a></td></tr>';
    }
    ?>
		</tbody>
	</table>
	<script type="text/javascript">
		jQuery(function(){
			<?php 
    woocommerce_datepicker_js();
    ?>
		});
	</script>
	<?php 
}
    /**
     *
     */
    function sales()
    {
        global $start_date, $end_date, $woocommerce, $wpdb;
        $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : strtotime(date('Ymd', strtotime(date('Ym', current_time('timestamp')) . '01')));
        $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : strtotime(date('Ymd', current_time('timestamp')));
        if (!empty($_POST['start_date'])) {
            $start_date = strtotime($_POST['start_date']);
        }
        if (!empty($_POST['end_date'])) {
            $end_date = strtotime($_POST['end_date']);
        }
        $after = date('Y-m-d', $start_date);
        $before = date('Y-m-d', strtotime('+1 day', $end_date));
        $commission_due = $wpdb->get_var("\n\t\t\tSELECT SUM(total_due + total_shipping + tax) FROM {$wpdb->prefix}pv_commission WHERE status = 'due'\n\t\t\tAND     time >= '" . $after . "'\n\t\t\tAND     time <= '" . $before . "'\n\t\t");
        $reversed = $wpdb->get_var("\n\t\t\tSELECT SUM(total_due + total_shipping + tax) FROM {$wpdb->prefix}pv_commission WHERE status = 'reversed'\n\t\t\tAND     time >= '" . $after . "'\n\t\t\tAND     time <= '" . $before . "'\n\t\t");
        $paid = $wpdb->get_var("\n\t\t\tSELECT SUM(total_due + total_shipping + tax) FROM {$wpdb->prefix}pv_commission WHERE status = 'paid'\n\t\t\tAND     time >= '" . $after . "'\n\t\t\tAND     time <= '" . $before . "'\n\t\t");
        ?>

		<form method="post" action="">
			<p><label for="from"><?php 
        _e('From:', 'wc_product_vendor');
        ?>
</label> <input type="text"
																							 name="start_date" id="from"
																							 readonly="readonly"
																							 value="<?php 
        echo esc_attr(date('Y-m-d', $start_date));
        ?>
"/>
				<label for="to"><?php 
        _e('To:', 'wc_product_vendor');
        ?>
</label> <input type="text" name="end_date"
																						  id="to" readonly="readonly"
																						  value="<?php 
        echo esc_attr(date('Y-m-d', $end_date));
        ?>
"/>
				<input type="submit" class="button" value="<?php 
        _e('Show', 'wc_product_vendor');
        ?>
"/></p>
		</form>
		<script type="text/javascript">
			jQuery(function () {
				<?php 
        woocommerce_datepicker_js();
        ?>
			});
		</script>

		<div id="poststuff" class="woocommerce-reports-wrap">
			<div class="woocommerce-reports-sidebar">
				<div class="postbox">
					<h3><span><?php 
        _e('Total paid in range', 'wc_product_vendor');
        ?>
</span></h3>

					<div class="inside">
						<p class="stat"><?php 
        if ($paid > 0) {
            echo woocommerce_price($paid);
        } else {
            _e('n/a', 'wc_product_vendor');
        }
        ?>
</p>
					</div>
				</div>
				<div class="postbox">
					<h3><span><?php 
        _e('Total due in range', 'wc_product_vendor');
        ?>
</span></h3>

					<div class="inside">
						<p class="stat"><?php 
        if ($commission_due > 0) {
            echo woocommerce_price($commission_due);
        } else {
            _e('n/a', 'wc_product_vendor');
        }
        ?>
</p>
					</div>
				</div>
				<div class="postbox">
					<h3><span><?php 
        _e('Total reversed in range', 'wc_product_vendor');
        ?>
</span></h3>

					<div class="inside">
						<p class="stat"><?php 
        if ($reversed > 0) {
            echo woocommerce_price($reversed);
        } else {
            _e('n/a', 'wc_product_vendor');
        }
        ?>
</p>
					</div>
				</div>
			</div>

			<div class="woocommerce-reports-main">
				<div class="postbox">
					<h3><span><?php 
        _e('Recent Commission', 'wc_product_vendor');
        ?>
</span></h3>

					<div>
						<?php 
        $commission = $wpdb->get_results("\n\t\t\t\t\t\t\t\tSELECT * FROM {$wpdb->prefix}pv_commission\n\t\t\t\t\t\t\t\tORDER BY time DESC\n\t\t\t\t\t\t\t\tLIMIT 20\n\t\t\t\t\t\t\t");
        if (sizeof($commission) > 0) {
            ?>
							<div class="woocommerce_order_items_wrapper">
								<table id="commission-table" class="woocommerce_order_items" cellspacing="0">
									<thead>
									<tr>
										<th><?php 
            _e('Order', 'wc_product_vendor');
            ?>
</th>
										<th><?php 
            _e('Product', 'wc_product_vendor');
            ?>
</th>
										<th><?php 
            _e('Vendor', 'wc_product_vendor');
            ?>
</th>
										<th><?php 
            _e('Total', 'wc_product_vendor');
            ?>
</th>
										<th><?php 
            _e('Date &amp; Time', 'wc_product_vendor');
            ?>
</th>
										<th><?php 
            _e('Status', 'wc_product_vendor');
            ?>
</th>
									</tr>
									</thead>
									<tbody>
									<?php 
            $i = 1;
            foreach ($commission as $row) {
                $i++;
                ?>
										<tr<?php 
                if ($i % 2 == 1) {
                    echo ' class="alternate"';
                }
                ?>
>
											<td><?php 
                if ($row->order_id) {
                    ?>
<a
													href="<?php 
                    echo admin_url('post.php?post=' . $row->order_id . '&action=edit');
                    ?>
"><?php 
                    echo $row->order_id;
                    ?>
</a><?php 
                } else {
                    _e('N/A', 'wc_product_vendor');
                }
                ?>
											</td>
											<td><?php 
                echo get_the_title($row->product_id);
                ?>
</td>
											<td><?php 
                echo PV_Vendors::get_vendor_shop_name($row->vendor_id);
                ?>
</td>
											<td><?php 
                echo woocommerce_price($row->total_due + $row->total_shipping + $row->tax);
                ?>
</td>
											<td><?php 
                echo date(__('D j M Y \\a\\t h:ia', 'wc_product_vendor'), strtotime($row->time));
                ?>
</td>
											<td><?php 
                echo $row->status;
                ?>
</td>
										</tr>
									<?php 
            }
            ?>
									</tbody>
								</table>
							</div>
						<?php 
        } else {
            ?>
<p><?php 
            _e('No commission yet', 'wc_product_vendor');
            ?>
</p><?php 
        }
        ?>
					</div>
				</div>
			</div>
		</div>
	<?php 
    }
    function activations()
    {
        global $wpdb;
        $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : '';
        $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : '';
        if (!$start_date) {
            $start_date = date('Ymd', strtotime(date('Ym', current_time('timestamp')) . '01'));
        }
        if (!$end_date) {
            $end_date = date('Ymd', current_time('timestamp'));
        }
        $start_date = strtotime($start_date);
        $end_date = strtotime($end_date);
        ?>
		<form method="post" action="">
			<p><label for="from"><?php 
        _e('From:', 'woocommerce');
        ?>
</label> <input type="text" name="start_date" id="from" readonly="readonly" value="<?php 
        echo esc_attr(date('Y-m-d', $start_date));
        ?>
" /> <label for="to"><?php 
        _e('To:', 'woocommerce');
        ?>
</label> <input type="text" name="end_date" id="to" readonly="readonly" value="<?php 
        echo esc_attr(date('Y-m-d', $end_date));
        ?>
" /> <input type="submit" class="button" value="<?php 
        _e('Show', 'woocommerce');
        ?>
" /></p>
		</form>
		<script type="text/javascript">
			jQuery(function(){
				<?php 
        woocommerce_datepicker_js();
        ?>
			});
		</script>
		<?php 
        $activations = $wpdb->get_results("\n\t\t\tSELECT * FROM {$wpdb->prefix}woocommerce_software_activations as activations\n\t\t\tLEFT JOIN {$wpdb->prefix}woocommerce_software_licences as licences ON activations.key_id = licences.key_id\n\t\t\tWHERE date_format( activation_time ,'%Y%m%d') >= '" . date("Ymd", $start_date) . "'\n\t\t\tAND date_format( activation_time ,'%Y%m%d') <= '" . date("Ymd", $end_date) . "'\n\t\t\tORDER BY activation_time ASC\n\t\t\tLIMIT 50\n\t\t");
        if (sizeof($activations) > 0) {
            ?>
			<table id="activations-table" class="widefat" cellspacing="0">
				<thead>
			    	<tr>
			    		<th><?php 
            _e('Order', 'wc_software');
            ?>
</th>
			    		<th><?php 
            _e('Instance', 'wc_software');
            ?>
</th>
			    		<th><?php 
            _e('Software ID', 'wc_software');
            ?>
</th>
						<th><?php 
            _e('Licence Key', 'wc_software');
            ?>
</th>
						<th><?php 
            _e('Status', 'wc_software');
            ?>
</th>
						<th><?php 
            _e('Date &amp; Time', 'wc_software');
            ?>
</th>
						<th><?php 
            _e('Software Version', 'wc_software');
            ?>
</th>
						<th><?php 
            _e('Platform/OS', 'wc_software');
            ?>
</th>
					</tr>
				</thead>
				<tbody>
			    	<?php 
            $i = 1;
            foreach ($activations as $activation) {
                $i++;
                ?>
						<tr<?php 
                if ($i % 2 == 1) {
                    echo ' class="alternate"';
                }
                ?>
>
							<td><?php 
                if ($activation->order_id) {
                    ?>
<a href="<?php 
                    echo admin_url('post.php?post=' . $activation->order_id . '&action=edit');
                    ?>
"><?php 
                    echo $activation->order_id;
                    ?>
</a><?php 
                } else {
                    _e('N/A', 'wc_software');
                }
                ?>
</td>
							<td><?php 
                if ($activation->instance) {
                    echo $activation->instance;
                } else {
                    _e('N/A', 'wc_software');
                }
                ?>
</td>
							<td><?php 
                echo $activation->software_product_id;
                ?>
</td>
							<td><?php 
                echo $activation->licence_key;
                ?>
</td>
							<td><?php 
                echo $activation->activation_active ? __('Activated', 'wc_software') : __('Deactivated', 'wc_software');
                ?>
</td>
							<td><?php 
                echo date(__('D j M Y \\a\\t h:ia', 'wc_software'), strtotime($activation->activation_time));
                ?>
</td>
							<td><?php 
                echo $activation->software_version;
                ?>
</td>
							<td><?php 
                echo ucwords($activation->activation_platform);
                ?>
</td>
			      		</tr>
			    	<?php 
            }
            ?>
				</tbody>
			</table>
			<?php 
        } else {
            ?>
<p><?php 
            _e('No activations found.', 'wc_software');
            ?>
</p><?php 
        }
    }
function wcaf_report_daily()
{
    global $start_date, $end_date, $woocommerce, $wpdb;
    $start_date = isset($_POST['start_date']) ? $_POST['start_date'] : '';
    $end_date = isset($_POST['end_date']) ? $_POST['end_date'] : '';
    if (!$start_date) {
        $start_date = date('Ymd', strtotime(date('Ym', current_time('timestamp')) . '01'));
    }
    if (!$end_date) {
        $end_date = date('Ymd', current_time('timestamp'));
    }
    $start_date = strtotime($start_date);
    $end_date = strtotime($end_date);
    $amounts_deposited = 0;
    $num_deposits = 0;
    // Get orders to display in widget
    //add_filter( 'posts_where', 'orders_within_range' );
    if (version_compare(WC_VERSION, '2.2.0', '<')) {
        $args = array('numberposts' => -1, 'orderby' => 'post_date', 'order' => 'ASC', 'post_type' => 'shop_order', 'suppress_filters' => 0, 'meta_query' => array(array('key' => '_funds_deposited', 'value' => '1')), 'tax_query' => array(array('taxonomy' => 'shop_order_status', 'terms' => array('completed', 'processing', 'on-hold'), 'field' => 'slug', 'operator' => 'IN')));
    } else {
        $args = array('numberposts' => -1, 'orderby' => 'post_date', 'order' => 'ASC', 'post_type' => 'shop_order', 'post_status' => array('wc-completed', 'wc-processing', 'wc-on-hold'), 'suppress_filters' => 0, 'meta_query' => array(array('key' => '_funds_deposited', 'value' => '1')));
    }
    $orders = get_posts($args);
    $deposit_counts = array();
    $deposit_amounts = array();
    // Blank date ranges to begin
    $count = 0;
    $days = ($end_date - $start_date) / (60 * 60 * 24);
    if ($days == 0) {
        $days = 1;
    }
    while ($count < $days) {
        $time = strtotime(date('Ymd', strtotime('+ ' . $count . ' DAY', $start_date))) . '000';
        $deposit_counts[$time] = 0;
        $deposit_amounts[$time] = 0;
        $count++;
    }
    if ($orders) {
        foreach ($orders as $order) {
            $order_obj = new WC_Order($order->ID);
            $order_items_array = $order_obj->get_items();
            $time = strtotime(date('Ymd', strtotime($order->post_date))) . '000';
            foreach ($order_items_array as $item) {
                $item_id = isset($item['product_id']) ? $item['product_id'] : $item['id'];
                $product = X3M_AccountFunds::get_product($item_id);
                $is_deposit = get_post_meta($item_id, '_is_deposit', true);
                if ($is_deposit == 'yes') {
                    $num_deposits++;
                    $amounts_deposited += $product->get_price() * $item['qty'];
                    if (isset($deposit_counts[$time])) {
                        $deposit_counts[$time]++;
                    } else {
                        $deposit_counts[$time] = 1;
                    }
                    if (isset($deposit_amounts[$time])) {
                        $deposit_amounts[$time] = $deposit_amounts[$time] + $product->get_price() * $item['qty'];
                    } else {
                        $deposit_amounts[$time] = $product->get_price() * $item['qty'];
                    }
                }
                continue 2;
            }
        }
    }
    ?>
	<form method="post" action="">
		<p><label for="from"><?php 
    _e('From:', 'woocommerce');
    ?>
</label> <input type="text" name="start_date" id="from" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $start_date));
    ?>
" /> <label for="to"><?php 
    _e('To:', 'woocommerce');
    ?>
</label> <input type="text" name="end_date" id="to" readonly="readonly" value="<?php 
    echo esc_attr(date('Y-m-d', $end_date));
    ?>
" /> <input type="submit" class="button" value="<?php 
    _e('Show', 'woocommerce');
    ?>
" /></p>
	</form>

	<div id="poststuff" class="woocommerce-reports-wrap">
		<div class="woocommerce-reports-sidebar">
			<div class="postbox">
				<h3><span><?php 
    _e('Total deposits in range', 'wc_account_funds');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    if ($amounts_deposited > 0) {
        echo woocommerce_price($amounts_deposited);
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>
			<div class="postbox">
				<h3><span><?php 
    _e('Total deposits in range', 'wc_account_funds');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    if ($num_deposits > 0) {
        echo $num_deposits;
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>
			<div class="postbox">
				<h3><span><?php 
    _e('Average deposit in range', 'wc_account_funds');
    ?>
</span></h3>
				<div class="inside">
					<p class="stat"><?php 
    if ($amounts_deposited > 0) {
        echo woocommerce_price($amounts_deposited / $num_deposits);
    } else {
        _e('n/a', 'woocommerce');
    }
    ?>
</p>
				</div>
			</div>
		</div>
		<div class="woocommerce-reports-main">
			<div class="postbox">
				<h3><span><?php 
    _e('Deposits in range', 'wc_account_funds');
    ?>
</span></h3>
				<div class="inside chart">
					<div id="placeholder" style="width:100%; overflow:hidden; height:568px; position:relative;"></div>
				</div>
			</div>
		</div>
	</div>
	<?php 
    $deposit_counts_array = array();
    foreach ($deposit_counts as $key => $count) {
        $deposit_counts_array[] = array($key, $count);
    }
    $deposit_amounts_array = array();
    foreach ($deposit_amounts as $key => $amount) {
        $deposit_amounts_array[] = array($key, $amount);
    }
    $deposit_data = array('deposit_counts' => $deposit_counts_array, 'deposit_amounts' => $deposit_amounts_array);
    $chart_data = json_encode($deposit_data);
    ?>
	<script type="text/javascript">
		jQuery(function(){
			var deposit_data = jQuery.parseJSON( '<?php 
    echo $chart_data;
    ?>
' );
            console.log(deposit_data);
			var d = deposit_data.deposit_counts;
		    var d2 = deposit_data.deposit_amounts;

			for (var i = 0; i < d.length; ++i) d[i][0] += 60 * 60 * 1000;
		    for (var i = 0; i < d2.length; ++i) d2[i][0] += 60 * 60 * 1000;

			var placeholder = jQuery("#placeholder");

			var plot = jQuery.plot(placeholder, [ { label: "Number of deposits", data: d }, { label: "Deposit amount", data: d2, yaxis: 2 } ], {
				series: {
					lines: { show: true },
					points: { show: true }
				},
				grid: {
					show: true,
					aboveData: false,
					color: '#ccc',
					backgroundColor: '#fff',
					borderWidth: 2,
					borderColor: '#ccc',
					clickable: false,
					hoverable: true,
					markings: weekendAreas
				},
				xaxis: {
					mode: "time",
					timeformat: "%d %b",
					tickLength: 1,
					minTickSize: [1, "day"]
				},
				yaxes: [ { min: 0, tickSize: 10, tickDecimals: 0 }, { position: "right", min: 0, tickDecimals: 2 } ],
		   		colors: ["#8a4b75", "#47a03e"]
		 	});

		 	placeholder.resize();

			<?php 
    woocommerce_weekend_area_js();
    ?>
			<?php 
    woocommerce_tooltip_js();
    ?>
			<?php 
    woocommerce_datepicker_js();
    ?>
		});
	</script>
	<?php 
}