<?php
/**
 * Processing Forget password form data:
 * check data then generate new password and send it through SMPT Email
 *
 * PHP version 7.3
 *
 * @package        SMS
 * @version        Release 1.0.0
 * @create_by      Mohammad aljaouni
 * @create_date    10-08-2020
 * @edited_by      Mohammad aljaouni
 * @last_edit_date 10-08-2020
 * @todo           Nothing
 */
ob_start();
session_start();
$chain = "AWdrh78y892Djk*^523*%$#ghgHGHia&%$*)AsfdsLJnLaad";
include("validateLogin.php");
include("includeInformation.php");
include_once("../functions/pointFunction.php");
include_once("../functions/sendFunctions.php");
include("../functions/insertMsg.php");
$link="sendMsgReportsList.php";
function filterNumberNew($number){
	global $conn;
	$number = preg_replace("/[^0-9]/", "", $number);
	if(substr($number, 0, 3)=="966" && strlen($number)!=12){
		return false;
	}else{
		if(substr($number,0,3) == '966' || substr($number,0,4) == '+966' || substr($number,0,2) == '05' || substr($number,0,1) == '5') {
			if(in_array(substr($number,0,6), array('+96650','+96651','+96653','+96654','+96655','+96656','+96658','+96659','+96657'))) {
				$number = ltrim($number, "");
			}elseif(in_array(substr($number,0,3), array('050','051','053','054','055','056','058','059','057'))) {
				$number = preg_replace('/0/', '966', $number, 1);
			} elseif(in_array(substr($number,0,2), array('50','51','53','54','55','56','58','59','57'))){
				$number = '966'.$number;
			}
			return $number;
		
		} else {
			return false;
		}
	}
}

$sendNow = "";
$timeSendLater = '-1';
$date = date("A h:i : m-d-Y");
if(!empty($_POST["msg"])) {
	$msg = clearArabicNum($_POST['msg']);
	/*if(empty($msg)) {
		exit('SMS message is empty');
	}*/
}
$unique = "0";	
if(isset($_POST['deleteNum']) && $_POST['deleteNum'] == "on")
{
	$unique = "1"; 	
}
$msg = $_POST["msg"];
$numbers = $_POST["numbers"];
$userSender = trim($_POST['userSender']);
$acceptedNumbers = array();
$rejectedNumbers = array();
$numbersDetails = array();
$messagesDetails = array();
$category = "";

if(!empty($_POST['categoryId'])) {

	foreach($_POST['categoryId'] as $category) {

		$query = "SELECT id,name, number FROM `user_number` WHERE (`userId`=$_SESSION[userId] OR `userId`=1) AND `categoryId`=$category AND `name` IS NOT NULL";
		$result = mysqli_query($conn, $query);
		$num = mysqli_num_rows($result);
		if(!empty($num)) {
			while($row = mysqli_fetch_assoc($result)) {
				$number = filterNumberNew($row['number']);
				if($number) {
					$acceptedNumbers[] = $number;
					if(!empty($row['name'])) {
						if(!empty($unique))
							$numbersDetails[$number] = $row['name']; //No Repeat
						else
							$numbersDetails[] = array(0=>$number, 1=>$row['name']); //Repeat
					} else {
						continue;
					}					
				} else {
					$rejectedNumbers[] = $row['number'];
					continue;
				}
			}
		}
	}
}

if(!empty($_POST['numbers'])) {
	$numbers = $_POST["numbers"];
	//$numbers =str_replace("\n",";",$_POST["numbers"]);	 
	$numbersLineArr = preg_split("/\\r\\n|\\r|\\n/", $numbers);
	if(!empty($unique))
		$numbersLineArr = array_filter($numbersLineArr);
	if(count($numbersLineArr) > 0) {
		foreach($numbersLineArr as $oneNumberDetails) {
			if(empty($oneNumberDetails))
				continue;
			list($name, $number) = explode(',', $oneNumberDetails);
			$filterNumber = filterNumberNew($number);
			if($filterNumber) {
				$acceptedNumbers[] = $filterNumber;
				if(!empty($name)) {
					if(!empty($unique))
						$numbersDetails[$filterNumber] = $name; //No Repeat
					else
						$numbersDetails[] = array(0=>$filterNumber, 1=>$name); //Repeat
				} else {
					continue;
				}				
			} else {
				$rejectedNumbers[] = $number;
				continue;
			}
		}
	}
}
if(!empty($unique))
	$acceptedNumbers = array_filter($acceptedNumbers);
