<?php
require("../../inc/header.inc");
?>

<script language="JavaScript">
function selectOrder(order_field)
{
	var page_num=document.myform.page_num.value;
	var newurl="./replace_down.php?order_field="+order_field+"&page_num="+page_num;
	window.location.href=newurl;
}

function selectPage()
{
	var page_num=document.myform.page_num.value;
	var order_field=document.myform.order_field.value;
	var newurl="./replace_down.php?order_field="+order_field+"&page_num="+page_num;
	window.location.href=newurl;
}

function selectPrevious()
{
	var page_num=document.myform.page_num.value-1;
	var order_field=document.myform.order_field.value;
	var newurl="./replace_down.php?order_field="+order_field+"&page_num="+page_num;
	window.location.href=newurl;
}

function selectNext()
{
	var page_num=document.myform.page_num.value+1;
	var order_field=document.myform.order_field.value;
	var newurl="./replace_down.php?order_field="+order_field+"&page_num="+page_num;
	window.location.href=newurl;
}

function selectMSISDN(msisdn)
{
	var page_num=document.myform.page_num.value;
	var order_field=document.myform.order_field.value;
	
	var res=confirm("Select the MSISDN="+msisdn);
	if(res == false)
		return;
	parent.replace_up.myform.replacingMSISDN.value=msisdn;
	parent.replace_up.myform.page_num.value=page_num;
	parent.replace_up.myform.order_field.value=order_field;
}
</script>

<body leftmargin="15" rightmargin="10" onload="javascript:adjust_frame('down');" onresize="javascript:adjust_frame('down');" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;">
<?php
adjust_head_frame("down");
adjust_title_head_frame("down");
adjust_title_tail_frame("down");
adjust_content_head_frame("down");	

if(!isset($page_num))
	$page_num=0;
if(!isset($order_field))
	$order_field="msisdn";
	
	
