<?php
$lngModule_tmp = isset($lngModule) ? $lngModule : "";
$lngFile_tmp = isset($lngFile) ? $lngFile : "";
$lngModule = "weather_advanced";
$lngFile = basename(__FILE__);
if(isset($module_params) && is_array($module_params) && count($module_params) >0) {
	$q_ws = "select * from module where module_id='$mc_module_id';";
	$r_ws = @mysql_query($q_ws);
	if($r_ws && mysql_num_rows($r_ws)>0) {
		$row_ws = mysql_fetch_assoc($r_ws);
		$weather_advanced_title = stripslashes($row_ws["title_$lang2iso"]);
	}
	
	$current_catdom_module_id = $module_params['catdom_module_id'];
	
	// Pull in the NuSOAP code
	require_once("$modules_path/wsbin/lib/nusoap.php");
	include_once("$modules_path/$module_dir/functions.php");
	
	//$webservices_url = "http://localhost/webservices/cyws/srvdispatcher.php?wsdl";
	$webservices_url = "http://www.apps24.com/srvdispatcher.php?wsdl";

	$adv_weather_debug = false;
	if(isset($_REQUEST['adv_weather_debug'])) $adv_weather_debug = true;
	$out_path_cache = str_ireplace("general", "", $general_path);
	$all_cache_folder = "$out_path_cache/all_cache";
	$all_cache_folder = str_ireplace("//", "/", $all_cache_folder);
	$all_cache_weather = "$all_cache_folder/weather";
	
	$city_name_list = $module_params['cities_list'];
	$ws_request_current = array(
		'server_name' 		=> 'weather',
		'function_name'		=> 'getCitiesWeather',
		'function_params'	=> base64_encode(serialize($city_name_list))
	);
	
	$ws_request_fiveday = array(
		'server_name' 		=> 'weather',
		'function_name'		=> 'getCitiesWeatherFiveday',
		'function_params'	=> base64_encode(serialize($city_name_list))
	);
	
	/* Check if cache folders are in place ******************************************************/
	if(!file_exists("$all_cache_folder") || !is_dir("$all_cache_folder")) {
		if( mkdir("$all_cache_folder", 0777) ) {
			if($adv_weather_debug) echo "<br/>$all_cache_folder created";
			
			if( mkdir("$all_cache_weather", 0777) ) {
				if($adv_weather_debug) echo "<br/>$all_cache_weather created";
			}
			else {
				if($adv_weather_debug) echo "<br/>Cannot create dir [$all_cache_weather]";
			}
		}
		else {
			if($adv_weather_debug) echo "<br/>Cannot create dir [$all_cache_folder]";
		}
	}
	else {
		if(!file_exists("$all_cache_weather") || !is_dir("$all_cache_weather")) {
			if( mkdir("$all_cache_weather", 0777) ) {
				//chmod("$general_path/all_cache/weather", 777);
				if($adv_weather_debug) echo "<br/>$all_cache_weather created";
			}
			else {
				if($adv_weather_debug) echo "<br/>Cannot create dir [$all_cache_weather]";
			}
		}
	}
	/* END Check for cache folders  *************************************************************/
	
	$have_it_on_cache = false;
	$md5 = md5(serialize($ws_request_current));
	
	if($adv_weather_debug) {
		echo '<pre>',print_r($ws_request_current),'</pre>';
	}
	
	$cache_file = $all_cache_weather . "/" . $md5;
	if(file_exists($cache_file)) {
		//echo "<br/>[$cache_file] exists";
		$cache_time = filemtime($cache_file);
		$current_time = time();
		if($current_time - $cache_time < 7200) {
			$have_it_on_cache = true;
			//echo "<br/>$cache_file time is earlier than 15 min";
		}
		else {
			unlink($cache_file);
			//echo "<br/>$cache_file time is older than 15 min";
		}
	}
	
	$got_the_weather = false;
	
	if($have_it_on_cache) {
		$cache_get = file_get_contents($cache_file);
	
		if($cache_get != "") {
			$cache_get = unserialize($cache_get);
	
			if(isset($cache_get[0]) && is_array($cache_get[0])) {
				$weather_current = $cache_get[0];
				if(count($weather_current) > 0) {
					$got_the_weather = true;
				}
			}
			
			if(isset($cache_get[1]) && is_array($cache_get[1])) {
				$weather_fiveday = $cache_get[1];
			}
		}
	}
	if(!$have_it_on_cache || !$got_the_weather) {
		$weather_current = getCurrentCityWeather($webservices_url, $ws_request_current);
		$weather_fiveday = getCurrentCityWeather($webservices_url, $ws_request_fiveday);
		
		if($adv_weather_debug) {
			echo '<pre>',print_r($weather_current),'</pre>';
			echo '<pre>',print_r($weather_fiveday),'</pre>';
		}
		
		//echo "<br/>DO NOT Have it on cache";
		$cache_put = serialize(array($weather_current, $weather_fiveday));
		if( true == ($fc = fopen($cache_file, "w") ) ) {
			
			if($adv_weather_debug) {
				echo '<write in cache> ',$cache_put;
			}
			
			fwrite($fc, $cache_put, strlen($cache_put));
			fclose($fc);
			@chmod($cache_file, 0777);
		}
	}
	
	//pre_($weather_fiveday);
	
	//$module_default_scale = isset($module_params['module_default_scale']) ? $module_params['module_default_scale'] : "c";
	//$module_show_title = isset($module_params['module_show_title']) ? $module_params['module_show_title'] : 1;
	//$module_show_title = isset($module_params['module_show_title']) ? $module_params['module_show_title'] : 1;
	
	$c_to_f = isset($module_default_scale) ? $module_default_scale : "c";
	if(isset($_REQUEST['show_scale']) && $_REQUEST['show_scale'] == "f") {
		$c_to_f = "f";
	}
	elseif(isset($_REQUEST['show_scale']) && $_REQUEST['show_scale'] == "c") {
		$c_to_f = "c";
	}
	?>
	<div class="middle_module_container weather_advanced_container">
		<?php
		if($module_show_title == 1) {
			?>
			<div class="middle_module_title_container weather_advanced_title_container">
				<div class="middle_module_title weather_advanced_title">
					<p><span><?php echo tx("$weather_advanced_title");?></span></p>
				</div>
				<div class="middle_module_title_image weather_advanced_title_image"></div>
			</div>
			<?php
		}
		
		if($module_change_scale == 1 || $module_show_print_link == 1) {
			?>
			<div class="weather_tools">
				<table cellpadding="0" cellspacing="0" border="0">
					<tr>
					<?php
					if($module_change_scale == 1) {
						if($c_to_f == "c") { 
							$scale_name = "Fahrenheit (&deg;F)";
							$scale_unit = "f";
						}
						if($c_to_f == "f") {
							$scale_name = "Celsius (&deg;C)";
							$scale_unit = "c";
						}
						
						$weather_link = $_SERVER['REQUEST_URI'];
						if(($qmark = strpos($weather_link, "?")) === false) {
							$weather_link .= "?show_scale=" . $scale_unit;
						}
						else {
							$qs = substr($weather_link, $qmark, strlen($weather_link)-1);
							if($qs == "?") {
								$qs .= "show_scale=" . $scale_unit;
							}
							else {
								$qp = str_replace("?", "", $qs);
								$qp = explode("&", $qp);
								if(is_array($qp) && count($qp)>0) {
									$new_qs = "?";
									foreach ($qp as $i=>$par) {
										if(strpos($par, "=") !== false) {
											$pars = explode("=", $par);
											if($pars[0] == "show_scale") {
												$new_qs .= "&show_scale=$scale_unit";
											}
											else {
												$new_qs .= "&$par";
											}
										}
										else {
											$new_qs .= "&$par";
										}
									}
									$qs = $new_qs;
								}
								else {
									$qs .= "&show_scale=" . $scale_unit;
								}
							}
							$new_weather_link = substr($weather_link, 0, $qmark);
							$weather_link = $new_weather_link . $qs;
						}
						$weather_link = str_replace("?&", "?", $weather_link);
						?>
						<td><a class="change_scale" href="<?php echo $weather_link;?>"><?php echo tx("$scale_name");?></a></td>
						<?php
					}
					
					if($module_show_print_link == 1) {
						if(!isset($print_screen)) {
							?>
							<td><a class="print" href="index.php?print=1&module_page=weather_advanced&show_scale=<?php echo $c_to_f;?>&lang=<?php echo $lang2iso;?>&action=print&ccmi=<?php echo $current_catdom_module_id;?>" target="_blank"><?php echo tx("Print");?></a></td>
							<?php
						}
						else {
							?>
							<td><a class="print" href="javascript:print();"><?php echo tx("Print");?></a></td>
							<?php
						}
					}
					
					?>
					</tr>
				</table>
			</div>
			<?php
		}
		if(is_array($weather_current) && count($weather_current)>0) {
			foreach ($weather_current as $k=>$city) {
				$fin_wnd_dir = mb_strtoupper($city['wind_dir'], 'UTF-8');
				$wnd_dir = str_split(mb_strtolower($city['wind_dir'], 'UTF-8'));
				if(is_array($wnd_dir) && count($wnd_dir)>0) {
					$co_card = array("n"=> tx("NORTH"), "e"=> tx("EAST"), "s"=> tx("SOUTH"), "w"=>t("WEST"));
					$fin_wnd_dir = "";
					foreach ($wnd_dir as $dir_letter) {
						if(array_key_exists($dir_letter, $co_card)) {
							$fin_wnd_dir .= mb_substr ( tx($co_card[$dir_letter]), 0, 1);
						}
					}
					
					$fin_wnd_dir = mb_strtoupper($fin_wnd_dir, 'UTF-8');
				}
				?>
				<div class="weather_container_adv">
					<table cellpadding="0" cellspacing="0" border="0" width="100%">
						<tr>
							<th colspan="6" align="left"><?php echo tx($city['ws_city_name']);?></th>
						</tr>
						<tr>
							<td class="ws_td ws_1st_row ws_1st_row_first" align="center" valign="top">
								<strong><?php echo tx("CURRENT");?></strong><br/>
								<p class="degree"><?php echo convert_temp($city['temp'], $c_to_f) . '&deg; ' . show_scale($city['temp_units'], $c_to_f);?></p>
							</td>
							<td class="ws_td ws_1st_row" align="center" valign="top">
								<strong><?php echo mb_strtoupper ( tx($city['phrase']), 'UTF-8');?></strong><br/>
								<div class="m_icon"><img src="<?php echo $out_path_cache;?>images/weather_icons/<?php echo $city['icon'];?>.png" align="weather-icon" border="0"/></div>
							</td>
							<td class="ws_td ws_1st_row ws_1st_row_last" valign="middle" align="center"  colspan="3">
								<table cellpadding="0" cellspacing="0" border="0" class="ws_details">
									<tr>
										<td align="left" nowrap class="para_name"><?php echo tx("Visibility");?>:</td>
										<td align="left" nowrap class="para_value"><?php echo $city['vis'] . " " . $city['vis_unit'];?></td>
										<td align="left" nowrap class="para_name"><?php echo tx("Wind speed");?>:</td>
										<td align="left" nowrap class="para_value"><?php echo $city['windspeed'] . " " . $city['windspeed_unit'];?></td>
									</tr>
									<tr>
										<td align="left" nowrap class="para_name"><?php echo tx("Pressure");?>:</td>
										<td align="left" nowrap class="para_value"><?php echo $city['pres'] . " " . $city['pres_unit'];?></td>
										<td align="left" nowrap class="para_name"><?php echo tx("Wind direction");?>:</td>
										<td align="left" nowrap class="para_value"><?php echo $fin_wnd_dir ;?></td>
									</tr>
									<tr>
										<td align="left" nowrap class="para_name"><?php echo tx("Humidity");?>:</td>
										<td align="left" nowrap class="para_value"><?php echo $city['rhumid'] . " " . $city['rhumid_unit'];?></td>
										<td align="left" nowrap class="para_name"><?php echo tx("Wind Chill");?>:</td>
										<td align="left" nowrap class="para_value"><?php echo convert_temp($city['wndchl'], $c_to_f) . "&deg; " . show_scale($city['wndchl_unit'], $c_to_f);?></td>
									</tr>
								</table>
							</td>
						</tr>
						<?php
						if(isset($weather_fiveday[$city['ws_city_id']])) {
							$tmp = array();
							$tmp = $weather_fiveday[$city['ws_city_id']];
							asort($tmp);
							$weather_fiveday[$city['ws_city_id']] = $tmp;
							
							// Put the names of days of the week
							?>
							<tr>
							<?php
							$cnt = 1;
							foreach ($weather_fiveday[$city['ws_city_id']] as $id=>$fd) {
								$ext_cls = "";
								if($cnt == 1) $ext_cls = "ws_2nd_row_first";
								if($cnt == count($weather_fiveday[$city['ws_city_id']])) $ext_cls = "ws_2nd_row_last";
								?>
								<td width="20%" class="ws_td ws_2nd_row <?php echo $ext_cls;?>" align="center"><?php echo tx($fd['day_name']);?></td>
								<?php
								$cnt++;
							}
							?>
							</tr>
							<?php
							
							// Put the particular forecast data per day
							?>
							<tr>
							<?php
							$cnt = 1;
							foreach ($weather_fiveday[$city['ws_city_id']] as $id=>$fd) {
								$ext_cls = "";
								if($cnt == 1) $ext_cls = "ws_3rd_row_first";
								if($cnt == count($weather_fiveday[$city['ws_city_id']])) $ext_cls = "ws_3rd_row_last";
								?>
								<td width="20%" class="ws_td ws_3rd_row <?php echo $ext_cls;?>" align="center">
									<div class="m_icon"><img src="<?php echo $out_path_cache;?>images/weather_icons/<?php echo $fd['icon'];?>.png" border="0" alt="<?php echo tx($fd['phrase']);?>" title="<?php echo tx($fd['phrase']);?>"/></div>
									<table border="0" cellspacing="0" cellpadding="0" class="ws_details">
										<tr>
											<td nowrap class="para_name"><?php echo tx("High");?>:</td>
											<td nowrap class="para_value" align="right"><?php echo convert_temp($fd['high'], $c_to_f) . '&deg;' . show_scale($fd['high_unit'], $c_to_f); ?></td>
										</tr>
										<tr>
											<td nowrap class="para_name"><?php echo tx("Low");?>:</td>
											<td nowrap class="para_value" align="right"><?php echo convert_temp($fd['low'], $c_to_f) . '&deg;' . show_scale($fd['low_unit'], $c_to_f); ?></td>
										</tr>
									</table>
								</td>
								<?php
								$cnt++;
							}
							?>
							</tr>
							<?php
							
							// Put the particular forecast phrase
							?>
							<tr>
							<?php
							$cnt = 1;
							foreach ($weather_fiveday[$city['ws_city_id']] as $id=>$fd) {
								$ext_cls = "";
								if($cnt == 1) $ext_cls = "ws_4th_row_first";
								if($cnt == count($weather_fiveday[$city['ws_city_id']])) $ext_cls = "ws_4th_row_last";
								?>
								<td width="20%" class="ws_td ws_4th_row <?php echo $ext_cls;?>" align="center"><?php echo tx($fd['phrase']);?></td>
								<?php
								$cnt++;
							}
							?>
							</tr>
							<?php
						}
						?>
					</table>
				</div>
				<?php
			}
		}
		?>
		
	</div>
	<?php
}
$lngModule = $lngModule_tmp;
$lngFile = $lngFile_tmp;
?>