if(!empty($unique))
	$rejectedNumbers = array_filter($rejectedNumbers);
$totalPoints = 0;

if(count($numbersDetails) > 0) {
	if(!empty($unique)) {
		foreach($numbersDetails as $oneNumber => $oneName) {
			$oneMessagePoint = 0;
			$oneMessage = str_replace('<<Name>>', $oneName, $msg);
			$oneMessagePoint = getPoints($oneNumber, $oneMessage);
			$totalPoints+=$oneMessagePoint;
			$messagesDetails[$oneNumber] = $oneMessage;
		}
	} else {
		foreach($numbersDetails as $key => $oneMsg) {
			$oneMessagePoint = 0;
			$oneMessage = str_replace('<<Name>>', $oneMsg[1], $msg);
			$oneMessagePoint = getPoints($oneMsg[0], $oneMessage);
			$totalPoints+=$oneMessagePoint;
			$messagesDetails[] = array(0=>$oneMsg[0], 1=>$oneMessage); //Repeat
		}
	}
}

$points = $totalPoints;
if(empty($messagesDetails)){
	header("location: $link?error=rp");
    exit;
	
}
$MsgID =0;

if(!empty($unique)){
	foreach ($messagesDetails as $key => $value)
	{
		$queryAccount = "SELECT * FROM $userLogin WHERE id=$_SESSION[userId]";
		$resultAccount = mysqli_query($conn, $queryAccount);
		$rowAccount = mysqli_fetch_array($resultAccount);
		$mysqlError = "";
		if(mysqli_query($conn, "START TRANSACTION"))
		{
			$points = getPoints($key, $value);
			$queryAccountUpdate = "UPDATE $userLogin SET `account`=`account`-".ceil($points)." WHERE `id`=".$_SESSION['userId'];
			$resultAccountUpdate = mysqli_query($conn, $queryAccountUpdate);
			$mysqlError.= mysqli_error($conn);
			
			$md5STR = $_SESSION["userId"].$userSender.$key.$value.time();
			$msgKey = md5($md5STR);
			
			if(!empty($resultAccountUpdate))
			{
				$numMsgs = getMsgLen($value);
				$subMsgKey = $msgKey.'_1';
				$original = date('Y').date('m').date('d');
				$resultFunction = insertDBNumber($_SESSION["userId"],$userSender,$key,$value,3,$_SESSION["msgUnique"],0,0,1);
				++$MsgID;
			} else {
				header("location: $link?sendErrorMsg=1");
				exit;
			}
		}
	}
}else{
	foreach ($messagesDetails as $key => $oneMsg)
	{
		$queryAccount = "SELECT * FROM $userLogin WHERE id=$_SESSION[userId]";
		$resultAccount = mysqli_query($conn, $queryAccount);
		$rowAccount = mysqli_fetch_array($resultAccount);
		$mysqlError = "";
		if(mysqli_query($conn, "START TRANSACTION"))
		{
			$points = getPoints($oneMsg[0], $oneMsg[1]);
			$queryAccountUpdate = "UPDATE $userLogin SET `account`=`account`-".ceil($points)." WHERE `id`=".$_SESSION['userId'];
			$resultAccountUpdate = mysqli_query($conn, $queryAccountUpdate);
			$mysqlError.= mysqli_error($conn);
			
			$md5STR = $_SESSION["userId"].$userSender.$oneMsg[0].$oneMsg[1].time();
			$msgKey = md5($md5STR);
			
			if(!empty($resultAccountUpdate))
			{
				$numMsgs = getMsgLen($oneMsg[1]);
				$subMsgKey = $msgKey.'_1';
				$original = date('Y').date('m').date('d');
				$resultFunction = insertDBNumber($_SESSION["userId"],$userSender,$oneMsg[0],$oneMsg[1],3,$_SESSION["msgUnique"],0,0,1);
					++$MsgID;
			} else {
				header("location: $link?sendErrorMsg=1");
				exit;
			}
		}
	}
	
}
if(!empty($MsgID)) {
	header("location: printMessage.php?res=221");
	exit;
} else {
	header("location: $link?sendErrorMsg=1");
	exit;
}
ob_end_flush();
?>