if(isset($replace_opt) && $replace_opt == 1)
{
	if($DEBUG)
	{
		echo "replacedMSISDN=$replacedMSISDN<br>";
		echo "replacingMSISDN=$replacingMSISDN<br>";
		echo "page_num=$page_num,order_field=$order_field<br>";
	}
	
	//check the status
	$check_server_systype=array(330,360,375);
	$check_server_name=array("HLR","PPS","OPPS");
	
	for($i=0;$i<sizeof($check_server_systype);$i++)
	{
		$sql="select * from OMC_PUB.sysInfo where sysTypeNo={$check_server_systype[$i]} and baseStat>0 ";
		$res=@mysqli_query($pubConn,$sql);
		if(mysqli_num_rows($res) == 0)
			exit("<font color=red>{$check_server_name[$i]} is not online</font><br>");
		else
		{
			$rows=@mysqli_fetch_array($res);
			$sysNo=$rows[sysNo]+0;
			$server_sysId[$i]="{$check_server_systype[$i]}_{$sysNo}_0";
			//echo "server_sysId[$i]={$server_sysId[$i]}<br>";
		}
	}
	
	//get HLR IMSI by replaced msisdn
	$replacedMSISDN91=omc_keep_length("91".$replacedMSISDN,'E',18,0);
	$replacingMSISDN91=omc_keep_length("91".$replacingMSISDN,'E',18,0);
	$sql="select imsi from HLR_DB.subscriberData where inter_msisdn = '{$replacedMSISDN91}' ";
	//echo "$sql<br>";
	$res=@mysqli_query($pubConn,$sql);
	$num=mysqli_num_rows($res);
	if($num == 0)
	{
		echo "<font color=red>Can not find HLR subscriber by MSISDN={$replacedMSISDN}</font><br>";
		exit();
	}
	$rows=@mysqli_fetch_array($res);
	$HLR_IMSI=$rows[imsi];
	$HLR_replaced_IMSI=substr($HLR_IMSI,1);
	

	//read HLR subscriber by IMSI
	printInfo("Read HLR subscriber IMSI=$HLR_IMSI, MSISDN=$replacedMSISDN","blue");
	clearCommTable();
	$commId=subsCommSend($server_sysId[0],0,$HLR_IMSI,"ALL",1,0);
	checkComm($commId);
	
	//read PPS subscriber by MSISDN
	printInfo("Read PPS subscriber MSISDN=$replacedMSISDN","blue");
	clearCommTable();
	$commId=subsCommSend($server_sysId[1],0,$replacedMSISDN,"ALL",1,0);
	checkComm($commId);
	
	//save the PPS subscriber data
	$sql="desc PPS_DB.user_info ";
	$res=@mysqli_query($pubConn,$sql);
	$pps_field_num=mysqli_num_rows($res);
	if($pps_field_num <= 0)
		printInfo("PPS_DB.user_info table is null<br>");
	$i=0;
	while($rows=@mysqli_fetch_array($res))
	{
		$pps_field_name[$i]=$rows[Field];
		if(stristr($rows[Type],"int"))
			$pps_field_type[$i]="int";
		else
			$pps_field_type[$i]="char";
		$i++;
	}
	
	$sql="select * from PPS_DB.user_info where msisdn='{$replacedMSISDN}' ";
	$res=@mysqli_query($pubConn,$sql);
	
	$rows=@mysqli_fetch_array($res);
	$i=0;
	while($i<$pps_field_num)
	{
		if(trim($rows[$i]) == "")
			$pps_field_value[$i]="";
		else
			$pps_field_value[$i]=$rows[$i];
		$i++;
	}
	
	//read OPPS subscriber by MSISDN
	printInfo("Read OPPS subscriber MSISDN=$replacedMSISDN","blue");
	clearCommTable();
	$commId=subsCommSend($server_sysId[2],0,$replacedMSISDN,"ALL",1,0);
	checkComm($commId);
	
	
	
	//Modify the HLR MSISDN
	printInfo("Modify HLR subscriber MSISDN from $replacedMSISDN to $replacingMSISDN","blue");
	$sql="update OBJ_330.tmpSubsData_0 set inter_msisdn='{$replacingMSISDN91}' where imsi='{$HLR_IMSI}' ";
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
	//echo "$sql<br>";
	
	clearCommTable();
	$commId=subsCommSend($server_sysId[0],0,$HLR_IMSI,"inter_msisdn",2,0);
	checkComm($commId);
	
	//read the new HLR subscriber
	printInfo("Read HLR subscriber IMSI=$HLR_IMSI, MSISDN=$replacingMSISDN","blue");
	clearCommTable();
	$commId=subsCommSend($server_sysId[0],0,$HLR_IMSI,"ALL",1,0);
	checkComm($commId);
	
	//get the replaced OPPS subscriber data
	$sql="select * from OBJ_375.tmpSubsData_0 where msisdn='{$replacedMSISDN}' ";
	$res=@mysqli_query($pubConn,$sql);
	$num=mysqli_num_rows($res);
	if($num < 1)
	{
		printInfo("Can not find OPPS subscriber msisdn=$replacedMSISDN","red");
		exit();
	}	
	$rows=@mysqli_fetch_array($res);
	$replaced_opps_userType=$rows[userType]+0;
	
	//modify the replaced OPPS subscriber
	printInfo("Modify OPPS subscriber MSISDN=$replacedMSISDN 's User Type from OPR-1 to OPR-0","blue");
	//,imsi='$HLR_replacing_IMSI'
	$sql="update OBJ_375.tmpSubsData_0 set oprFlag='0',imsi=' ' where msisdn='{$replacedMSISDN}' ";
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
	//echo "$sql<br>";
	
	clearCommTable();
	$commId=subsCommSend($server_sysId[2],0,$replacedMSISDN,"oprFlag,imsi",2,0);
	checkComm($commId);
	
	//read the replaced OPPS subscriber
	printInfo("Read OPPS subscriber MSISDN=$replacedMSISDN","blue");
	clearCommTable();
	$commId=subsCommSend($server_sysId[2],0,$replacedMSISDN,"ALL",1,0);
	checkComm($commId);
	
	
	//modify the replacing OPPS subscriber
	printInfo("Modify OPPS subscriber MSISDN=$replacingMSISDN 's User Type from OPR-0 to OPR-1","blue");
	//
	$sql="update OBJ_375.tmpSubsData_0 set oprFlag='1',imsi='$HLR_replaced_IMSI',userType='$replaced_opps_userType' where msisdn='{$replacingMSISDN}' ";
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
	//echo "$sql<br>";
	
	clearCommTable();
	$commId=subsCommSend($server_sysId[2],0,$replacingMSISDN,"oprFlag,imsi,userType",2,0);
	checkComm($commId);
	
	//read the replacing OPPS subscriber
	printInfo("Read OPPS subscriber MSISDN=$replacingMSISDN","blue");
	clearCommTable();
	$commId=subsCommSend($server_sysId[2],0,$replacingMSISDN,"ALL",1,0);
	checkComm($commId);
	
	//delete old PPS subscriber
	printInfo("Delete PPS subscriber MSISDN=$replacedMSISDN","blue");
	clearCommTable();
	$commId=subsCommSend($server_sysId[1],0,$replacedMSISDN,"ALL",4,0);
	checkComm($commId);
	$sql="delete from OBJ_360.tmpSubsData_0 where msisdn='{$replacedMSISDN}' ";
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
	$sql="delete from PPS_DB.user_info where msisdn='{$replacedMSISDN}' ";
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
	
	
	//create new PPS subsriber
	printInfo("Create PPS subsriber MSISDN=$replacingMSISDN","blue");
	//INSERT INTO omcPubVarConf (instance, pubVarName, pubVarValue, remark) VALUES ('24', '1', '1', '1') 
	$sql="insert into OBJ_360.tmpSubsData_0 (";
	$field_sql=" values(";
	$pps_field_list="";

	for($i=0;$i<$pps_field_num;$i++)
	{
		$sql.=$pps_field_name[$i];
		
		if($pps_field_type[$i] == "int")
			$field_sql.=$pps_field_value[$i];
		else
		{
			if($pps_field_name[$i] == "msisdn")
				$field_sql.="'".$replacingMSISDN."'";
			else
				$field_sql.="'".$pps_field_value[$i]."'";
		}
		
		if($i == $pps_field_num-1)
		{
			$field_sql.=")";
			$sql.=")";
			$pps_field_list.=$pps_field_name[$i];

		}
		else
		{
			$field_sql.=", ";
			$sql.=", ";
			$pps_field_list.=$pps_field_name[$i].",";
			
		}
	}
	$sql.=$field_sql;
	$update_sql.=" where msisdn='{$replacingMSISDN}' ";
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
	//echo "<p>$sql<p>";
	$sql=str_replace("OBJ_360.tmpSubsData_0","PPS_DB.user_info",$sql);
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
	
	//echo "<p>$sql<br>";
	//echo "<p>$pps_field_list<br>";
	
	
	
	clearCommTable();
	$commId=subsCommSend($server_sysId[1],0,$replacingMSISDN,$pps_field_list,3,0);
	checkComm($commId);
	
	clearCommTable();
	$commId=subsCommSend($server_sysId[0],0,$HLR_IMSI,"ALL",1,0);
	checkComm($commId);
	
	
	echo "\n<script language=\"JavaScript\">\n";
	echo "alert('MSISDN of the selected user has been successfully changed from $replacedMSISDN to $replacingMSISDN;User Type = Hybrid');\n";
	echo "</script>\n";
}

