<?php

function send_smorre_test_mail() {

	// Plain text
	$email_body = 'Test mail'."\r\n".'Test sending of mail from php script';
	
	// Html body
	$email_body = "<div style='width:100%;padding 4 0 4 0;font-weight:bold;font-size:125%;text-align:center;'>Test HTML e-mail</div>";
	$email_body .= "<div style='width:100%;'>This is body text and <span style='color:red;'>this part is another color</span></div>";

	$this_var = array('to' => 'dcco@hotmail.com', 'subject' => 'Helkama lunch auto-update', 'message' => $email_body, 'html' => true);
	
	return send_mail($this_var);
}

function send_todays_orders($vars=null) {
	/*	
		$vars['date'] = override default date
		$vars['ignore_sent_mail'] = default = false
		$vars['send_to'] = override default send to
	*/
	include("includes/lunch/lunch_variables.php");
	include("languages/fin.php");
	global $now, $today;
	$debug_function = false;
	
	if($debug_function) {
		write_to_log("Function send_todays_orders called with variables ".json_encode($vars));
	}

	// setup Send mail recievers
	if(isset($vars['send_to']) ? $vars['send_to'] : null) {
		$to = $vars['send_to'];
	} else {
		$to = $day_order_send_to_list;
	}
	
	if(!(isset($vars['ignore_sent_mail']) ? $vars['ignore_sent_mail'] : false)) {
		// Check if orders-email have been sent allready
		$this_var = array('datetime_start' => $today." 00:00:00", 'datetime_end' => $today." 23:59:00", 'name' => 'todays_order_email');
		
		$result = get_scheduler_log($this_var);
		
		if($result !== false) {
			if(count($result) > 0) {
				// Email allready sent, return true and exit
				if($debug_function) write_to_log("Email allready sent, exit");
				return true;
			}
		} else {
			// Failed query, write to log (NOT IMPLEMENTED YET)
			if($debug_function) write_to_log("Could not get data for sent e-mail, exit");
			return false;
		}
		
		$log_email_send = true;
	} else {
		$log_email_send = false;
	}
	
	if(isset($vars['date']) ? $vars['date'] : null) {
		$use_date = $vars['date'];
	} else {
		$use_date = $today;
	}
	
	// Check that date is not closed
	if(is_lunch_closed_for_date($use_date)) {
		
		// Date is closed for lunch orders, send mail about it and exit
		
		$this_var = array('to' => $to, 'subject' => 'Helkama lunch todays-orders', 'message' => $l_Day." ".$l_Closed, 'html' => true);
		
		$query_values = "0, '".date("Y-m-d H:i:s", time())."', 'todays_order_email'";
		if(send_mail($this_var)) {
			$query_values .= ", 'Sent OK'";
			$send_status = true;
		} else {
			$query_values .= ", 'Send failed'";
			$send_status = false;
		}		
		$query = "INSERT INTO scheduler_log (scheduler_log_id, datetime, name, info) VALUES (".$query_values.")";
		
		return run_query($query);
	}
	
	// Gather data to send email
	$this_var = array('start_date' => $use_date." 00:00:00", 'end_date' => $use_date." 23:59:00");
	
	if(!$result = get_order_summary($this_var)) {
		
		// Failed to get data about todays orders, exit
		$this_var = array('to' => 'dcco@hotmail.com, info@smormagasinet.fi', 'subject' => 'Helkama lunch todays-orders', 'message' => 'Could not retrieve order summary ('.json_encode($result).')', 'html' => true);
		
		$query_values = "0, '".date("Y-m-d H:i:s", time())."', 'todays_order_email'";
		if(send_mail($this_var)) {
			$query_values .= ", 'Sent OK'";
			$send_status = true;
		} else {
			$query_values .= ", 'Send failed'";
			$send_status = false;
		}
		
		$query = "INSERT INTO scheduler_log (scheduler_log_id, datetime, name, info) VALUES (".$query_values.")";
				
		return run_query($query);
	}
	
	$orders_array = array();
	if(isset($result[$use_date])) {
		$orders_array = $result[$use_date];
	}

	$email_body = "";
	if($debug_function) write_to_log("Orders array consist of ".json_encode($orders_array));

	// Add guest orders
	if($guest_orders = get_guest_lunch_orders($this_var)) {
		$guest_department_id = get_department_id('Guests');
		foreach($guest_orders as $this_guest_order_id => $this_guest_order_data) {
			$this_guest_order_data['user_name'] = $this_guest_order_data['guest_name'];
			$orders_array[$this_guest_order_data['shift']][$this_guest_order_data['order_choise_id']][$guest_department_id][$this_guest_order_id] = $this_guest_order_data;
		}
	}
	
	$depart_choise_count = array();
	$dish_names = array();
	foreach($orders_array as $this_shift => $this_shift_orders) {
		if(is_array($this_shift_orders)) {
			
			foreach($this_shift_orders as $this_choise_id => $these_departments) {
				if(is_array($these_departments)) {
					foreach($these_departments as $this_departmnet_id => $this_department_orders) {
						$depart_choise_count[$this_shift][$this_departmnet_id][$this_choise_id] += count($this_department_orders);
						if(!isset($dish_names[$this_choise_id])) {
							foreach($this_department_orders as $order_id => $order_data) {
								if(!isset($dish_names[$this_choise_id])) {
									$dish_names[$this_choise_id] = $order_data['dish_name_fin'];
								}
							}
						}
					}
				}
			}
			
		}
	}

	$email_body = "";
	$total_count = 0;
	foreach($depart_choise_count as $this_shift => $these_departments) {
		$shift_total_count = 0;
		$dep_tmp_data = "";
		
		foreach($these_departments as $this_department_id => $department_choises) {
			$department_total_count = 0;
			$tmp_data = "";
			foreach($department_choises as $this_choise_id => $this_choise_count) {
				
				$tmp_data .= "<div style='display:block;width:100%;padding:2px 0px 2px 0px;'>";
					$tmp_data .= "<div style='display:inline-block;width:70%;'>";
					$tmp_data .= $dish_names[$this_choise_id];
					$tmp_data .= "</div>";
					$tmp_data .= "<div style='display:inline-block;width:30%;'>".$this_choise_count." kpl.</div>";
				$tmp_data .= "</div>";
				
				$department_total_count += $this_choise_count;
				$shift_total_count += $this_choise_count;
			}
			$dep_tmp_data .= "<div style='display:block;padding-top:8px;padding-left:12px;width:calc(100% - 12px);'><span style='font-weight:bold;font-size:95%;'>".$helkama_departments[$this_department_id]."</span> (".$department_total_count." kpl yht.)</div><div style='padding-left:22px;width:calc(100% - 22px);'>".$tmp_data."</div>";
			
		}
		
		if($email_body) $email_body .= "<div style='width:100%;height:8px;'></div><br>";
		$email_body .= "<div style='width:100%;margin-bottom:10px;padding-top:12px;'><div style='padding-bottom:4px;text-decoration: underline;'>".$shift_to_meal[$this_shift]." (".$shift_total_count." kpl yht):</div><div style=''>".$dep_tmp_data."</div></div>";
		
		$total_count += $shift_total_count;
	}

	if($email_body == "") {
		// If e-mail body is empty, set "no orders for today"
		$email_body .= "Ei tilauksia tänään";
	}

	$email_body = "<div style='font-weight:bold;font-size:120%;margin-top:15px;'>Tilaukset ".date("d.m.Y", strtotime($use_date))."</div><div style='width:350px;font-size:110%;'>".$email_body."</div>";

	if($debug_function) write_to_log("E-mail body created '".$email_body."' and will be sent to ".$to);
	
	// $email_body .= "\r\n"."\r\n".json_encode($orders_array);
	// $email_body .= "\r\n"."\r\n".json_encode($depart_choise_count);
	
	$email_body = "<div style='margin:auto;'><img src='".smormagasinet_logo()."' style='width:250px;'></div>".$email_body;

	$this_var = array('to' => $to, 'subject' => 'Helkama lunch todays-orders ('.$total_count.' kpl yht.)', 'message' => $email_body, 'html' => true);
	$query_values = "0, '".date("Y-m-d H:i:s", time())."', 'todays_order_email'";
	if(send_mail($this_var)) {
		$query_values .= ", 'Sent OK'";
		$send_status = true;
	} else {
		$query_values .= ", 'Send failed'";
		$send_status = false;
	}
	$query = "INSERT INTO scheduler_log (scheduler_log_id, datetime, name, info) VALUES (".$query_values.")";

	if($log_email_send) {
		return run_query($query);
	} else {
		return $send_status;
	}
}

