<?php
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
	$_gitlink = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/';
	$_files = [
		'confirmed'	=> [
			'url' => $_gitlink.'time_series_19-covid-Confirmed.csv',
			'path' => 'data/covid_confirmed.csv'
		],
		'deaths' => [
			'url' => $_gitlink.'time_series_19-covid-Deaths.csv',
			'path' => 'data/covid_deaths.csv'
		],
		'recovered' => [
			'url' => $_gitlink.'time_series_19-covid-Recovered.csv',
			'path' => 'data/covid_recovered.csv'
		]
	];
	$_start_index = 40;
	if($_start_index < 4) { $_start_index = 4; }
	$sync_output = sync_data();
	
	$data = [];
	foreach($_files as $k => $v) {
		$ts = file_get_contents($v['path']);
		$ts = condition_csv($ts);
		$data[$k] = parse_ts_csv($ts);
	}
	//print_r($data,1);
	//$data['current'] = $data['confirmed'];
	$data['current'] = get_current_factors($data);
	
	
		
	function get_current_factors($data) {
		//Get numbers of people that were infected on each day.
		foreach($data['confirmed']['series'] as $country => $states) {
			foreach($states as $state => $d) {
				foreach($states[$state]['data'] as $k => $v) {
					$infected = (int) $data['confirmed']['series'][$country][$state]['data'][$k];
					$cured = (int) $data['recovered']['series'][$country][$state]['data'][$k];
					$dead = (int) $data['deaths']['series'][$country][$state]['data'][$k];
					$data['current']['series'][$country][$state]['data'][$k] = ($infected-($cured));
				}
			}
		}
		return $data['current'];
	}
	
	
	
	?>
<!DOCTYPE html>
<html lang="en">
	<head>
        <meta charset="utf-8">
        <title>COVID-19</title>
        <meta name="description" content="Page Titile">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no, minimal-ui">
        <!-- Call App Mode on ios devices -->
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <!-- Remove Tap Highlight on Windows Phone IE -->
        <meta name="msapplication-tap-highlight" content="no">
        <!-- base css -->
        <link rel="stylesheet" media="screen, print" href="css/vendors.bundle.css">
        <link rel="stylesheet" media="screen, print" href="css/app.bundle.css">
        <!-- Place favicon.ico in the root directory -->
        <link rel="apple-touch-icon" sizes="180x180" href="img/eq2emu_labs_logo_180.png">
        <link rel="icon" type="image/png" sizes="32x32" href="img/favicon/eq2emu_labs_favico_32.png">
        <link rel="mask-icon" href="img/favicon/safari-pinned-tab.svg" color="#5bbad5">
		
        <link rel="stylesheet" href="css/animate.min.css">
        <link rel="stylesheet" href="css/fa-light.css">
        <link rel="stylesheet" href="css/fa-regular.css">
        <link rel="stylesheet" href="css/fa-solid.css">
        <link rel="stylesheet" href="css/fa-duotone.css">
        <link rel="stylesheet" href="css/fa-brands.css">
        <link rel="stylesheet" href="css/eq2emu.css">
        <link rel="stylesheet" media="screen, print" href="css/statistics/chartist/chartist.css">
		<script>
			var cvd = <?php echo json_encode($data); ?>;
		
		</script>
        <!--<link rel="stylesheet" media="screen, print" href="css/your_styles.css">-->
        <script src="js/vendors.bundle.js"></script>
        <script src="js/app.bundle.js"></script>
        <script src="js/eq2emu.js"></script>
        <script src="js/statistics/chartist/chartist.js"></script>
		<style>
		.ct-chart-line {
		  overflow: visible;
		  margin : 0 0 30px 0;
		}

		.ct-chart .ct-label.ct-horizontal.ct-end {
		  position: relative;
		  justify-content: flex-end;
		  text-align: right;
		  transform-origin: 100% 0;
		  transform: translate(-100%) rotate(-45deg);
		  white-space:nowrap;
		 }
		</style>
    </head>
    <body class="mod-bg-1 ">
        <!-- BEGIN Page Wrapper -->
        <div class="page-wrapper">
            <div class="page-inner">
                <!-- BEGIN Left Aside -->
                <!-- END Left Aside -->

                <div class="page-content-wrapper">
					<div class="row">
						<div class="col-xl-3">
							<select id="country" class="form-control">
							
							</select>
							<label>Country</label>
						</div>
						
						<div class="col-xl-3">
							<select id="states" class="form-control">
							
							</select>
							<label>State/Province</label>
						</div>
						
						<div class="col-xl-3">
							<button id="load" class="btn btn-md btn-default">
								<i class="fa fa-bolt text-warning"></i>&nbsp;&nbsp;Run Chart
							</button>
						</div>
						<div class="col-xl-12"><h4><hr></hr></h4></div>
						<div class="col-xl-12">
							<div class="ct-chart nyc">
							
							</div>
						</div>
					</div>
					<div class="row">
						<div class="col-xl-4">
							<p id="tooltip">Test!</p>
						</div>
						<div class="col-xl-8">
							<?php
								//echo '<pre>'.$sync_output.'</pre>';
								//echo '<pre>'.print_r($data, 1).'</pre>';
								//echo '<pre>'.json_encode($data, JSON_PRETTY_PRINT).'</pre>';
								//echo '<pre>'.$ts.'</pre>';
							?>
						</div>
					</div>
					<script>
						load_countries();
						
						function load_countries() {
							$.each(cvd.current.series, function(k, v) {
								if($('option[value="'+k+'"]').length < 1) {
									$('#country').append('<option value="'+k+'">'+k+'</option>');
								}
							});
							sort_options('.countries');
							$('#country').prepend('<option class="countries" value="US" selected="selected" disabled>- Select a Country -</option>');
							$('#country').prepend('<option class="countries" value="US">United States</option>');
						}
						
						function load_states(c) {
							var s = $('#states');
							s.empty();
							
							$.each(cvd.current.series[c], function(k, v) {
								s.append('<option class="states" value="'+k+'">'+k.replace('|', ', ')+'</option>');
							});
							sort_options('.states');
						}
						
						function sort_options(e) {
							var options = $(e);
							var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
							arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
							options.each(function(i, o) {
							  o.value = arr[i].v;
							  $(o).text(arr[i].t);
							});
						}
						
						$(document).on('change', '#country', function() {
							var c = $(this, 'option:selected').val();
							load_states(c);
						});
						
						$(document).on('click', '#load', function() {
							var c = $('#country option:selected').val(), s = $('#states option:selected').val();
							load_chart(c,s);
							
							
						});
						
						function load_chart(c, s) {
							
							//chart.clear();
							
							chart = new Chartist.Line('.nyc', {
								labels: cvd.confirmed.labels,
								series: [
									cvd.current.series[c][s].data,
									cvd.deaths.series[c][s].data,
									cvd.recovered.series[c][s].data
								]
							}, {
								height:'300px',
								fullWidth: true,
								chartPadding: { right: 40 },
								axisX: {
									labelInterpolationFnc: function(value, index) {
										return index % 2 === 0 ? value : null;
									}
								}
							});
						}

 						var chart = new Chartist.Line('.nyc', {
							labels: cvd.confirmed.labels,
							series: [
								cvd.current.series["Italy"]['country']
							]
						}, {
							height:'300px',
							fullWidth: true,
							chartPadding: { right: 40 },
							axisX: {
								labelInterpolationFnc: function(value, index) {
									return index % 2 === 0 ? value : null;
								}
							}
						});
						
						// Based on ty's comment
						chart.on('created', function(bar) {
						  $('.ct-point').on('mouseover', function() {
							$('#tooltip').html('<b>Selected Value: </b>' + $(this).attr('ct:value'));
						  });

						  $('.ct-point').on('mouseout', function() {
							$('#tooltip').html('<b>Selected Value:</b>');
						  });
						});
					</script>
					
                    <!-- END Color profile -->
                </div>
            </div>
        </div>
    </body>
