<?php



	

		

	

	$current_year  = isset($_GET['year']) ? intval($_GET['year']) : date('Y');

	$current_month = isset($_GET['month']) ? intval($_GET['month']) : date('n');

	

	$where_date = $wpdb->prepare(

		"AND YEAR(p.post_date) = %d AND MONTH(p.post_date) = %d",

		$current_year,

		$current_month

	);



	

	$orders_query = "

		SELECT p.ID, p.post_date, pt.meta_value AS total

		FROM $wpdb->posts p

		JOIN $wpdb->postmeta pt ON p.ID = pt.post_id

		WHERE pt.meta_key = '_order_total'

		AND p.post_type = 'shop_order'

		AND p.post_status IN ('wc-completed', 'wc-processing')

		$where_date

	";



	



	$orders_list = $wpdb->get_results($orders_query);



	



	//pree($orders_query);



	



	//pree($orders_list);



	



	$dates_arr = array();



	



	$continue_day = 0;



	$last_day = 0;



	$month_year = '';



	



	if(!empty($orders_list)){



		$orders_arr = array();



		foreach($orders_list as $orders_data){



			$key = date('Y-m-d', strtotime($orders_data->post_date));



			if(!$last_day){



				$last_day = date('t', strtotime($key));



				$month_year = date('M, Y', strtotime($key));



			}



			$orders_arr[$key][] = $orders_data;



		}



		//echo $last_day;



		if(!empty($orders_arr)){



			



			foreach($orders_arr as $orders_date=>$order_detail){



				//pree($orders_date);



				//pree($order_detail);



				



				$order_elem_total = array_map(function($order_elem){ return $order_elem->total; }, $order_detail);



				$order_total = (is_array($order_elem_total)?array_sum($order_elem_total):0);



				



				



				//pree($order_elem_sum);



				//echo $orders_date.' > '.count($order_detail).' > $'.$order_total.'<br />';



				$continue_day = date('j', strtotime($orders_date));



				$dmy = date('j M, Y', strtotime($orders_date));



				$orders_date = $dmy.' - $'.$order_total;



				if(array_key_exists($dmy, $dates_arr)){ unset($dates_arr[$dmy]); }



				$dates_arr[$orders_date] = count($order_detail);//.' ('.get_woocommerce_currency_symbol().$order_total.')';



				



				//pree($continue_day);



			}



			//ksort($dates_arr);



			



			



			



			for($d=($continue_day+1); $d<=$last_day; $d++){



				$dates_arr[$d.' '.$month_year] = 0;



			}



		}



	}



	



	$hourly_unit = 10; //minutes



	//pree($dates_arr);

	

	// Get all unique years and months with at least one order

	$results = $wpdb->get_results("

		SELECT 

			YEAR(post_date) AS order_year,

			MONTH(post_date) AS order_month,

			COUNT(ID) AS total_orders

		FROM {$wpdb->prefix}posts

		WHERE post_type = 'shop_order'

		  AND post_status IN ('wc-completed', 'wc-processing')

		GROUP BY order_year, order_month

		ORDER BY order_year DESC, order_month DESC

	");

	

	$calendar = [];

	foreach ($results as $row) {

		$year = $row->order_year;

		$month = $row->order_month;

		$month_name = date("F", mktime(0, 0, 0, $month, 10));

		$calendar[$year][] = [

			'month' => $month,

			'label' => $month_name,

			'count' => $row->total_orders,

		];

	}

	

	$peak_sales = $wpdb->get_results("

		SELECT

			YEAR(post_date) AS order_year,

			MONTH(post_date) AS order_month,

			DATE(post_date) AS sale_day,

			COUNT(ID) AS daily_orders

		FROM {$wpdb->prefix}posts

		WHERE post_type = 'shop_order'

		  AND post_status IN ('wc-completed', 'wc-processing')

		GROUP BY order_year, order_month, sale_day

		ORDER BY daily_orders DESC

	");

	

	$peak_by_month = [];



	foreach ($peak_sales as $row) {

		$key = $row->order_year . '-' . str_pad($row->order_month, 2, '0', STR_PAD_LEFT);

		

		if (!isset($peak_by_month[$key]) || $row->daily_orders > $peak_by_month[$key]->daily_orders) {

			$peak_by_month[$key] = $row;

		}

	}

	

		

	$is_current_month = ($current_year == date('Y') && $current_month == date('n'));

	$label_prefix = $is_current_month ? __('Projected', 'si-system') : __('Total', 'si-system');

	

	$total_orders = array_sum(array_values($dates_arr));

	$days_passed = $is_current_month ? date('j') : cal_days_in_month(CAL_GREGORIAN, $current_month, $current_year);

	$total_days = cal_days_in_month(CAL_GREGORIAN, $current_month, $current_year);

	

	$avg_daily_orders = $days_passed > 0 ? $total_orders / $days_passed : 0;

	$projected_orders = round($avg_daily_orders * $total_days);

	

	$total_sales_value = 0;

	foreach ($orders_list as $order) {

		$total_sales_value += floatval($order->total);

	}

	$avg_daily_revenue = $days_passed > 0 ? $total_sales_value / $days_passed : 0;

	$projected_revenue = round($avg_daily_revenue * $total_days, 2);



?>



<div class="woocommerce-sales-dropdown" style="max-width:400px;">

	<select class="form-control" onchange="if(this.value) window.location.href=this.value;">

		<option value=""><?php _e('Select Sales Period', 'si-system'); ?></option>

		<?php foreach ($calendar as $year => $months): ?>

            <optgroup label="<?php echo esc_attr($year); ?>">

                <?php foreach ($months as $m): 

					$is_selected = ($year == $current_year && $current_month == $m['month']);

                    $key = $year . '-' . str_pad($m['month'], 2, '0', STR_PAD_LEFT);

                    $peak_info = '';

                    if (isset($peak_by_month[$key])) {

                        $m['peak_day'] = $peak_by_month[$key]->sale_day;

                        $m['peak_orders'] = $peak_by_month[$key]->daily_orders;

                        $peak_info = ' - '.sprintf(__('Peak: %s (%d)', 'si-system'), date('M j', strtotime($m['peak_day'])), $m['peak_orders']);

                    }

                    

                    $link = admin_url('admin.php?page=wpsis&t=0&year=' . $year . '&month=' . $m['month']); ?>

                    

                    <option value="<?php echo esc_url($link); ?>" <?php selected($is_selected); ?>>

                        <?php echo esc_html(sprintf(__('%s %d (%d)%s', 'si-system'), $m['label'], $year, $m['count'], $peak_info)); ?>

                    </option>

                <?php endforeach; ?>

            </optgroup>



		<?php endforeach; ?>

	</select>

</div>



<div class="projected-sales-summary" style="background:#fff3f5;border:1px solid #f5c2c7;padding:15px;margin:20px 0;border-left:5px solid #d63384;">

    <h4 style="margin-top:0;">📊 <?php echo sprintf(__('%s Sales — %s', 'si-system'), $label_prefix, date('F Y', mktime(0, 0, 0, $current_month, 1, $current_year))); ?></h4>

    <p><strong><?php echo $label_prefix; ?> <?php _e('Orders:', 'si-system'); ?></strong> <?php echo number_format($projected_orders); ?></p>

    <p><strong><?php echo $label_prefix; ?> <?php _e('Revenue:', 'si-system'); ?></strong> <?php echo wc_price($projected_revenue); ?></p>

</div>





<div title="<?php echo $hourly_unit; ?> minutes"



  class="countdown-container"



  data-duration="<?php echo $hourly_unit*60; ?>"



  data-transition="linear"



  data-color="rgb(230, 119, 140)"



  data-size="90"



  data-position="center"



></div>







		<div style="width: 100%">



			<canvas id="wpsis_sales_per_day"></canvas>



		</div>



        



<script type="text/javascript" language="javascript">



	<?php 

	

		if(!empty($dates_arr)){

	

			uksort($dates_arr, function ($a, $b) {

				return strnatcmp($a, $b);

			});	

	

	?>



	



	var hourly_unit = parseInt('<?php echo $hourly_unit; ?>');



	var xValues = <?php echo json_encode(array_keys($dates_arr)); ?>; // Converts PHP array keys to JSON array



	var yValues = <?php echo json_encode(array_values($dates_arr)); ?>; // Converts PHP array values to JSON array



	



	var chart_data = {



	  labels: xValues,



	  datasets: [{



		  label: 'Sales Per Day',



		  backgroundColor:'rgba(255, 99, 132, 0.2)',



		  borderColor: 'rgb(255, 99, 132)',



		  borderWidth: 1,



		  data: yValues



		}],



	};



	



	const sales_per_day_chart = new Chart(document.getElementById("wpsis_sales_per_day"), {



	  type: "bar",



	  



	  data: chart_data,



	  options: {



		  scales: {



				  y: {



					beginAtZero: true



				  }



				}		  



		}



	});



	



	setTimeout(function(){ if(jQuery('div.si_dashboard').is(':visible')){ document.location.reload(); } }, (1000*60*hourly_unit)-1000);



	



	<?php } ?>



	



</script>       