<?php
	
	/* HARDCODED VALUES */
	
	$var_max_km_per_day = 500;

	date_default_timezone_set("Europe/Ljubljana");
	if (isset($_POST) && !empty($_POST)) {
		/* GENERATE DAYS AND IT'S PROPERTIES (weekend/workday) */
		$startDate 	= strtotime($_POST['datum_od']);
		$endDate 	= strtotime($_POST['datum_do']);
		
		$temp = $startDate;
		
		while ($temp <= $endDate+(60*60*24)) {
			if (in_array(date("w",$temp),array(0,6))) {	//check if weekend
				$arr_days[] = array(
					'date' 	=> date("d.m.Y",$temp),
					'type'	=> 'weekend'
				);
			} else {									//is regular day
				$arr_days[] = array(
					'date' 	=> date("d.m.Y",$temp),
					'type'	=> 'workday'
				);
			}
			$temp = $temp+(60*60*24);
		};
		
		/* CREATE LOCATIONS ARRAY CONSIDERING IT'S WEIGHTS */
		$arr_locations = $db->select("SELECT * FROM tbl_pot ORDER BY teza DESC");
		//krumo($arr_locations);
		foreach ($arr_locations as $pot) {
			for ($i=0; $i!=$pot['teza']; $i++) {
				$arr_pot_trunk[] = $pot;
			}
		}
		//krumo($arr_pot_trunk);			//tukaj je še urejeno po teza DESC
		
		/* GENERATE IMAGINARY TRIPS */
		
		$price_goal 	= $_POST['znesek'];
		$price_sum		=0;
		$distance_sum	=0;
		$price_temp		=0;
		$distance_temp	=0;
		$price_temp_check=0;
		$i 				= 0;	//iteration
		while ($price_temp_check < $price_goal) {
			shuffle($arr_pot_trunk);	//randomize!
			$i++;
			
			foreach ($arr_pot_trunk as $pot) {
				$trip_cost 			 = ($pot['km']*$_POST['kilometrina']);
				$price_temp_check 	+= ($trip_cost*2);			// *2 => tja in nazaj!!!
				
				if ($price_temp_check > $price_goal) {
					break;	//TODO: Try to maximize price
				}
				
				$picked_day = $arr_days[rand(0,count($arr_days)-1)]['date'];
				
				//if picked day doesn't exist yet
				if (!isset($final_array[strtotime($picked_day)])) {
					$final_array[strtotime($picked_day)] = array();	//create it
				}

				//count day km
				$day_km=0;
				foreach($final_array[strtotime($picked_day)] as $date => $trip) {
					$day_km += $trip['trip_distance'];
				}
				if ($day_km <= $var_max_km_per_day) {
				
					$price_temp 	+= $trip_cost;	//ena smer!
					$distance_temp 	+= $pot['km'];	//ena smer!
					$arr_price_growth[] = $price_temp;
					
					$final_array[strtotime($picked_day)][] = array(
						"trip_price" 	=> ($pot['km']*$_POST['kilometrina']),
						"trip" 			=> "{$pot['od']} - {$pot['do']}",
						"trip_distance"	=> $pot['km'],
						"trip_date"		=> $picked_day,
						"price_sum"		=> $price_temp,
						"distance_sum"	=> $distance_temp
					);
					
					if (!$pot['zakljucena'])
					{
						############ Povratek #############
						$price_temp 	+= $trip_cost;	//druga smer!
						$distance_temp 	+= $pot['km'];	//druga smer!
						$arr_price_growth[] = $price_temp;
						
						
						$final_array[strtotime($picked_day)][] = array(
							"trip_price" 	=> ($pot['km']*$_POST['kilometrina']),
							"trip" 			=> "{$pot['do']} - {$pot['od']}",
							"trip_distance"	=> $pot['km'],
							"trip_date"		=> $picked_day,
							"price_sum"		=> $price_temp,
							"distance_sum"	=> $distance_temp
						);
					}
				} else {
					$price_temp_check 	-= ($trip_cost*2);			// *2 => tja in nazaj!!!
				}
			}
		}
		//dump($arr_price_growth);
		$last_elt = end($x = end($final_array));
		ksort($final_array);
		krumo($final_array);
		
		//print_r($final_array);
		$serija=getSerija();
		vstaviNalog($_POST['datum_od'],$_POST['datum_do'],$_POST['znesek'],$_POST['kilometrina'],$last_elt['price_sum'],$last_elt['distance_sum'], $_POST['avto_id'],$serija);
	
		$cena= zapisi($final_array, $serija);

	}
	
	function zapisi($final_array, $serija){
		$link = mysql_connect('localhost', 'pcpomoc_potni', 'boroko');
		//$link = mysql_connect('localhost', 'root', '');
		mysql_select_db('pcpomoc_potni', $link);
		mysql_query("SET NAMES 'utf8'") or die(mysql_error());
		mysql_query("SET lc_time_names = 'sl_SI'") or die(mysql_error());

		$c=0;
	
		foreach ($final_array as $key => $value)
			foreach ($value as $nr => $trip){
			$c+=number_format($trip['trip_price'],2);
			$datum=$trip['trip_date'];
			$pot=$trip['trip'];
			$km=number_format($trip['trip_distance'],2);
			$cena=number_format($trip['trip_price'],2);
			$sql = "INSERT INTO nalog (datum, pot, km, cena, serija)
			VALUES ('$datum','$pot','$km','$cena','$serija')";
			
			mysql_query($sql);
		}
		mysql_close($link);
		
		return $c;
	}
	
	function getIzpisi(){
		$con = mysql_connect('localhost','pcpomoc_potni','boroko');
		if (!$con){
			echo('Could not connect: ' . mysql_error());
		}
		mysql_select_db("pcpomoc_potni", $con);
		mysql_query("SET NAMES 'utf8'") or die(mysql_error());
		mysql_query("SET lc_time_names = 'sl_SI'") or die(mysql_error());
		$result=mysql_query("SELECT DISTINCT(serija) AS serija FROM nalog");
		while ( $results[] = mysql_fetch_object ( $result ) );
		array_pop ( $results );
		return $results;
		mysql_close($con);
	}
	function vstaviNalog($datumod, $datumdo, $znesek, $kilometrina,$skupnacena, $skupajkm, $avto, $serija){
		$link = mysql_connect('localhost', 'pcpomoc_potni', 'boroko');
		//$link = mysql_connect('localhost', 'root', '');
		mysql_select_db('potni_stroski', $link);
		mysql_query("SET NAMES 'utf8'") or die(mysql_error());
		mysql_query("SET lc_time_names = 'sl_SI'") or die(mysql_error());

		$sql = "INSERT INTO tbl_nalog (datum_od, datum_do, znesek, kilometrina, skupna_cena, skupaj_km, avto_id, serija)
		VALUES ('$datumod','$datumdo','$znesek','$kilometrina','$skupnacena','$skupajkm','$avto','$serija')";
			
		mysql_query($sql);
		mysql_close($link);
	}
	function getSerija(){
		
	$con = mysql_connect("localhost","pcpomoc_potni","boroko");
	if (!$con){
		echo('Could not connect: ' . mysql_error());
	}
	mysql_select_db("pcpomoc_potni", $con);
	mysql_query("SET NAMES 'utf8'") or die(mysql_error());
	mysql_query("SET lc_time_names = 'sl_SI'") or die(mysql_error());
	$result=mysql_query("SELECT serija FROM tbl_nalog ORDER BY serija DESC");
	
	$row=mysql_fetch_array($result);
	$serija=$row['serija'];
	
	if(sizeOf($row)!=0)
		return $serija+1;
	else
		return 1;
	
	mysql_close($con);
	}
?>