function check_script_fn_run($fn_name, $set_time, $frame='15', $return_status=true, $runs=1, $try=5) {
	/*
		$fn_name = function identifier for log
		$set_time = time when scritp should run
		$frame = frame + set time = total timeframe to run script
		$runs = successfull runs per day (default 1)
		$try = failed tries per day (default 5)
	*/
	global $today;
	
	$selected_time_start = strtotime($today.' '.$set_time);
	$selected_time_end = $selected_time_start+$frame*60;
	$now_timestamp = time();
	
	if($now_timestamp > $selected_time_end OR $now_timestamp < $selected_time_start) {
		// Its either before or after start time + timeframe
		return false;
	}
	$success_alternative = array('Sent OK', 'Scheduled run OK');
	
	// Check if log has a success for fn
	$query = 'SELECT id, info FROM scheduler_log WHERE name="'.$fn_name.'" AND datetime>="'.$today.' 00:00:00" AND datetime<="'.$today.' 23:59:59"';

	if(!$result = run_query($query)) {
		// We cant determin if script have run
		return true;
	}
	
	$returndata = array('success' => 0, 'attempts' => 0);
	while($row = $result->fetch_assoc()) {
		if(in_array($row['info'], $success_alternative)) {
			$returndata['success']++;
		} else {
			$returndata['attempts']++;
		}
		
		if($return_status AND $returndata['success'] >= $runs OR $returndata['attempts'] >= $try) {
			return false;
		}
	}
	
	if($return_status)
		return true;
	
	return $returndata;
	
}

