<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
	//pass:cfnが無い又は、データが25バイトじゃないとき終了
	if(strcmp($_GET["pass"],"cfn") != 0 || strlen($_GET["data"])!=25){
		die("送信データのエラー");
	}
	//車載器から送られてきたデータをdataに格納
	$data = $_GET["data"];
	
	//データに数字以外の文字がないか確認
	for($ch = 0;$ch <= 24;$ch++){
		if(($data[$ch] > '9') || ($data[$ch] < '0')){
			unset($ch,$data);
			die();
		}
	}

	//バス停番号
	$bus=0;
	//各ルートの運行状態(0:運行終了,1:運行中,2:運行準備,3:点検など,4:運休)
	$status = rtrim(file_get_contents("./maintenance/data/location/status".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES));
	//$status = file_get_contents("./data/status".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES);

	//現在の便番号
	$now_bin = rtrim(file_get_contents("./maintenance/data/location/bin".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES));
	//$now_bin = file_get_contents("./data/bin".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES);

	//現在のバス停通過番号
	$now_pass = rtrim(file_get_contents("./maintenance/data/location/pass_bus".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES));
	//$now_pass = file_get_contents("./data/pass_bus".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES);

	//進行方向のフラグ
	$bus_flag = rtrim(file_get_contents("./maintenance/data/location/bus_flag".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES));
	//$bus_flag = file_get_contents("./data/bus_flag".$data[0].$data[1].".txt", FILE_IGNORE_NEW_LINES);

	//始発と終点の抽出
	$max_bin=1;//配列の添え字を便番号に合わせるために1を加算
	$fileName = "./maintenance/data/location/bin_data".$data[0].$data[1].".txt";
	//$fileName = "./data/bin_data".$data[0].$data[1].".txt";
    $file = fopen($fileName, "r");
	while (!feof($file)) {
	   	$str = fgets($file);
		$str = trim($str);
		$data_array = explode(",", $str);
		$start_bus[$max_bin]=$data_array[0];
		$end_bus[$max_bin]=$data_array[1];
		$bus_time[$max_bin]=intval(str_replace(":","",$data_array[2]));
		$end_bus_time[$max_bin]=intval(str_replace(":","",$data_array[3]));
		if($_GET['debug']==1){
			echo "便：".$max_bin."<br>";
			echo "始発：".$start_bus[$max_bin]."<br>";
			echo "終点：".$end_bus[$max_bin]."<br>";
			echo "運行開始時刻：".$bus_time[$max_bin]."<br>";
			echo "運行終了時刻：".$end_bus_time[$max_bin]."<br>";
			echo "<br>";
		}
		$max_bin++;
    }
	fclose($file);
	$max_bin--;//加算した分を減算
	unset($fileName,$file,$str,$data_array);

	if($_GET['debug']==2){
		/*---------送信されたデータを出力-------*/
		print('<br>'.' 現在の運行状況:'.$status.'<br>');
		print('<br>'.' 現在の便番号:'.$now_bin.'<br>');
		print('<br>'.' バスの進行方向:'.$bus_flag.'<br>');
		print('<br>'.' 現在のバス停通過番号:'.$now_pass.'<br><br>');
		/*------------------------------------------*/
	}

	/*---------送信されたデータを整理する-------*/
	$day = date("md");
	$r_id=$data[0].$data[1];
	$lat=$data[8].$data[9].".".$data[10].$data[11].$data[12].$data[13].$data[14].$data[15];
	$lng=$data[16].$data[17].$data[18].".".$data[19].$data[20].$data[21].$data[22].$data[23].$data[24];
	$time = $data[2].$data[3].$data[4].$data[5].$data[6].$data[7];
	$cal_time = intval(date($data[2].$data[3].$data[4].$data[5]));//<-何時何分までの時刻を取り出す
	/*------------------------------------------*/

	/*------------通過情報のチェック------------*/
	$con=@mysql_connect("localhost","event","L523GpA");
	if(!$con){
		unset($con,$data,$r_id,$lat,$lng,$time,$day);
		die("DB接続エラー");
	}
	$select_db=@mysql_select_db("eventdb");
	if(!$select_db){
		unset($con,$select_db,$r_id,$lat,$lng,$time,$day);
		die ("DB選択エラー");
	}
	@mysql_query("set names utf8");
	//$sql="select busstop_id,bus_name,stop_lat,stop_lng from nbus_master inner join nbus_view using(r_id,busstop_id) where r_id=".$r_id." and view_bin=".$now_bin." and busstop_id >= ".$now_pass."  and view_fg=1 group by bus_name order by busstop_id asc";
	//現在通過したバス停とこれから向かうバス停をunionで連結して表示させる
	$sql="select busstop_id,bus_name,stop_lat,stop_lng from nbus_master where r_id=".$r_id." and busstop_id = ".$now_pass."
		  union 
		  select busstop_id,bus_name,stop_lat,stop_lng from nbus_master inner join nbus_view using(r_id,busstop_id) where r_id=".$r_id." and view_bin=".$now_bin." and busstop_id > ".$now_pass."  and view_fg=1 group by bus_name order by busstop_id asc";
	$res = mysql_query($sql);
	if($now_pass==0){
		$check_bus=1;
	}else{
		$check_bus=0;
	}
	for($i = $check_bus;$row = mysql_fetch_array($res);$i++){
		$stop_id[$i]=intval($row['busstop_id']);
		$stop_name[$i]=$row['bus_name'];
		$stop_lat[$i] = $row['stop_lat'];
		$stop_lng[$i] = $row['stop_lng'];
		if($_GET['debug']==1){
			echo $stop_id[$i].",".$stop_name[$i].",".$stop_lat[$i].",".$stop_lng[$i]."<br>";
		}
	}
	mysql_free_result($res);
	$close=@mysql_close($con);
	if(!$close){
		unset($con,$select_db,$res,$sql,$row,$close,$r_id,$lat,$lng,$time,$day);
		die("DB切断エラー");
	}
	unset($con,$select_db,$res,$sql,$row,$close);
	//バス停範囲にいるかどうか判断(約20m四方)

	//$pass_fg (1:次のバス停，0:それ以外)
	$pass_fg=0;
	$cr = array(" 着"," 発");

	/*--------------------------次に向かうバス停かを判別----------------------*/
	for($j=1;$j>=0;$j--){
		if($status==1 && ($lat<$stop_lat[$j]+0.000264)&&($lng<$stop_lng[$j]+0.000264) && ($lat>$stop_lat[$j]-0.000264)&&($lng>$stop_lng[$j]-0.000264)){
			if($_GET['debug']==2){
				echo "次に向かうバス停<br>";
			}
			$bus = $stop_id[$j];
			$filepath = "./maintenance/data/location/pass_bus".$data[0].$data[1].".txt";
			//$filepath = "./data/pass_bus".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$bus,strlen($bus));//通過バス停情報を書き込む
			}
			fclose($fp);
			$pass_fg=1;
			break;
		}
	}
	/*----------------------------------------------------------------------------*/

	/*--------------------------通過情報に抜けがあった場合の更新処理----------------------*/
	if($pass_fg==0){
		for($j = 0;$j < $i;$j++){
			if(($lat<$stop_lat[$j]+0.000264)&&($lng<$stop_lng[$j]+0.000264) && ($lat>$stop_lat[$j]-0.000264)&&($lng>$stop_lng[$j]-0.000264)){
				$array_key=array_search($now_pass,$stop_id);
				if($status==1&&(strpos(str_replace($cr,"",$stop_name[$j]),str_replace($cr,"",$stop_name[$array_key]))===false)){
					$bus = $stop_id[$j];
					echo $stop_name[$j].":".$stop_name[1]."<br>";
					echo $bus-$stop_id[1]."<br>";
					if(($bus-$stop_id[1])>=2){
						if($_GET['debug']==2){
							echo "それ以外の更新<br>";
						}
						$filepath = "./maintenance/data/location/pass_bus".$data[0].$data[1].".txt";
						//$filepath = "./data/pass_bus".$data[0].$data[1].".txt";
						$fp = fopen($filepath, "w");
						if(flock($fp,LOCK_EX)){
							ftruncate($fp,0);
							@fwrite($fp,$bus,strlen($bus));//通過バス停情報を書き込む
						}
						fclose($fp);
					}
					break;
				}
			}
		}
	}
	/*-----------------------------------------------------------------------------*/

	/*-------------------DBの更新---------------*/
	$con=@mysql_connect("localhost","event","L523GpA");
	if(!$con){
		unset($data,$r_id,$lat,$lng,$time,$day);
		die("DB接続エラー");
	}
	$select_db=@mysql_select_db("eventdb");
	if(!$select_db){
		unset($con,$select_db,$r_id,$lat,$lng,$time,$day);
		die ("DB選択エラー");
	}
	@mysql_query("set names utf8");
	//echo "update nbus_log set log_lat='".$lat."',log_lng='".$lng."',log_time='".$time."',log_day='".$day."' where r_id=".$r_id;
	$res= mysql_query("update nbus_log set log_lat ='".$lat."',log_lng ='".$lng."',log_time='".$time."',log_day='".$day."' where r_id=".$r_id." and busstop_id=".$bus);
	if($res === true){
		mysql_query("commit");
	}else{
		mysql_query("rollback");
	}
	$close=@mysql_close($con);
	if(!$close){
		unset($con,$select_db,$res,$sql,$row,$close,$r_id,$lat,$lng,$time,$day);
		die("DB切断エラー");
	}
	/*------------------------------------------*/

	/*-------------4便における方向切換-------------*/
	if($bus_flag==0 && $bus ==51 && $now_bin==4){
		echo "第4便折り返し<br>";
		$filepath = "./maintenance/data/location/bus_flag".$data[0].$data[1].".txt";
		//$filepath = "./data/bus_flag".$data[0].$data[1].".txt";
		$fp = fopen($filepath, "w");
		if(flock($fp,LOCK_EX)){
			ftruncate($fp,0);
			@fwrite($fp,1);//運行方向
		}
		fclose($fp);
		$filepath = "./maintenance/data/location/pass_bus".$data[0].$data[1].".txt";
		//$filepath = "./data/pass_bus".$data[0].$data[1].".txt";
		$fp = fopen($filepath, "w");
		if(flock($fp,LOCK_EX)){
			ftruncate($fp,0);
			@fwrite($fp,4);
		}
		fclose($fp);
	}
	/*---------------------------------------------*/

	/*----------------運行状況の更新---------------*/

	if($bus>=$end_bus[$now_bin] && $status==1 && $bus_flag==1){
		if($_GET['debug']==2){
			echo "便番号の更新<br>";
		}
		if($now_bin==$max_bin){
			if($_GET['debug']==2){
				echo "運行終了<br>";
			}
			$status=0;
			$filepath = "./maintenance/data/location/status".$data[0].$data[1].".txt";
			//$filepath = "./data/status".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$status,strlen($status));//運行状況の書き込み
			}
			fclose($fp);
		}else{
			if($_GET['debug']==2){
				echo "運行準備<br>";
			}
			$now_bin++;
			if($_GET['debug']==2){
				echo "運行準備<br>";
			}
			$status=2;
			$filepath = "./maintenance/data/location/bin".$data[0].$data[1].".txt";
			//$filepath = "./data/bin".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$now_bin,strlen($now_bin));//便情報を書き込む
			}
			fclose($fp);

			if($now_bin==4){
				$bus_flag=0;
			}else{
				$bus_flag=1;
			}
			$now_pass=$start_bus[$now_bin];

			$filepath = "./maintenance/data/location/bus_flag".$data[0].$data[1].".txt";
			//$filepath = "./data/bus_flag".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$bus_flag,strlen($bus_flag));//運行状況の書き込み
			}
			fclose($fp);
			$filepath = "./maintenance/data/location/pass_bus".$data[0].$data[1].".txt";
			//$filepath = "./data/pass_bus".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$now_pass,strlen($now_pass));
				//@fwrite($fp,0);
			}
			fclose($fp);
			$filepath = "./maintenance/data/location/status".$data[0].$data[1].".txt";
			//$filepath = "./data/status".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$status,strlen($status));//運行状況の書き込み
			}
			fclose($fp);
		}
	}else if(($status==2)&&($now_pass!=0)){//始発のバス停に到着時に運行準備から運行中への移行
		if($_GET['debug']==2){
			echo $cal_time.":".$bus_time[$now_bin]."<br>";
		}
		if($cal_time>=$bus_time[$now_bin]){
			if($_GET['debug']==2){
				echo $now_bin."便 運行開始<br>";
			}
			$status=1;
			$filepath = "./maintenance/data/location/status".$data[0].$data[1].".txt";
			//$filepath = "./data/status".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$status,strlen($status));//運行状況の書き込み
			}
			fclose($fp);
		}
	}else if($status==0){
		if($cal_time<=$bus_time[1]){//第1便の運行時刻前の信号をリセット信号とする
			if($_GET['debug']==2){
				echo "運行状況のリセット<br>";
			}
			$status=2;
			$now_bin=1;
			$filepath = "./maintenance/data/location/bin".$data[0].$data[1].".txt";
			//$filepath = "./data/bin".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$now_bin,strlen($now_bin));//便情報を書き込む
			}
			fclose($fp);
			$filepath = "./maintenance/data/location/pass_bus".$data[0].$data[1].".txt";
			//$filepath = "./data/pass_bus".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$start_bus[$now_bin],strlen($start_bus[$now_bin]));
				//@fwrite($fp,0);
			}
			fclose($fp);
			$filepath = "./maintenance/data/location/status".$data[0].$data[1].".txt";
			//$filepath = "./data/status".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$status,strlen($status));//運行状況の書き込み
			}
			fclose($fp);
			$filepath = "./maintenance/data/location/bus_flag".$data[0].$data[1].".txt";
			//$filepath = "./data/bus_flag".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,1);//運行方向
			}
			fclose($fp);
		}
		if($status==0){//2便以降のリセット
			for($j=2;$j<$max_bin;$j++){
				if(($cal_time>=$end_bus_time[($j-1)]) && ($cal_time<$end_bus_time[$j])){//第1便の運行時刻前の信号をリセット信号とする
					if($_GET['debug']==2){
						echo "運行状況のリセット2<br>";
					}
					$status=2;
					$now_bin=$j;
					$filepath = "./maintenance/data/location/bin".$data[0].$data[1].".txt";
					//$filepath = "./data/bin".$data[0].$data[1].".txt";
					$fp = fopen($filepath, "w");
					if(flock($fp,LOCK_EX)){
						ftruncate($fp,0);
						@fwrite($fp,$now_bin,strlen($now_bin));//便情報を書き込む
					}
					fclose($fp);
					$filepath = "./maintenance/data/location/pass_bus".$data[0].$data[1].".txt";
					//$filepath = "./data/pass_bus".$data[0].$data[1].".txt";
					$fp = fopen($filepath, "w");
					if(flock($fp,LOCK_EX)){
						ftruncate($fp,0);
						@fwrite($fp,$start_bus[$now_bin],strlen($start_bus[$now_bin]));
						//@fwrite($fp,0);
					}
					fclose($fp);
					$filepath = "./maintenance/data/location/status".$data[0].$data[1].".txt";
					//$filepath = "./data/status".$data[0].$data[1].".txt";
					$fp = fopen($filepath, "w");
					if(flock($fp,LOCK_EX)){
						ftruncate($fp,0);
						@fwrite($fp,$status,strlen($status));//運行状況の書き込み
					}
					fclose($fp);
					if($now_bin==4){
						$direction=0;
					}else{
						$direction=1;
					}
					$filepath = "./maintenance/data/location/bus_flag".$data[0].$data[1].".txt";
					//$filepath = "./data/bus_flag".$data[0].$data[1].".txt";
					$fp = fopen($filepath, "w");
					if(flock($fp,LOCK_EX)){
						ftruncate($fp,0);
						@fwrite($fp,$direction,strlen($direction));//運行方向
					}
					fclose($fp);
					break;
				}
			}
		}
	}

	/*----------------運行状況の更新(休憩や給油などの特殊パターン)---------------*/

	$bin_cd_fg=0;
	if((($lat<36.557145+0.000264)&&($lng<136.876008+0.000264) && ($lat>36.557145-0.000264)&&($lng>136.876008-0.000264)) && $status==1 && $bus_flag==1){
		$bin_cd_fg=1;
	}else if((($lat<36.556233+0.000264)&&($lng<136.876635+0.000264) && ($lat>36.556233-0.000264)&&($lng>136.876635-0.000264)) && $status==1 && $bus_flag==1){
		$bin_cd_fg=1;
	}
	if($bin_cd_fg==1){
		if($_GET['debug']==2){
			echo "便番号の更新2<br>";
		}
		if($now_bin==$max_bin){
			if($_GET['debug']==2){
				echo "運行終了2<br>";
			}
			$status=0;
			$filepath = "./maintenance/data/location/status".$data[0].$data[1].".txt";
			//$filepath = "./data/status".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$status,strlen($status));//運行状況の書き込み
			}
			fclose($fp);
		}else{
			if($_GET['debug']==2){
				echo "運行準備2<br>";
			}
			$now_bin++;
			$status=2;
			$filepath = "./maintenance/data/location/bin".$data[0].$data[1].".txt";
			//$filepath = "./data/bin".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$now_bin,strlen($now_bin));//便情報を書き込む
			}
			fclose($fp);

			if($now_bin==4){
				$bus_flag=0;
			}else{
				$bus_flag=1;
			}
			$now_pass=$start_bus[$now_bin];

			$filepath = "./maintenance/data/location/bus_flag".$data[0].$data[1].".txt";
			//$filepath = "./data/bus_flag".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$bus_flag,strlen($bus_flag));//運行状況の書き込み
			}
			fclose($fp);
			$filepath = "./maintenance/data/location/pass_bus".$data[0].$data[1].".txt";
			//$filepath = "./data/pass_bus".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$now_pass,strlen($now_pass));
				//@fwrite($fp,0);
			}
			fclose($fp);
			$filepath = "./maintenance/data/location/status".$data[0].$data[1].".txt";
			//$filepath = "./data/status".$data[0].$data[1].".txt";
			$fp = fopen($filepath, "w");
			if(flock($fp,LOCK_EX)){
				ftruncate($fp,0);
				@fwrite($fp,$status,strlen($status));//運行状況の書き込み
			}
			fclose($fp);
		}
	}

	/*-------------------------------------------*/

	if($_GET['debug']==2){
		/*---------送信されたデータを出力-------*/
		print('<br>送信データについて<br>');
		print('<br>'.' 路線番号:'.$r_id.'<br>');
		print('<br>'.' 緯度:'.$lat.'<br>');
		print('<br>'.' 経度:'.$lng.'<br>');
		print('<br>'.' 日付:'.$day.'<br>');
		print('<br>'.' 時刻:'.$time.'<br>');
		print('<br>'.' 通過バス停:'.$bus.'番<br>');
		print('<br>'.' 最新の運行状況:'.$status.'<br>');
		print('<br>'.' 最新の便番号:'.$now_bin.'<br>');
		print('<br>'.' 最終の便番号:'.$max_bin.'<br>');
		print('<br>');
		/*------------------------------------------*/
	}

	/*---------送信ログデータを出力(csv形式)-------*/
	$filepath = "./maintenance/data/".$day."_log".$r_id.".csv";
	//$filepath = "./data/".$day."_log".$r_id.".csv";
	$data=$r_id.",".$bus.",".$lat.",".$lng.",".$day.",".$time."\n";
	//echo $data;
	if (!file_exists($filepath)) {
		$fp = fopen($filepath, "w");
		chmod($filepath,0666);
	}else{
		$fp = fopen($filepath, "a");
	}
	if(flock($fp,LOCK_EX)){
		@fwrite($fp, $data);//通過バス停情報を書き込む
	}
	fclose($fp);
	/*------------------------------------------*/

	unset($stop_name,$stop_id,$stop_lat,$stop_lng);
	unset($status,$filepath,$fp,$start_bus,$end_bus,$max_bin,$now_bin,$now_pass,$cal_time,$bus_time,$pass_fg,$cr);
	unset($con,$select_db,$res,$sql,$row,$close,$lat,$time,$day,$r_id,$bus,$data,$bin_cd_fg,$direction);
?>
