<?php
require_once ($_SERVER['DOCUMENT_ROOT']."/inc/mysql.inc");
require_once ($_SERVER['DOCUMENT_ROOT']."/inc/pgsql.inc");

function cutstr($str,$size) { 
	if(!$size or (strlen($str) <= $size)) return $str; 
	else for($i = 0;$i < $size;$i++) if(ord($str[$i]) > 127) $over++; 
	return chop(substr($str,0,$size - $over%2)); 
} 

function NewSMSserver($msg,$passwd,$dbConnPgSql, $strSqlpg,$group_seq, $sid)
{
	$tmpSqlmy = "";
	$tmpSqlpg = "";
	$user_count =0;
	$cellphone_list = "";

	$dbConnPgSql->query($strSqlpg);

	if($dbConnPgSql->nf() == 0)
	{
		echo "fail to pgsql querty : $strSqlpg "; echo "<br><br>";
		makelog(false, "fail to pgsql querty : $strSqlpg ");
		return false;
	}

	$dbConnMySql = new dbconnect('222.122.18.22', 'smsuser', $passwd, 'sms', __FILE__, __LINE__);
	if(!$dbConnMySql->bConnect){
		echo "SMS  Server 1 (222.122.18.22) Connect Failed!"; echo "<br><br>";
		makelog(false, "SMS  Server 1 (222.122.18.22) Connect Failed!");
		return false;
	}
	echo "SMS Server 1 (222.122.18.22) connecting!"; echo "<br><br>";

	while($dbConnPgSql->next_record())
	{
		$cellphone = $dbConnPgSql->f("member_cellphone");
		if( strlen($cellphone_list) > 0 )
		{
			$cellphone_list .= "|ktics1^" . $cellphone;
		}
		else
		{
			$cellphone_list = "ktics1^" . $cellphone;
		}

		$user_count ++;

		$tmpSqlpg .= "INSERT INTO t_sms_log (group_seq, sms_id, sms_cellphone, sms_message, reg_datetime, update_datetime) ";
		$tmpSqlpg .= "VALUES (".$group_seq.", 'SH_".$sid."', '".$cellphone."', '".$msg."', now(), now()); ";
	}

	echo "phone list : " . $cellphone_list; echo "<br><br>";

	$tmpSqlmy  = "INSERT INTO SDK_SMS_SEND ( USER_ID, SCHEDULE_TYPE, SUBJECT, NOW_DATE,SEND_DATE, CALLBACK, DEST_COUNT, DEST_INFO, SMS_MSG) ";
	$tmpSqlmy .= "VALUES ('ktics1', 0,'ktics1',DATE_FORMAT(now(),'%Y%m%d%H%i%s'),DATE_FORMAT(now(),'%Y%m%d%H%i%s'),'$cellphone',$user_count,'$cellphone_list','$msg')";

	$res=$dbConnMySql->query($tmpSqlmy,__FILE__, __LINE__);
	if(!$res->result) {
		echo "fail to send SMS ";  echo "<br><br>";
		makelog(false, $tmpSqlmy);
		return false;
	}
			
	$dbConnMySql->close();

	if($user_count == $dbConnPgSql->nf()) {
		echo "Server 1 (222.122.18.22) : success to All send SMS  " ; echo "<br><br>";

		$dbConnPgSql->query($tmpSqlpg);

		//makelog(true, $tmpSqlmy);
		return true;
	}

	makelog(false, $tmpSqlmy);

	return false;
}


function SMSserver($msg,$dbConnPgSql,$strSqlpg,$group_seq, $sid )
{
	$tmpSqlmy = "";
	$tmpSqlpg = "";
	$user_count =0;

	$dbConnPgSql->query($strSqlpg);

	if($dbConnPgSql->nf() == 0)
	{
		echo "fail to pgsql querty : $strSqlpg "; echo "<br><br>";
		return false;
	}

	$dbConnMySql = new dbconnect('211.39.134.240', 'sms', '', 'sms', __FILE__, __LINE__);
	if(!$dbConnMySql->bConnect){
		echo "SMS Server 2 (211.39.134.240) Connect Failed "; echo "<br><br>";
		return false;
	}
	echo " SMS SERVER 2 (211.39.134.240) Connectng...";  echo "<br><br>";

	while($dbConnPgSql->next_record())
	{
		$cellphone = $dbConnPgSql->f("member_cellphone");
		$cli_ip = $_SERVER['REMOTE_ADDR'];

		$tmpSqlmy  = "INSERT INTO sms_msg (phone, callback, reqdate, msg,etc1 )  ";
		$tmpSqlmy .= "VALUES ( '$cellphone', '$cellphone', sysdate(), '$msg', '$cli_ip')";

		$res=$dbConnMySql->query($tmpSqlmy,__FILE__, __LINE__);
		if(!$res->result) {
			echo "fail to send SMS ";  echo "<br><br>";
			continue;
		}   
		$user_count ++;

		$tmpSqlpg .= "INSERT INTO t_sms_log (group_seq, sms_id, sms_cellphone, sms_message, reg_datetime, update_datetime) ";
		$tmpSqlpg .= "VALUES (".$group_seq.", 'SH_".$sid."', '".$cellphone."', '".$msg."', now(), now()); ";
	}

//	echo "Server count; "; echo $user_count ; echo "<br><br>";
//	echo "Server nf   ; "; echo $dbConnPgSql->nf(); echo "<br><br>";

	$dbConnMySql->close();

	if($user_count == $dbConnPgSql->nf()){
		echo " SERVER 2 (211.39.134.240):  success to All send SMS  " ; echo "<br><br>";
		
		$dbConnPgSql->query($tmpSqlpg);
		return true;
	}

	return false;
}