$maxRecordPerPage=20;

if(!isset($classValue))
	$classValue=0;
$classValue=$classValue-1;
//All
if($classValue == -1)
	$classWhere=" ";
//Ordinary
else
	$classWhere=" and class=$classValue ";
	
$sql="select * from OPR_DB.subscriberData where msisdn is not null $classWhere ";
$res=@mysqli_query($pubConn,$sql);
$record_total_num=mysqli_num_rows($res);
$page_num_total=ceil($record_total_num/$maxRecordPerPage);
//echo "record_total_num=$record_total_num<br>";

$select_fields=array("msisdn","oprFlag","class");
$show_fields=array("MSISDN","User Type","Class");

$oprClassLabel=array(0=>"Ordinary",1=>"Premier",2=>"VIP");

$select_fields_flip=array_flip($select_fields);
$oprFlagFiledPos=$select_fields_flip['oprFlag'];

$limit_from=$page_num*$maxRecordPerPage;

	
$sql="select * from OPR_DB.subscriberData where msisdn is not null $classWhere order by $order_field LIMIT $limit_from,$maxRecordPerPage ";
$res=@mysqli_query($pubConn,$sql);
$record_num=0;
$field_num=sizeof($select_fields);
while($rows=@mysqli_fetch_array($res))
{
	for($i=0;$i<$field_num;$i++)
	{
		$records[$record_num][$i]=$rows[$select_fields[$i]];
	}
	$record_num++;
}
echo mysqli_error($pubConn);
	
if($record_num == 0)
	exit("No record found!<br>");

echo "<form name=\"myform\" method=post action=\"replace_down.php\">";
echo "<table border=0 width=100%>";
echo "<tr>";
echo "<td align=left>";
if((($page_num+1)*$maxRecordPerPage) > $record_total_num)
	$tmp=$record_total_num;
