<?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)); 
} 

// 2016-08-01 huibong
// SKB sms MySQL DB modifiy
function NewSMSserver($msg,$passwd,$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>";
		makelog(false, "fail to pgsql querty : $strSqlpg ");
		return false;
	}
	
	// SKB CDN modify

	$dbConnMySql = new dbconnect('222.239.93.143:13306', 'lghv_user', $passwd, 'lghv_db', __FILE__, __LINE__);
	if(!$dbConnMySql->bConnect){
		echo "SMS  Server 1 (222.239.93.143) Connect Failed!"; echo "<br><br>";
		makelog(false, "SMS  Server 1 (222.239.93.143) Connect Failed!");
		return false;
	}

	echo "SMS Server 1 (222.239.93.143) connecting!"; echo "<br><br>";

	while($dbConnPgSql->next_record())
	{
		$cellphone = $dbConnPgSql->f("member_cellphone");

		$tmpSqlmy  = "INSERT INTO lghv_db.TBL_SEND_TRAN( fmsgtype, fmessage, fsenddate, fdestine, fcallback ) ";
		$tmpSqlmy .= "VALUES ( '0', '$msg', now(), '$cellphone', '0221823688' ); ";

		//echo "mysql query : " . $tmpSqlmy; echo" <br><br>";

		$res=$dbConnMySql->query($tmpSqlmy, __FILE__, __LINE__);

		if(!$res->result) 
		{
			echo "fail to send SMS ";  echo "<br><br>";
			makelog(false, $tmpSqlmy);
		
			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()); ";

	}
	
	$dbConnMySql->close();
	
	if($user_count == $dbConnPgSql->nf()) 
	{
		echo "Server 1 (222.239.93.143) : success to All send SMS  " ; echo "<br><br>";
		$dbConnPgSql->query($tmpSqlpg);

		//makelog(true, $tmpSqlmy);
		return true;
	}
	else 
	{
		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>";
		makelog(false, "SMS  Server 2 (211.39.134.240) Connect Failed!");
		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) {
			 makelog(false, $tmpSqlmy); 
			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;
	}
	 makelog(false, $tmpSqlmy);

	return false;
}

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

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

	$log_dir_yyyymm = $filepath . "/";

	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\n");

	fclose($filep);
} 


$id = $_GET['id'];
$msg = $_GET['msg'];
$passwd ="solbox@#12";


if ($id == "" ) {
	$sid = "ALL";
} else if ($id =="ADMIN") {
	$sid = "ADMIN";	
} else {
	$sid = $id;
}


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 )
				{
					// send sms success !!
					break;
				}
			}

			if(!$SMS_send_Success )
			{
			 echo "Unexpected error was occured "; echo "<br><br>";
			 makelog(false,"Unexpected error was occured " );
			}

		}
		else
		{
			echo "PGSQL `group_seq` failed"; echo "<br><br>";
			makelog(false,"PGSQL `group_seq` failed" );
		}
	
		$dbConnPgSql->close();
	}
	else 
	{
		echo "sid or msg NULL!!!"; echo "<br><br>";
		makelog(false,"PGSQL `group_seq` failed" );
	}

}
else 
{
	echo "Unexpected error was occured. sid : \"$sid\" msg :\"$msg\"\n";  echo "<br><br>";
	makelog(false,"Unexpected error was occured. sid : \"$sid\" msg :\"$msg");
}

?>
