<?php
include '../db/db.php';
session_start();

if(isset($_SESSION['userID'])) {
	$log = htmlspecialchars(strip_tags(trim($_SESSION['userID'])), ENT_QUOTES, 'UTF-8');
} else {
	$log = '';
}

if (empty($log)) {     
	$redirectUrl = "../";
	echo "<script type=\"text/javascript\">";
	echo "window.location.href = '$redirectUrl'";
	echo "</script>";
	 
} else {
	$sqlu = "SELECT id FROM user_acc_tbl WHERE userID='$log' and access=1 and val=1";
	$stmtu = mysqli_query($conn, $sqlu);
	$countu = mysqli_num_rows($stmtu);
	
	if($countu == 1) {
		$rowu = mysqli_fetch_assoc($stmtu);
		$uid = $rowu['id'];
		
		date_default_timezone_set('Asia/Colombo');
		$date = date('Y-m-d');
		$time = date('H:i:s');
		
		/*************************** SEND SMS ***************************/
		
		if(isset($_POST['mtype'])) {
			$mtype = htmlspecialchars(strip_tags(trim($_POST['mtype'])), ENT_QUOTES, 'UTF-8');
			$tel_no = htmlspecialchars(strip_tags(trim($_POST['tel_no'])), ENT_QUOTES, 'UTF-8');
			$cmsg = htmlspecialchars(strip_tags(trim($_POST['msg'])), ENT_QUOTES, 'UTF-8');
			
			$telNo_arr = array();
			
			if($mtype == 1) { // All Customers
				$sql_au = mysqli_query($conn, "SELECT tel_no FROM order_details GROUP BY tel_no");
				while($row_au = mysqli_fetch_array($sql_au)) {
					$telNo_arr[] = $row_au['tel_no'];
				}
			
			} else if($mtype == 2) { // Selected Cust
				if(!empty($tel_no)) {
					$telNo_arr = explode(',', $tel_no);
				}
			
			} else {
				
			}

			if(count($telNo_arr) > 0) {
				/*$url= 'https://smsserver.textorigins.com/Send_sms?';
				$success_count = 0;

				foreach ($telNo_arr as $value) {
					$data_sms = array(
						'src' => 'CYCLOMAX3', //Mask
						'email' => '', //User Email
						'pwd' => '', //User Password
						'msg' => $cmsg, //Message
						'dst' => $value //Phone Number
					);
					
					$msg = http_build_query($data_sms);
					$url .= $msg;
					$ch = curl_init($url);

					curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
					curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
					curl_setopt($ch, CURLOPT_HEADER, false);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

					$result_set = curl_exec($ch);

					if (preg_replace('/\s+/', '',$result_set) == '{"status":"1601","message":"SMSSendSuccessful"}') {
						$success_count++;
					}

					$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
					curl_close($ch);
				}*/

				$result['count']=$success_count;
				$result['status']='1601';
				$result['message']='Successfully Sent';

				echo json_encode($result);
			}

		}    

		/************************************************************/
		
	} else {
		$redirectUrl = "../";
		echo "<script type=\"text/javascript\">";
		echo "window.location.href = '$redirectUrl'";
		echo "</script>";
	}
}
?>