else
	$tmp=($page_num+1)*$maxRecordPerPage;
echo "Record <font color=blue>".($page_num*$maxRecordPerPage+1)."</font> - <font color=blue>".($tmp)."</font>(Total:$record_total_num)";
echo "</td>";
echo "<td align=right>";
	if($page_num > 0)
		echo "<a href=# onClick=\"javascript:selectPrevious();\">";
	echo "Previous<IMG alt=Previous border=0 align=absBottom src=../../images/left.gif ></a>";
	if($page_num > 0)
		echo "</a>";
	echo "<select size=1 name=\"page_num\" onchange=\"javascript:selectPage();\">";
	for($i=0;$i<$page_num_total;$i++)
	{
		echo "<option value=$i";
		if($i == $page_num)
			echo " selected ";
		echo ">".($i+1)."</option>";
	}
	echo "</select>";
	if($page_num < ($page_num_total-1))
		echo "<a href=# onClick=\"javascript:selectNext();\">";
	echo "<IMG alt=Next border=0 align=absBottom src=../../images/right.gif >Next</a>";
	if($page_num < ($page_num_total-1))
		echo "</a>";
echo "</td>";
echo "</table>";



echo "<table border=\"1\" width=\"100%\" cellpadding=\"2\" cellspacing=\"0\" bordercolor=\"#666666\" bordercolordark=\"#FFFFFF\" bgcolor=\"#FFFFFF\">";
echo "<tr bgcolor=#E6E6E6>";
for($i=0;$i<$field_num;$i++)
	echo "<td align=center><a href=# onclick=\"javascript:selectOrder('{$select_fields[$i]}');\">{$show_fields[$i]}</a></td>";
echo "</tr>";



for($i=0;$i<$record_num;$i++)
{
	echo "<tr>";
	for($j=0;$j<$field_num;$j++)
	{
		if($select_fields[$j] == "msisdn")
		{
			echo "<td align=center>";
			if($records[$i][$oprFlagFiledPos] == 0)
				echo "<a href=# onclick=\"javascript:selectMSISDN('{$records[$i][$j]}');\">{$records[$i][$j]}</a>";
			else
				echo "<font color=#cecece>{$records[$i][$j]}</font>";
			echo "</td>";
		}
		else if($select_fields[$j] == "oprFlag")
		{
			echo "<td align=center>";
			if($records[$i][$j] == 0)
				echo "Idle";
			else
				echo "In Use";
			echo "</td>";
		}
		else if($select_fields[$j] == "class")
		{
			
			echo "<td align=center>";
			$showValue=$oprClassLabel[$records[$i][$j]];
			echo "$showValue";
			echo "</td>";
		}
		else
		{
			echo "<td align=center>{$records[$i][$j]}</td>";
		}
	}
	echo "</tr>";
}

echo "</table>";


echo "<input type=hidden name=\"order_field\" value=\"$order_field\">";
echo "</form>";

function checkComm($commId)
{
	$sep=explode("-",$commId);
	for($i=0;$i<sizeof($sep);$i++)
	{
		if(trim($sep[$i]) == "")
			continue;
		do{
			$sql="select * from OMC_PUB.subscriberComm where commId={$sep[$i]} ";
			$res=@mysqli_query($pubConn,$sql);
			$rows=@mysqli_fetch_array($res);
			$remark=$rows[remark];
			
		}while(trim($remark) == "");
		//echo "$sql<br>";
		//echo "commId={$sep[$i]},remark=$remark<br>";
		if(stristr($remark,"process finished"))
			printInfo("...successful<br>","blue");
		else
		{
			printInfo("...fail<br>","red");
			exit();
		}
	}
}

function clearCommTable()
{
	$sql="delete from OMC_PUB.subscriberComm ";
	$res=@mysqli_query($pubConn,$sql);
	echo mysqli_error($pubConn);
}

function printInfo($info,$color)
{
	echo "<font color=$color>$info</font>";
}