function makelog($result,$log_str)
{
	$filepath = "/user/service/log/sms_result";		// 로그파일을 저장한 디렉토리 
	$filename = "log";								// 로그파일의 Prefix

	$yyyymm = date("Ym", time());
	$yyyymmdd = date("Ymd", time());

	$log_dir_yyyymm = $filepath . "/" . $yyyymm;

	if(!is_dir($log_dir_yyyymm)) {
		mkdir($log_dir_yyyymm, 0707);
		chmod($log_dir_yyyymm,0707);
	}

	$file_name_log = $log_dir_yyyymm . "/" . $filename . "-" . $yyyymmdd;

	$filep = fopen("$file_name_log","a");
	if(!$filep)
	{
		echo " Error : Don't open a log file[$file_name_log]."; echo "<br><br>";
		fclose($filep);
		return;
	}

	$log_msg = "";
	$log_msg .= date("Y-m-d H:i:s", time());
	if(result)	$log_msg .= "  Sucess : ";
	else		$log_msg .= "  Fail   : ";
	$log_msg .= $log_str;

	fputs($filep, "$log_msg\n");

	fclose($filep);
} 


$id = $_GET['id'];
$msg = $_GET['msg'];
$passwd ="sms5emffld)";

// rcid is not RC004 ( thinkware )
if ($id == "" || $id != "THINKWARE")
$sid = "ALL";

if ($id == "THINKWARE") {
	$sid = "BD-RC004";
} else if ($id =="ADMIN") {
	$sid = "ADMIN";	
} else if ($id =="AION") {
	$sid = "AION-NC";
} else if ($id =="WARHAM") {
	$sid = "WARHAM";
} else if ($id =="LINPATCH") {
	$sid ="LINPATCH";
} else if ($id =="NHNIDO") {
	$sid ="NHNIDO";
} else if ($id =="SILVER") {
	$sid ="SILVER";
}

if($sid != "" && $msg != "")
{
	$dbConnPgSql = new DB_Sql;
	$strSqlpg  = "SELECT group_seq ";
	$strSqlpg .= "FROM t_group ";
	$strSqlpg .= "WHERE group_id = '".$sid."' AND deleted_yn = 'N'";

	$sizelen=strlen($msg); 
	echo "Message : $msg  Size :$sizelen \n";  echo "<br><br>";
	$dbConnPgSql->query($strSqlpg);
	// FIXME:errchk

	if($dbConnPgSql->nf() == 1)
	{
		$dbConnPgSql->next_record();
		$group_seq = $dbConnPgSql->f("group_seq");
		if($group_seq != "")
		{
			$strSqlpg  = "SELECT member_cellphone ";
			$strSqlpg .= "FROM t_group_member ";
			$strSqlpg .= "WHERE group_seq = ".$group_seq;

			//$dbConnPgSql->query($strSqlpg);

			if($sizelen > 80){
				$strtmp = $msg;
				$msg=cutstr($strtmp,80);
				$sizelen=strlen($msg); 
				echo "CutSTR Message : $msg  Size :$sizelen \n";  echo "<br><br>";
			}

			$SMS_send_Success = false;

			for($i = 0; $i< 2; $i++) {
				$SMS_send_Success = NewSMSserver( $msg, $passwd, $dbConnPgSql, $strSqlpg, $group_seq, $sid );
				if(!$SMS_send_Success) {
					if(SMSserver( $msg, $dbConnPgSql, $strSqlpg, $group_seq, $sid )){   //  send sms success !!
						$SMS_send_Success = true;
						break;
					}
				}else {  // send sms success !!
					break;
				}
			}
			if(!$SMS_send_Success ){
			 echo "Unexpected error was occured "; echo "<br><br>";
			}

		}else
			echo "PGSQL `group_seq` failed"; echo "<br><br>";

		$dbConnPgSql->close();
	}else 
		echo "sid or msg NULL!!!"; echo "<br><br>";
}else 
	echo "Unexpected error was occured. sid : \"$sid\" msg :\"$msg\"\n";  echo "<br><br>";

?>