function log_script_run($vars) {
	/*
		$vars['name']
		$vars['info']
	*/

	$query = 'INSERT INTO scheduler_log VALUES (0, "'.date("Y-m-d H:i:s", time()).'", "'.$vars['name'].'", "'.$vars['info'].'")';
	
	return run_query($query);
	
}

function create_auto_lunch_menu() {
	include('languages/fin.php');
	global $today, $week_day;
	$debug_function = false;
	
	$this_var = array('datetime_start' => $today." 00:00:00", 'datetime_end' => $today." 23:59:00", 'name' => 'auto_lunch_menu_function');
	
	$result = get_scheduler_log($this_var);
	
	if($result !== false) {
		if(count($result) > 0) {
			// Email allready sent, return true and exit
			if($debug_function) write_to_log("Email allready sent, exit");
			return true;
		}
	} else {
		// Failed query, write to log (NOT IMPLEMENTED YET)
		if($debug_function) write_to_log("Could not get data for sent e-mail, exit");
		return false;
	}
	

	$next_week = get_week_year(null, date("W", time()), date("Y", time()), 'add');
	$next_week_dates = get_week_dates($next_week['week'], $next_week['year']);
	$save_choise_array = array('dish_name_fin' => 'Vaihtoehto 1', 'dish_name_swe' => 'Alternativ 1');
	
	$confirm_mail = '';
	
	foreach($next_week_dates as $this_date) {
		if(date("N", strtotime($this_date)) >5 )
			continue;
		
		$result = get_date_data(null, $this_date);
		$create_menu_for_shift = array('M' => true, "E" => true, "N" => false);
		$date_data_id = 0;
		
		// If menu found, set create_menu_for_shift to false if dish is found
		if((isset($result['date_data']['not_serving']) ? $result['date_data']['not_serving'] : 0) != 0) {
			// Date is closed, continue
			continue;
		} elseif(isset($result['menu'])) {
			foreach($shift_to_meal as $this_shift => $this_shift_name) {
				if(isset($result['menu'][$this_shift])) {
					foreach($result['menu'][$this_shift] as $this_menu_alt_id => $this_menu_alt_data) {
						if($this_menu_alt_data['dish_name_fin'] != "") {
							$create_menu_for_shift[$this_shift] = false;
						}
					}
				}
			}
		}
		
		//print $this_date.' => '.json_encode($create_menu_for_shift).';;'.json_encode($result).'<br>';

		// Create menu for each shift that is set to have menu created
		foreach($create_menu_for_shift as $this_shift => $this_shift_set_to) {
			if(!$this_shift_set_to) {
				continue;
			}
			
			if(!$date_data_id) {
				if(isset($result['date_data']['date_data_id'])) {
					$date_data_id = $result['date_data']['date_data_id'];
				} else {
					if(!$date_data_id = save_date_data(array('date' => $this_date, 'not_serving' => 0, 'notes' => ''))) {
						$confirm_mail .= '<div>Could not create date_data for '.$this_date.', skip menu for '.$shift_to_meal[$this_shift].'</div>';
						continue;
					}
				}
			}
			
			$this_save_choise_array = $save_choise_array;
			$this_save_choise_array['date_data_id'] = $date_data_id;
			$this_save_choise_array['shift'] = $this_shift;
			if(save_choise($this_save_choise_array)) {
				$confirm_mail .= '<div>Success: Menu created for '.$this_date.' / '.$shift_to_meal[$this_shift].' ('.$save_choise_array['dish_name_fin'].' / '.$save_choise_array['dish_name_swe'].')</div>';
			} else {
				$confirm_mail .= '<div>Error: Could not save dish for '.$this_date.' / '.$shift_to_meal[$this_shift].'</div>';
			}
		}
		
	}
	
	if(!$confirm_mail) {
		$confirm_mail .= '<div>Menu found for week '.$next_week['week'].'</div>';
	}
	
	$email_body = "<div style='margin:auto;'><img src='".smormagasinet_logo()."' style='width:250px;'></div>".$confirm_mail;
	
	$this_var = array('to' => $to, 'subject' => 'Auto-menu build for '.$next_week['week'].'/'.$next_week['year'], 'message' => $email_body, 'html' => true);

	if(send_mail($this_var)) {
		$set_log_status = 'Sent OK';
	} else {
		$set_log_status = 'Send failed';
	}

	log_script_run(array('info' => $set_log_status, 'name' => 'auto_lunch_menu_function'));
}

