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

$numberDetail="";
// Send Variables //
$Language = $_SESSION["language"];
$dir = "rtl";
if($Language == 2)
	$dir = "ltr";
$unique = "0";
if(isset($_POST['deleteNum']) && $_POST['deleteNum'] == "on")
{
	$unique = "1"; 	
}

$sendTime = '';
if(!empty($_POST["msg"])) {
	$msg = clearArabicNum($_POST['msg']);
	/*if(empty($msg)) {
		exit('SMS message is empty');
	}*/
}	
$msg = $_POST["msg"];
$msg = iconv("utf-8", "windows-1256", $_POST["msg"]);

$numbers = $_POST["numbers"];
$userSender = trim($_POST['userSender']);
$numNumber = 0;

$acceptedNumbers = array();
$rejectedNumbers = array();
$numbersDetails = array();
$messagesDetails = array();
$category = "";
if(!empty($_POST['category'])) {
	$categoryStr = $_POST['category'];

	$categoryArr = explode(",",$categoryStr);
	foreach($categoryArr 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;
				}
			}
		}
	}
}

$repArr = array();
if(!empty($_POST['numbers'])) {
	$numbers =  $_POST["numbers"];
	$numbers = iconv("utf-8", "windows-1256", $_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 => $oneName) {
			$oneMessagePoint = 0;
			$oneMessage = str_replace('<<Name>>', $oneName[1], $msg);
			$oneMessagePoint = getPoints($oneName[0], $oneMessage);
			$totalPoints+=$oneMessagePoint;
			$messagesDetails[$key] = $oneMessage;
		}
	}
}


$points = $totalPoints;
$queryAccount = "SELECT * FROM $userLogin WHERE id=$_SESSION[userId]";
$resultAccount = mysqli_query($conn, $queryAccount);
$rowAccount = mysqli_fetch_array($resultAccount);

$errMsg = "";
if ($rowAccount["account"] <= 0)
  $errMsg = $sendMsgLBL["balance0"];
if ($points > $rowAccount["account"])
   $errMsg = $sendMsgLBL["noBalance"];
$pointsRedeclare = $points;
if(!empty($errMsg))
{
    $numberDetail.= "<table width='300px' cellpadding=0 cellspacing=0  style=direction:" . $dir . ">";
    $numberDetail.= "      <tr>    ";
    $numberDetail.= "           <td align='center' nowrap><B>" . $errMsg . "</td>";
    $numberDetail.= "     </tr>  ";
    $numberDetail.= "</table>";
    $numberDetail.= "<input type='hidden' value='0' name='balance'>";
}
else
{
	$numberDetail.= "<input type='hidden' value='".$rowAccount["account"]."' name='balance'>";
    $numberDetail.= "<table border='0'  cellpadding='2' cellspacing='0' style='direction:".$dir.";width: 100%;'>";
	$numberDetail.= "      <tr>";
    $numberDetail.= "           <td align='center' nowrap colspan=2><b> <span style='font-size:11pt'>".$sendFromMyListLBL["usedBalance"]." ( " . $points . " ) ".$sendFromMyListLBL["pointsFromAccount"]."</td>";
    if(!empty($sendTime)){
        $numberDetail.= "      <tr>  ";
        $numberDetail.= "        	<td nowrap class='myModalLabel'>".$sendFromMyListLBL["sendTime"].": </td>";
        $numberDetail.= "      	 	<td nowrap>".$sendTime."</td>";
        $numberDetail.= "     </tr>    ";
    }
    $numberDetail.= "      <tr>  ";
    $numberDetail.= "        	<td nowrap class='myModalLabel'>".$sendFromMyListLBL["sender"].": </td>";
    $numberDetail.= "      	 	<td nowrap>".$userSender."</td>";
    $numberDetail.= "     </tr>    ";
	$numberDetail.= "      <tr>  ";
    $numberDetail.= "           <td nowrap width='100px'><b>".$sendFromMyListLBL["numbersCount"]." : </b></td> ";
    $numberDetail.= "           <td nowrap   width='350px'><b>".(count($acceptedNumbers)+count($rejectedNumbers))."</b></td> ";
    $numberDetail.= "      </tr>    ";
	$numberDetail.= "      <tr>  ";
    $numberDetail.= "           <td nowrap width='100px'><b>".$sendFromMyListLBL["acceptedNumbers"]." : </td> ";
    $numberDetail.= "           <td nowrap   width='350px'><b>".count($numbersDetails)."</b></td> ";
    $numberDetail.= "      </tr>    ";
	if(count($acceptedNumbers) > 0)
	{
		$messagesDetailsArr = array_chunk($messagesDetails, 5);
		$numberDetail.= "      <tr>  ";
		$numberDetail.= "           <td nowrap class='myModalLabel' colspan=2>".$sendFromMyListLBL["viewSendSMS"]." : </td> ";
		$numberDetail.= "      </tr>    ";
		foreach($messagesDetailsArr[0] as $key=>$value)
		{
			$numberDetail .="      <tr>  ";
			$numberDetail .="           <td  nowrap colspan='2'>".$value."</td>";
			$numberDetail .="     </tr> ";
			
		}
	}
	if(count($rejectedNumbers) > 0)
	{
		$rejectedNumbersArr = array_chunk($rejectedNumbers, 5);
		$numberDetail.= "      <tr>  ";
		$numberDetail.= "           <td nowrap class='myModalLabel'>".$sendFromMyListLBL["rejectedNumbersCount"]." : </td>";
		$numberDetail.= "           <td nowrap><b>".count($rejectedNumbers) ."</b></td>";
		$numberDetail.= "     </tr>    ";
		$numberDetail.= "  <tr>  ";
        $numberDetail.= "       <td  nowrap class='myModalLabel' valign='top' colspan='2'>".$sendFromMyListLBL["rejectedNumbers"]." :</td>";
        $numberDetail.= "  </tr>";
		foreach($rejectedNumbersArr[0] as $key=>$value)
		{
			$numberDetail .="      <tr>  ";
			$numberDetail .="           <td  nowrap colspan='2'>".$value."</td>";
			$numberDetail .="     </tr> ";
			
		}
	}
   	if(count($acceptedNumbers) > 0)
    {
        $numberDetail.= " <tr class='trBG' >";
        $numberDetail.= " <td nowrap valign=top colspan=2  align=left style='font-size:13px'><hr />";
		$numberDetail.= " <input  type=button value='".$sendMsgLBL["contSend"]."'  class='btn btn-success waves-effect waves-light' name=send onClick='document.formMsg.submit(); this.disabled=true;'>&nbsp;</td> ";
		$numberDetail.= " </tr>";
    }						
    $numberDetail.= "</table>";
}
echo $numberDetail;
ob_end_flush();
?>