function subsCommSend($sysId,$dataTypeNo,$indexValueList,$fieldNameList,$commType,$newIndexValue=0){
	//global $pubDb,$commTable;
	$DEBUG = 0;
	$pubDb = 'OMC_PUB';
	$commTable = 'subscriberComm';
	$ipTable = 'sysInfo';

	$nReadComm		= 1;
	$nChangeComm	= 2;
	$nCreateComm	= 3;
	$nDeleteComm	= 4;
	$nLoadIndexComm	= 5;
	$nReplaceIndexComm=6;

	$sysIdArr = explode('_',$sysId);
	$sysTypeNo = $sysIdArr[0];
	$sysNo	   = $sysIdArr[1];
	$subSysNo  = $sysIdArr[2];
	
	$comm="echo 'subsCommSend(<$sysId>,<$dataTypeNo>,<$indexValueList>,<$fieldNameList>,<$commType>,<0>)' >> /tmp/subCommand.txt";
	system($comm);
	
	//step 1: delete overtime and imcompetent command
	$overTime = date("Y-m-d H:i:s", mktime(date("H"),date("i")-1,date("s"),date("m"),date("d"),date("Y")));
	$delSql = "DELETE FROM $commTable WHERE (commState ='0' OR commState ='3') AND sendTime < '$overTime'";
	if($DEBUG) echo"<br>delete command sql = $delSql";
	mysqli_query($pubConn,$delSql);
	echo mysqli_error($pubConn);

	$overTime = date("Y-m-d H:i:s", mktime(date("H"),date("i")-30,date("s"),date("m"),date("d"),date("Y")));
	$delSql = "DELETE FROM $commTable WHERE sendTime < '$overTime'";
	if($DEBUG) echo"<br>delete command sql = $delSql";
	mysqli_query($pubConn,$delSql);
	echo mysqli_error($pubConn);
	
	/*
	//step 2: check the system's ip
	$chkIpSql = "SELECT ip FROM $ipTable
					WHERE sysTypeNo='$sysTypeNo' AND sysNo='$sysNo' AND subSysNo='$subSysNo'
					";
	if($DEBUG) echo"<br>chkIpSql = $chkIpSql";
	$chkIpResult = mysqli_query($pubConn,$chkIpSql);
	echo mysqli_error($pubConn);
	$rowsNum = @mysqli_num_rows($chkIpResult);
	if($rowsNum > 0){
		echo "<script language=\"javascript\"> ";
		echo "alert('Can not find this system's ip address in system infp list,\n Please add it first!'); ";
		echo "</script>";
		return(-1);
	} 
	*/

	//step 3: check the command(............................)
	$chkSql = "SELECT commId FROM $commTable
					WHERE sysTypeNo='$sysTypeNo' AND indexValueList='$indexValueList'
					";
	if($DEBUG) echo"<br>check command sql = $chkSql";
	$chkResult = mysqli_query($pubConn,$chkSql);
	echo mysqli_error($pubConn);
	$rowsNum = @mysqli_num_rows($chkResult);
	if($rowsNum <= 0){
			
		//step 4:insert commands into command table
		if($commType == $nReplaceIndexComm){
			$sendSql="INSERT INTO $commTable 	
				(commType,dataTypeNo,sysTypeNo,sysNo,subSysNo,indexValueList,	fieldNameList,paramType,commState,sendTime,remark)
				VALUES
				('$commType','$dataTypeNo','$sysTypeNo','$sysNo','$subSysNo','$indexValueList',
				'$fieldNameList','0','1',CURRENT_TIMESTAMP,'$newIndexValue')
				";
		}else{
			$sendSql="INSERT INTO $commTable 	
				(commType,dataTypeNo,sysTypeNo,sysNo,subSysNo,indexValueList,fieldNameList,paramType,commState,sendTime)
				VALUES
				('$commType','$dataTypeNo','$sysTypeNo','$sysNo','$subSysNo','$indexValueList',
				'$fieldNameList','0','1',CURRENT_TIMESTAMP)
				";
			
		}
		if($DEBUG)echo"<br>send command sql = $sendSql";
		$sendResult=mysqli_query($pubConn,$sendSql);
		//echo mysqli_error($pubConn);
	}
	
	//step 5:Return commIdStr
	$selSql = "SELECT commId FROM $commTable 
			WHERE sysTypeNo='$sysTypeNo' AND sysNo='$sysNo' AND subSysNo='$subSysNo' 
				AND indexValueList='$indexValueList'
			";
	if($DEBUG) 
	echo"<br>get command id sql = $selSql";
	$selResult=mysqli_query($pubConn,$selSql);
	echo mysqli_error($pubConn);
	$commIdStr='';
	while($selRows = mysqli_fetch_array($selResult)){
		$commIdStr .= $selRows[commId].'-';
	}
	if($DEBUG)echo "<br>commIdStr = $commIdStr";
	if($DEBUG) exit();
	return($commIdStr);
}//end of function sendComm()
adjust_content_tail("down");
?>