function auto_send_week_stats($vars=null) {
	/*
		$vars['week'] = week to send (default previous)
		$vars['year'] = year  (if week provided)
		$vars['ignore_sent_mail'] = default = false
		$vars['send_to'] = override default send to
	*/
	include("languages/fin.php");
	global $now, $today;
	$target_file = 'files/auto_week_report.csv';
	$target_file_location = '';
	$target_file_location = '/home/dc/smormagasinet.dcnet.fi/';
	$email_body = '';
	$debug_function = false;

	if(!(isset($vars['ignore_sent_mail']) ? $vars['ignore_sent_mail'] : false)) {
		// Check if orders-email have been sent allready
		$this_var = array('datetime_start' => $today." 00:00:00", 'datetime_end' => $today." 23:59:00", 'name' => 'auto_send_week_report');
		
		$result = get_scheduler_log($this_var);
		
		if($result !== false) {
			if(count($result) > 0) {
				// Email allready sent, return true and exit
				if($debug_function) write_to_log("Email allready sent, exit");
				return true;
			}
		} else {
			// Failed query, write to log (NOT IMPLEMENTED YET)
			if($debug_function) write_to_log("Could not get data for sent e-mail, exit");
			return false;
		}
		
		$log_email_send = true;
	} else {
		$log_email_send = false;
	}

	// Get settings
	$auto_send_report_settings = get_auto_send_week_report_settings();

	// Get target e-mails
	$to = '';
	foreach($auto_send_report_settings['recipients'] as $this_user_id => $this_user_recipients) {
		foreach($this_user_recipients as $this_recipient) {
			if(strpos($to, $this_recipient) !== false) {
				continue;
			}
			$to .= ', '.$this_recipient;
		}
	}
	$to = substr($to, 2);

	// Create report
	$this_var = array();
	if(isset($vars['week'])) {
		if(!isset($vars['year'])) {
			$vars['year'] = date('Y', time());
		}
		
	} else {
		$vars['week'] = date("W", time());
		$vars['year'] = date("Y", time());
		
		$week_dates = get_week_dates($vars['week'], $vars['year']);
		
		$vars['week'] = date('W', strtotime($week_dates[0].' -1 week'));
		$vars['year'] = date('Y', strtotime($week_dates[0].' -1 week'));
		
	}

	$week_dates = get_week_dates($vars['week'], $vars['year']);
	
	$this_var['start_date'] = $week_dates[0];
	$this_var['end_date'] = $week_dates[6];
	
	$result = get_timeframe_report_details($this_var);

	$csv_dump = '';

	// Prepare stats
	$shift_meal_counter = array();
	$unique_users = 0;
	foreach($shift_to_meal as $shift => $shift_meal) {
		$shift_meal_counter[$shift] = 0;
	}

	foreach($result as $this_worker_id => $this_worker_data) {
		$this_user_data = lunch_get_user_data($this_worker_id);
		
			foreach($shift_to_meal as $shift => $shift_meal) {
				if(!isset($this_worker_data[$shift])) {
					continue;
				}
				
				$shift_meal_counter[$shift] += $this_worker_data[$shift];
				$csv_dump .= $this_user_data['workernbr'].';'.$this_user_data['user_name'].';'.$shift_to_meal[$shift].';'.$this_worker_data[$shift]."\r\n";
			}
		$unique_users++;
	}	

	// Dump to csv file
	if($file_handler = fopen($target_file_location.$target_file, 'w')) {
		fwrite($file_handler, utf8_decode($csv_dump));
		fclose($file_handler);
	}
	
	if(!file_exists($target_file_location.$target_file)) {
		// File was not created successfully
		return false;
	}
	
	$email_body .= '<div style="text-align:center;" class=""><h1>Viikko raportti '.$vars['week'].'/'.$vars['year'].'</h1></div>';
	$email_body .= '<div style="text-align:center;" class=""><a href="https://smormagasinet.dcnet.fi/'.$target_file.'">Lataa csv tiedosto</a></div>';
	$email_body .= '<div style="text-align:center;margin-top:5px;" class="">';
		$email_body .= '<div style="text-decoration:underline;font-weight:bold;padding: 2px 0px;">';
			$email_body .=  'Tilattu : ';
		$email_body .= '</div>';
		foreach($shift_meal_counter as $this_shift => $this_shift_count) {
			$email_body .= '<div style="padding: 1px 0px 1px 5px;">';
				$email_body .=  $shift_to_meal[$this_shift].' : '.$this_shift_count.' kpl';
			$email_body .= '</div>';
		}
	$email_body .= '</div>';
	
	$email_body = "<div style='text-align:center;'><img src='".smormagasinet_logo()."' style='width:250px;'></div>".$email_body;
	
	$this_var = array('to' => $to, 'subject' => 'Lounas viikko raportti', 'message' => $email_body, 'html' => true);

	$query_values = "0, '".date("Y-m-d H:i:s", time())."', 'auto_send_week_report'";

	if(send_mail($this_var)) {
		$query_values .= ", 'Sent OK'";
		$send_status = true;
	} else {
		$query_values .= ", 'Send failed'";
		$send_status = false;
	}
	$query = "INSERT INTO scheduler_log (scheduler_log_id, datetime, name, info) VALUES (".$query_values.")";

	if($log_email_send) {
		return run_query($query);
	} else {
		return $send_status;
	}
}

?>