<?php 
ob_start();
error_reporting(E_ALL);
    ini_set("display_errors", 1);
require("../functions/functionUnicode.php");
require("../functions/checkSendPorts.php");
if(curlTest() == 5)
	require("../functions/curlSMS.php");
elseif(fsockopenTest() == 5)
	require("../functions/fsockopen.php");
elseif(fopenTest() == 3)
	require("../functions/fopenSMS.php");
else
{
	echo "لا يوجد لديك دوال مفعلة<br>راجع الإستضافة وفعل إحدى البوابات الثلاث fsockopen و curl و fopen";
	exit;
}
$groupSend = "4,9";
$nextTime = time() + 57;
function cronJobSend($timeCron = '')
{
	global $nextTime;
	global $groupSend;
	$followTime = time();
	include("config.php");
	$defaultUserAccount = $userAccount;
	$passAccount=$passUserAccount = "Mfq-321321!";//$passAccount;
	date_default_timezone_set('Asia/Riyadh');
	//$time = mktime(date("H,i,s,n,j,Y")); 
	$time = mktime(date("H"),date("i"),date("s"),date("n"),date("j"),date("Y"));
	$followTime = $time;  
	//$time = time(); 
	if(isset($conn))   mysqli_close($conn);$conn = mysqli_connect($hostSms, $userConnection, $passwordConnection, $dataBase);
	
	/*if(empty($timeCron))
	{
	    
		$querySendMsgTemp="SELECT `id` FROM msg_send_temp WHERE `sent`!='1' AND (ISNULL(`cronGroup`) || `cronGroup`='') AND `counter` < 20 AND `groupSend` IN ($groupSend) ORDER BY `counter` ASC LIMIT 0, 100";
		$resultSendMsgTemp = mysqli_query($conn, $querySendMsgTemp);
		$numSendMsgTemp = mysqli_num_rows($resultSendMsgTemp);
		if($resultSendMsgTemp && mysqli_num_rows($resultSendMsgTemp))
			while($rowSendMsgTemp = mysqli_fetch_assoc($resultSendMsgTemp))
			{
				$mysqlError = "";
				if(mysqli_query($conn, "START TRANSACTION"))
				{
					mysqli_query($conn, "UPDATE `msg_send_temp` SET `cronGroup`='$time' WHERE `id`='$rowSendMsgTemp[id]'");
					$mysqlError .= mysqli_error($conn);
					mysqli_query($conn, "UPDATE `msg_send_temp` SET `counter`='1' WHERE `id`='$rowSendMsgTemp[id]' AND `counter`='0'");
					$mysqlError .= mysqli_error($conn);
					if($mysqlError)
						mysqli_query($conn, "ROLLBACK");
					else
						mysqli_query($conn, "COMMIT");
				}
			}
		$timeCron = $time;	
	}*/
	
	//AND `cronGroup`='$timeCron' 
	$resultSendMsgTemp = mysqli_query($conn, "SELECT * FROM msg_send_temp WHERE `sent`!='1'  AND `counter` < 20 AND `groupSend` IN ($groupSend) ORDER BY `counter` ASC LIMIT 0, 50");
	$numSendMsgTemp = mysqli_num_rows($resultSendMsgTemp);
	if($resultSendMsgTemp && !empty($numSendMsgTemp))
	while($rowSendMsgTemp = mysqli_fetch_assoc($resultSendMsgTemp))
	{
		if(isset($conn))   mysqli_close($conn);$conn = mysqli_connect($hostSms, $userConnection, $passwordConnection, $dataBase);
		$numbers = $rowSendMsgTemp["numbers"];
		$msg = $rowSendMsgTemp["msg"];
		$userSender = $rowSendMsgTemp["userSender"];
		$MsgID = $rowSendMsgTemp["id"];
		$userId = $rowSendMsgTemp["userId"];
		$countNumbers = $rowSendMsgTemp["countNumbers"];
		$numMsgs = $rowSendMsgTemp["numMsgs"];
		$points = $rowSendMsgTemp["points"];
		$msgKey = $rowSendMsgTemp["msgKey"];
		$api = $rowSendMsgTemp["api"];
		$msgUnique = $rowSendMsgTemp["msgUnique"];
		$excel = $rowSendMsgTemp["excel"];
		$accountBeforSend = $rowSendMsgTemp["accountBeforSend"];
		$accountAfterSend = $rowSendMsgTemp["accountAfterSend"];
		$numbersNotAccepted = $rowSendMsgTemp["numbersNotAccepted"];
		$countNotAccepted = $rowSendMsgTemp["countNotAccepted"];
		$counterRep = $rowSendMsgTemp["counterRep"];
		$sendType = $rowSendMsgTemp["type"];
		$insertDate = $rowSendMsgTemp["insert_date"];
		if(empty($timeFirst))
		{
			if(mysqli_query($conn, "UPDATE msg_send_temp SET `timeFirst`='$time' WHERE `id`='$rowSendMsgTemp[id]'"))
				$timeFirst = $time;
		} if(!isset($timeFirst))$timeFirst=0;
		if(($time - $timeFirst) > 2700)
		{
			$result = sendSMS($userAccount, $passAccount, $numbers, $userSender, $msg, $MsgID,1,$msgUnique);
			$resultJson = $result;
			$result = json_decode($result ,true);
			if($result['Data']['result'] == "20")
				$result['Data']['result'] = "1";
			else{
				$result = sendSMS($userAccount, $passAccount, $numbers, $userSender, $msg, $MsgID,0,$msgUnique);
				$resultJson = $result;
				$result = json_decode($result ,true);
			}
		}
		else{
			$result = sendSMS($userAccount, $passAccount, $numbers, $userSender, $msg, $MsgID,0,$msgUnique);
			$resultJson = $result;
			$result = json_decode($result ,true);	
		}
		if(!empty($result['Data']['result']) && $result['Data']['result']=="1")
		{
			$resultUserName = mysqli_query($conn, "SELECT `userName` FROM `user_login` WHERE id='$userId'");
			if($resultUserName)
			{
				$rowUserName = mysqli_fetch_assoc($resultUserName);
				$userName = $rowUserName["userName"];
				$date = time();
				$sentTime = time();
				$status = $result['status'];
				$responseStatus = $result['ResponseStatus'];
				$msgIdMobily = $result['Data']['msgId'];
				$resultMobily = $result['Data']['result'];
				$messageAr = $result['Data']['MessageAr'];
				$messageEn = $result['Data']['MessageEn'];
				$msgLengthMobily = $result['Data']['msgLength'];
				$countNumberMobily = $result['Data']['countNumber'];
				$pointMobily = $result['Data']['point'];
				$rejectedNumber = $result['Data']['rejectedNumber'];
				$rejectedNumber = str_replace("[", "", $rejectedNumber);
				$rejectedNumber = str_replace("]", "", $rejectedNumber);
				$rejectedNumberExplode = explode(',',$rejectedNumber);
				$rejectedNumberExplode = array_filter($rejectedNumberExplode);
				$rejectedNumberCount = count($rejectedNumberExplode);
				$rejectedNumber = implode(',',$rejectedNumberExplode);
				$rejectedNumber = $numbersNotAccepted.",".$rejectedNumber;
				$rejectedNumberCount = $rejectedNumberCount+$countNotAccepted;
				$queryInsertHistory = "INSERT INTO history (numbers,msg,userSender,date,userName,idUser,countNumbers,numMsgs,points,msgKey,msgType,msgTempId,accountBeforSend,accountAfterSend,`api`,`status`,`responseStatus`,`msgIdMobily`,`resultMobily`,`messageAr`,`messageEn`,`msgLengthMobily`,`countNumberMobily`,`pointMobily`,`rejectedNumber`,`countNotAccepted`,`excel`,`accepted`,`count_accepted`,`type`,`timeSend`,`realDate`,`insert_date`,`result_json`) VALUES 
				('".mysqli_real_escape_string($conn, $numbers)."','".mysqli_real_escape_string($conn, $msg)."','".mysqli_real_escape_string($conn,$userSender)."','".$date."','".$userName."','".$userId."','".$countNumbers."','".$numMsgs."','".$points."','".$msgKey."','1','".$MsgID."','".$accountBeforSend."','".$accountAfterSend."','".$api."','".$status."','".$responseStatus."','".$msgIdMobily."','".$resultMobily."','".$messageAr."','".$messageEn."','".$msgLengthMobily."','".$countNumberMobily."','".$pointMobily."','".$rejectedNumber."','".$rejectedNumberCount."','".$excel."','".$numbers."','".$countNumbers."','".$sendType."','".$sentTime."','".time()."','".$insertDate."','".$resultJson."')";
				$mysqlError = "";
				if(mysqli_query($conn, "START TRANSACTION"))
				{
					mysqli_query($conn, $queryInsertHistory);
					$mysqlError .= mysqli_error($conn);
					mysqli_query($conn, "UPDATE `msg_send_temp` SET `sent`='1',`sentTime`='".$sentTime."' WHERE id='$rowSendMsgTemp[id]'");
					$mysqlError .= mysqli_error($conn);
					if($mysqlError)
						mysqli_query($conn, "ROLLBACK");
					else
						mysqli_query($conn, "COMMIT");
				}
			}
		}
		elseif($result == "14" || $result == "15" || $result == "16" || $result == "17" || $result == "--1"){
			$status = $result['status'];
			$responseStatus = $result['ResponseStatus'];
			$messageAr = $result['Error']['MessageAr'];
			$messageEn = $result['Error']['MessageEn'];
			if($counterRep!=1)
			{
				$rejectedNumber2 = $numbersNotAccepted.",".$numbers;
				$countNotAcceptedAll = $countNotAccepted+$countNumbers;
				mysqli_query($conn, "UPDATE msg_send_temp SET counter='20',`followTime`='$followTime',`numbersNotAccepted`='$rejectedNumber2',`countNotAccepted`=`countNotAccepted`+'$countNotAcceptedAll',`status`='".$status."',`responseStatus`='".$responseStatus."',`messageAr`='".$messageAr."',`messageEn`='".$messageEn."' WHERE id=$rowSendMsgTemp[id]");
			}
			else
				mysqli_query($conn, "UPDATE msg_send_temp SET counter='20',`followTime`='$followTime',`status`='".$status."',`responseStatus`='".$responseStatus."',`messageAr`='".$messageAr."',`messageEn`='".$messageEn."' WHERE id=$rowSendMsgTemp[id]");
		}
		elseif($result != "0" || $result != "-1" || $result != "-2" || $result != ""){
			$status = $result['status'];
			$responseStatus = $result['ResponseStatus'];
			$messageAr = $result['Error']['MessageAr'];
			$messageEn = $result['Error']['MessageEn'];
			mysqli_query($conn, "UPDATE msg_send_temp SET counter=counter+1,`followTime`='$followTime',`status`='".$status."',`responseStatus`='".$responseStatus."',`messageAr`='".$messageAr."',`messageEn`='".$messageEn."' WHERE id=$MsgID");	
		}
	}
	mysqli_close($conn);
	if(time()<$nextTime)
	{
		ob_flush();
		sleep(5);
		if(empty($numSendMsgTemp))
			cronJobSend();
		else
			cronJobSend($time);	
	}
	return 0;	
}
cronJobSend();

ob_end_flush();
?>