<?php
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//	自動でクラスを参照する
//	関数名	：	__autoload()
//	備考	：	参照先は./class/XXX.phpとする
//	更新	：	2012/10/19 KMK-Teraoka
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
function __autoload($className)
{
	$fPath = "./class/" . str_replace("_", "/", $className) . ".php";
	require_once $fPath;
}

//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//	GCMで指定端末にイベントを送る
//	関数名	：	sendGcmEvent
//	備考	：	
//	更新	：	2013/03/19 KMK-Teraoka
//-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
function sendGcmEvent($gcmId_, $events_)
{
	$url = "https://android.googleapis.com/gcm/send";
	
	$header = array(
		"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
		"Authorization: key=AIzaSyCtFNuvqkLxtwe0hfTp38Xk17Nq8_YHGVw",		//API key
	);
	
	$post_list = array(
		"registration_id"	=>	$gcmId_,
		"collapse_key"		=>	time(),
		"data.message"		=>	time(). "#". (strlen(bin2hex($events_)) / 2). "#". $events_,
	);
	
	$post = http_build_query($post_list, "&");
	
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FAILONERROR, 1);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_POST, TRUE);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	curl_setopt($ch, CURLOPT_TIMEOUT, 5);
	$ret = curl_exec($ch);
	
	var_dump($ret);
	
	return $ret;
}

//===============================================
//	DEBUG_MODE
//	備考		：	
//	更新		：	2012/11/29 KMK-Teraoka
//===============================================
define("DEBUG_MODE", "1");
Debug::setMode(DEBUG_MODE);
if (DEBUG_MODE == 1)
{
	Stopwatch::start();
}

//===============================================
//	CommonUtilities
//	備考		：	
//	更新		：	2012/11/29 KMK-Teraoka
//===============================================
$HOST = "192.168.100.153";
$DB = "ansys";
$USER = "postgres";
$PASS = "am#71ZJ*";
$LOG_FILE = "./log/req_guardman.log";

try
{
	$_log = new Log($LOG_FILE);
	
	//===============================================
	//	POST、GETパラメータの受け取り
	//	備考		：	
	//	更新		：	2012/11/29 KMK-Teraoka
	//===============================================
	if (DEBUG_MODE == 1)
	{
		extract($_POST);
		extract($_GET);
		Debug::writes($_POST);
	}
	$constId = isset($_POST["const_id"]) ? htmlspecialchars($_POST["const_id"]) : "";
	$appId = isset($_POST["app_id"]) ? htmlspecialchars($_POST["app_id"]) : "";
	$androidId = isset($_POST["android_id"]) ? htmlspecialchars($_POST["android_id"]) : "";
	$evId[0] = isset($_POST["event_id1"]) ? htmlspecialchars($_POST["event_id1"]) : "";
	$evId[1] = isset($_POST["event_id2"]) ? htmlspecialchars($_POST["event_id2"]) : "";
	$evId[2] = isset($_POST["event_id3"]) ? htmlspecialchars($_POST["event_id3"]) : "";
	$evId[3] = isset($_POST["event_id4"]) ? htmlspecialchars($_POST["event_id4"]) : "";
	
	if (DEBUG_MODE == 1)
	{
		$constId = 4;
		$appId = 3;
		$androidId = "198903985b36c4b2";
		$evId[0] = 5;
		$evId[1] = 8;
		$evId[2] = -1;
		$evId[3] = -1;
		$_log->write("DEBUG_MODE\n");
	}
	$_log->write("CONST_ID->". $constId. "\n");
	$_log->write("APP_ID->". $appId. "\n");
	$_log->write("ADNROID_ID->". $androidId. "\n");
	$_log->write("EVENTS->". $evId[0]. ",". $evId[1]. ",". $evId[2]. ",". $evId[3]. "\n");
	
	// 全てが揃っていないとイベントは失敗
	if (strcmp($constId, "") == 0 || strcmp($appId, "") == 0 || strcmp($androidId, "") == 0)
	{
		return -1;
	}
	
	// イベントIDが全てあるか確認
	for($iCount = 0; $iCount < 4; $iCount++)
	{
		if (strcmp($evId[$iCount], "") == 0)
		{
			return -1;
		}
	}
	
	// 全てのチェックを通過した場合
	// (2)ガードマン端末の抽出
	//================================================
	//	データベース接続
	//	備考		：	
	//	更新		：	2012/11/27 KMK-Teraoka
	//================================================
	$conn = pg_connect("
		host	=	". $HOST. "
		dbname	=	". $DB. "
		user	=	". $USER. "
		password=	". $PASS. "
	");
	if (!$conn)
	{
		throw new Exception("データベースへの接続に失敗しました");
	}
	
	$selGcmId = "SELECT ts.android_id, gc.gcm_id, gc.upddatetime FROM qgis.ts_terminal ts LEFT JOIN qgis.gcm_terminals gc ON ts.android_id = gc.android_id WHERE work_status='1' ORDER BY gc.upddatetime DESC;";
	$resGcmId = pg_query($conn, $selGcmId);
	
	$gmNum = pg_num_rows($resGcmId);
	
	$events = $evId[0]. ",". $evId[1]. ",". $evId[2]. ",". $evId[3];
	
	for($iCount = 0; $iCount < $gmNum; $iCount++)
	{
		$rowGcmId = pg_fetch_array($resGcmId, $iCount, PGSQL_ASSOC);
		
		if (DEBUG_MODE == 1)
		{
			print $rowGcmId["android_id"]. "<br />";
			print $rowGcmId["gcm_id"]. "<br />";
			print $rowGcmId["upddatetime"]. "<br />";
		}
		
		// gcm_eventテーブルに登録
		$insGcmEv = "INSERT INTO qgis.gcm_event (event_id, app_id, const_id, from_android_id, to_android_id, to_gcm_id, ev_01, ev_02, ev_03, ev_04, snddatetime, upddatetime, regdatetime)";
		$insGcmEv .= " VALUES (nextval('qgis.gcm_event_event_id_seq'),'". $appId. "','". $constId. "','". $androidId. "','". $rowGcmId["android_id"]. "','". $rowGcmId["gcm_id"]. "','". $evId[0]. "','". $evId[1]. "','". $evId[2]. "','". $evId[3]. "',current_timestamp,current_timestamp,current_timestamp);";
		
		$_log->write($insGcmEv. "\n");
		Debug::write($insGcmEv);
		
		$resGcmEv = pg_query($conn, $insGcmEv);
		
		$resLsSeqId = pg_query($conn, "SELECT currval('qgis.gcm_event_event_id_seq');");
		$rowLsSeqId = pg_fetch_assoc($resLsSeqId);
		$regEvId = $rowLsSeqId["currval"];
		
		Debug::write($regEvId);
		// (1)で抽出したメッセージIDsをガードマン端末に送る(GCMで)
		$ret = sendGcmEvent($rowGcmId["gcm_id"], $regEvId. ",". $events);
		//$_log->write("RETURN->". $ret. "\n");
		
		$updReqRet = "UPDATE qgis.gcm_event SET req_ret='". $ret. "',upddatetime=current_timestamp WHERE event_id='". $regEvId. "';";
		$_log->write("SQL->". $updReqRet. "\n");
		$resReqRet = pg_query($conn, $updReqRet);
	}
}
catch(Exception $exc)
{
	$_log->write("exception->". $exc. "\n");
}

pg_close($conn)
?>