</html>
<?php

		
	function parse_ts_csv($s, $return = [ 'labels'=>[], 'series' => [] ]) {
		global $_start_index;
		$lines = explode("\n", $s);
		
		$hdr = explode(",",$lines[0]);
		foreach($hdr as $hk => $hv) {
			if($hk > $_start_index) {
				$return['labels'][] = $hv;
			}
		}
		foreach($lines as $row => $csv) {
			if($row > 0) {
				$l = explode(",",$csv);
				if(!isset($return['series'][$l[1]])) { $return['series'][$l[1]] = []; }
				
				if(strlen($l[0]) < 1) { 
					$key = 'country';
				} else {
					$key = $l[0];
				}
				
				$return['series'][$l[1]][$key] = ['coords'=>[$l[2],$l[3]], 'data'=>[]];
				foreach($l as $k => $v) {
					if($k > $_start_index) {
						$return['series'][$l[1]][$key]['data'][] = $v;
					}
				}
			}
		}
		
		return $return;
	}

	function condition_csv($r) {
		
		return str_replace(['"', ', '], ['', '|'], $r);
		
	}


	
	function sync_data($return = NULL) {
		global $_files;
		$hours_til_sync = 6;
		foreach($_files as $k => $v) {
			$sync = false;
			if(file_exists($v['path'])) {
				$return .= $v['path'].' exists! Checking last update time.'.PHP_EOL;
				//time interval for deletion to occur...
				$x = (3600*$hours_til_sync);  //6 hours
				//timestamp
				$current_time = time();
				//timestamp
				$file_creation_time = filemtime($v['path']);
				//extract difference
				$difference = $current_time - $file_creation_time;
				//if difference = $x...then delete file
				if ($difference >= $x) {
					$return .= $v['path'].' needs to be updated!'.PHP_EOL;
					unlink($v['path']);
					$sync = true;
				} else {
					$return .= $v['path'].' is still fresh. Skipping update!'.PHP_EOL;
				}
			} else {
				$sync = true;
				$return .= $v['path'].' does not exist. Downloading file!'.PHP_EOL;
			}
			if($sync) {
				$csv = file_get_contents($v['url']);
				
				if (!file_exists($v['path'])) { touch($v['path']); }
				file_put_contents($v['path'], $csv);
				$return .= $v['path'].' has been updated!'.PHP_EOL;
			}
		}
		return $return;
	}
	
?>