<?php
header("Content-Type: application/json");
//--- BEGIN Balance Function ---//
function balance($accountData = array()) {
	if(empty($accountData['username']))
		return 1;
	if(empty($accountData['password']))
		return 2;
	global $conn;	
	$returnResult = checkIpData();
	if($returnResult==1)
		return "block ip";
	$userName = $accountData['username'];
	$password = $accountData['password'];
	$password = md5($password);		
	$result = chickUser($userName, $password);
	if($result == 1 || $result == 2)
		return $result;
	$result = mysqli_query($conn, "SELECT `account`, `accountOriginal` FROM `user_login` WHERE `userName`='$userName' AND `password`='$password'");
	$value = mysqli_fetch_assoc($result);
	return $value['accountOriginal']."/".$value['account'];    
}
//--- END Balance Function ---//

//--- BEGIN checkSender Function ---//
function sendMsg($sendMsgData = array()) {
   if (isset($sendMsgData['allMessages'])) {
        $sendMsgData = $sendMsgData['allMessages'];
    }
    $data = "data: ".$sendMsgData['username']."  result: ".$sendMsgData['username'].PHP_EOL;
	$fp = fopen('error_log2.txt', 'a+');
	fwrite($fp, $data);
	
	$filterArray = array();
	$useFlag = "production";//development
	if(!isset($sendMsgData)) {
		$ResponseStatus = 'fail';
		$Data = NULL;
		$Error = array('ErrorCode' => 10,'MessageAr' => "البيانات اللازمة للإرسال غير متوفرة",'MessageEn' => "Required data to send SMS is incorrect or unavailable");
		$jsonRespond = array('status' => 1,'ResponseStatus'=> $ResponseStatus,'Data' => $Data,'Error' => $Error);	
	} else {
		$countoFData = count($sendMsgData);
		if($countoFData == 0) {
			$ResponseStatus = 'fail';
			$Data = NULL;
			$Error = array('ErrorCode' => 10,'MessageAr' => "البيانات اللازمة للإرسال غير متوفرة",'MessageEn' => "Required data to send SMS is incorrect or unavailable");
			$jsonRespond = array('status' => 1,'ResponseStatus'=> $ResponseStatus,'Data' => $Data,'Error' => $Error);	
		} else {
			$messagesCounter = 0;
			if(isset($sendMsgData[0]) || (isset($sendMsgData['username']) && isset($sendMsgData['password']) && isset($sendMsgData['sender']) && isset($sendMsgData['numbers']) && isset($sendMsgData['msg']))) {
				if(isset($sendMsgData['username']) && isset($sendMsgData['password']) && isset($sendMsgData['sender']) && isset($sendMsgData['numbers']) && isset($sendMsgData['msg'])) {
					$sendMsgDataTemp[0] = array('username'=>$sendMsgData['username'], 'password'=>$sendMsgData['password'], 'sender'=>$sendMsgData['sender'], 'numbers'=>$sendMsgData['numbers'], 'msg'=>$sendMsgData['msg']);
					unset($sendMsgData);
					$sendMsgData[0] = $sendMsgDataTemp[0];
				}
				
				foreach($sendMsgData AS $oneMessage) {
					$messagesCounter++;
					$status = 1;
					$oneMessage['password'] = urldecode($oneMessage['password']);
					$oneMessage['sender'] = urldecode($oneMessage['sender']);
					$oneMessage['msg'] = urldecode($oneMessage['msg']);
					if(empty($oneMessage['username']))
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 2,'MessageAr' => "اسم المستخدم غير صحيح او غير متوفر",'MessageEn' => "Username is incorrect or unavailable");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					if(empty($oneMessage['password']))
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 3,'MessageAr' => "كلمة المرورغير صحيحة",'MessageEn' => "Password is incorrect");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
						
					if(empty($oneMessage['msg']))
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 5,'MessageAr' => "نص الرسالة غير صحيح او غير متوفر",'MessageEn' => "Message text is incorrect or unavailable");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					if(empty($oneMessage['numbers']) || count($oneMessage['numbers']) == 0)
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 8,'MessageAr' => "الارقام المرسل اليها غير متوفرة",'MessageEn' => "mobile numbers you sent to are unavailable ");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					$oneMessage['password'] = md5($oneMessage['password']);
					$result = chickUser($oneMessage['username'], $oneMessage['password']);
					if($result == 1)
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 2,'MessageAr' => "اسم المستخدم غير صحيح او غير متوفر",'MessageEn' => "Username is incorrect or unavailable");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					if($result == 2)
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 3,'MessageAr' => "كلمة المرورغير صحيحة",'MessageEn' => "Password is incorrect");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					global $conn;
					$returnResult = checkIpData();
					if($returnResult==1)
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 0,'MessageAr' => "block ip",'MessageEn' => "block ip");
						$jsonRespond = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);
						$valJasonReturn = json_encode($jsonRespond);
						return $valJasonReturn;	
					}	
					$userName = $oneMessage['username'];
					$password = $oneMessage['password'];
					$msg = $oneMessage['msg'];
					$msg = iconv("UTF-8", "windows-1256//IGNORE", $msg);
					$numbers = $oneMessage['numbers'];
					$resultAccount = mysqli_query($conn, "SELECT id,account,allowChangeSender,sender FROM user_login WHERE userName='$userName' AND password='$password'");
					$rowAccount = mysqli_fetch_assoc($resultAccount);
					$userId = $rowAccount['id'];
					$accounts = $rowAccount['account'];
					$sender = trim($oneMessage['sender']);
					if(checkSender($sender, $userId) == 0)
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 4,'MessageAr' => "اسم المرسل غير متاح حاليا لهذا العضو",'MessageEn' => "Sender name is unavailable or unauthorized for this user");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					$msg = clearMsg($msg);
					if(empty($msg))
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 5,'MessageAr' => "نص الرسالة غير صحيح او غير متوفر",'MessageEn' => "Message text is incorrect or unavailable");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					if(!empty($numbers))
					{
						$unique = 1;
						$idSend = $userId . "_" . time();
						$numberDeny = prefixDeny();
						$numbersNotAccepted = "";
						$countOfNotExpted = 0;
						$return = filter_numberWith($idSend, $numbers, $numberDeny, $unique);
						if(!empty($return["notAcceptedNumber"]))
						{
							$numbersNotAccepted = $return["notAcceptedNumber"];
							$countOfNotExpted = $return["countOfNotAcceptedNumber"];
						}
						$numbers = $return["acceptedNumber"];
						$arrayNumbers = explode(",",$numbers);
					}
					elseif(empty($numbers))
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 8,'MessageAr' => "الارقام المرسل اليها غير متوفرة",'MessageEn' => "mobile numbers you sent to are unavailable");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					$points = 0;
					
					$number966 = $numberOhers = '';
					foreach($arrayNumbers as $value)
					{
						if(!empty($value))
						{
							if(substr($value,0,3) === "+966") {
								$value  = substr($value, 1);
							}
							if(substr($value,0,5) === "00966"){
								$value  = substr($value, 2);
							}
							if(substr($value,0,2)=== "05") {
								$value  =substr($value, 1, strlen($value));
								$value = "966".$value;
							}
							elseif(substr($value,0,1) === "5")
								$value = "966".$value;
								
							if(in_array(substr($value,0,5), array('96650','96657','96653','96654','96655','96656','96657','96658','96659','96659','96651')))
								$number966 .= $value.',';
							else
								$numberOhers .= $value.',';
						}
					}
					$points = $points2 = 0;
					if(!empty($number966))
						$points = getPoints($number966, $msg);
					if($accounts <= 0)
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 6,'MessageAr' => "الرصيد = 0",'MessageEn' => "Your current balance is 0");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					if($points > $accounts)
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 7,'MessageAr' => "رصيدك غير كافي لإرسال كود التفعيل",'MessageEn' => "Your current balance is insufficient");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
					$resultFunction = "";
					$viewTime = date("m-d-Y H:i:s");
					$msgMd5 = $md5STR = $userId.$msg.$number966.$sender.date('H') . date('m') . date('d') . date('Y');
					$msgUniqe = md5($msgMd5);
					if($useFlag == "development")
      					$msgUniqe = md5($msgUniqe.rand (1,100));
					if(in_array($msgUniqe, $filterArray)) {
						continue;
					} else {
						$filterArray[] = $msgUniqe;
					}
					if(!empty($number966))
						$resultFunction = insertDBNumber($userId,$sender,$number966,$msg,8,$msgUniqe,$numbersNotAccepted,$countOfNotExpted,0,2,$viewTime);
					if(!empty($resultFunction)){	
						$ResponseStatus = 'success';
						$Error = NULL;
						$Data = array('ErrorCode' => 0,'MessageAr' => "تم حفظ الرسالة وجاري ارسالها",'MessageEn' => "SMS has been saved and will be sent","msgId"=>$resultFunction);	
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $number966,'Data' => $Data,'Error' => $Error);	
						continue;
					} 
					else 
					{
						$ResponseStatus = 'fail';
						$Data = NULL;
						$Error = array('ErrorCode' => 9,'MessageAr' => "لم يتم حفظ الرسالة في قاعدة البيانات,يرجى المحاولة لاحقأ",'MessageEn' => "SMS message did not saved in the database, please try later");
						$jsonRespond[] = array('status' => $status,'ResponseStatus'=> $ResponseStatus,'MsgNumbers' => $oneMessage['numbers'],'Data' => $Data,'Error' => $Error);	
						continue;
					}
				}
				$countSendMsgData = count($sendMsgData);
				if($countSendMsgData>=30)
					$jsonRespond = array_slice($jsonRespond, -10);
			} else {
				$ResponseStatus = 'fail';
				$Data = NULL;
				$Error = array('ErrorCode' => 10,'MessageAr' => "البيانات اللازمة للإرسال غير متوفرة",'MessageEn' => "Required data to send SMS is incorrect or unavailable");
				$jsonRespond = array('status' => 1,'ResponseStatus'=> $ResponseStatus,'Data' => $Data,'Error' => $Error);					
			}
		}
	}
	$sendMsgData[] = date('Y-m-d h:i:s a');
	$sendMsgDataConvert = json_encode($sendMsgData);
	$sendMsgResponse = json_encode($jsonRespond);
	$data = "data: ".$sendMsgDataConvert."  result: ".$sendMsgResponse.PHP_EOL;
	$fp = fopen('error_log.txt', 'a+');
	fwrite($fp, $data);
	return $sendMsgResponse;	
}
//--- END checkSender Function ---//
?>