<?php
include('../include/dbset.php');
include('../include/session.php');

date_default_timezone_set('Africa/Gaborone');
$entry_date = date("Y-m-d H:i:s");
$today = date("Y-m-d");

$table_name = $_SESSION['db_prefix']."_alerts";
	$alert_query = "SELECT user_name, condition_1, send_alert, send_email FROM $table_name WHERE alert_name = 'Stock take' ";
	$alert_result = mySQL_query($alert_query);
	$alert_num = mysql_num_rows($alert_result);
	
	
			
	$i=0;
	$email_address = '';
	while ($i<$alert_num) {
		$user_name = mysql_result($alert_result, $i, "user_name");
		$send_alert = mysql_result($alert_result, $i, "send_alert");
		$send_email = mysql_result($alert_result, $i, "send_email");
		$condition_1 = mysql_result($alert_result, $i, "condition_1");
		
		$table_name = $_SESSION['db_prefix']."_stockloss";
		$stock_take_query = "SELECT date  FROM $table_name ORDER BY date DESC LIMIT 1";
		$stock_take_result = mySQL_query($stock_take_query);
		$stock_take_num = mysql_num_rows($stock_take_result);
		$stock_date = mysql_result($stock_take_result, 0, "date");
		
		$date1=date_create($stock_date);
		$date2=date_create($today);
		$diff=date_diff($date1,$date2);
		$days_difference = $diff->format("%a");
				
		if ($days_difference>$condition_1) {
		
		if ($send_alert=='yes') {
			$table_name = $_SESSION['db_prefix']."_alerts_store";
			$message_query = "INSERT INTO $table_name (user_name, department, generated, alert, detail_1, detail_2, detail_3 ) VALUES ('".$user_name."', 'store', '".$entry_date."', '33', '".$stock_date."', '".$days_difference."', '' ) ";
			execsql($message_query);
		}
		
		
		if ($send_email=='yes') {
			$table_name = $_SESSION['db_prefix']."_users";
			$address_query = "SELECT email FROM $table_name WHERE username = '".$user_name."' ";
			$address_result = mySQL_query($address_query);
			$email_address = mysql_result($address_result, 0, "email").', '.$email_address;
		}
		
		}
	$i++;	
	}


if ($email_address!='') {			
			$subject = "Stock take at Radstone Phakalane";
			$message = "<body><font face=Calibri size=3>Stock take was last done ".$days_difference." days ago on ".date("l, d-m-Y", strtotime($stock_date))."<br><br>For more info, login at <a href=costing.tocotex.com/bypass.php?c=rad&a=stock_take&r=".$stock_date."&e=>Radstone Phakalane Management Program</a>.<br><br><font face=Calibri size=3 color=red><b>This message comes from a non-responsive address, please do not reply</b></font><body>";
			include ('../include/alert_to_email.php');
		}

//session_destroy(); 			
	
?>

<script language="javascript" type="text/javascript">
          window.location="../admin_module/cron_job_select.php";
</script>