<?php
include "connect.php";
require 'phpspreadsheet/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Shared\Date;

date_default_timezone_set('Africa/Dar_es_Salaam');

if (isset($_POST['page']) && isset($_POST['action'])) {
	if ($_POST['page'] == "admin") {
		if ($_POST['action'] == "fetchPupilForm") {
			?>
			<!-- Pupils Registration Form -->
			<h2>Pupils Registration Form</h2>
			<form id="pupilsRegistration">
				<!-- First Section -->
				<div class="mb-4">
					<div class="row mb-2">
						<div class="col">
							<hr>
						</div>
						<div class="col">
							<h6 class="text-center">Student Information</h6>
						</div>
						<div class="col">
							<hr>
						</div>
					</div>
					
					<div class="row mb-3">
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" name="fname" class="form-control form-control-sm" id="floatingInput">
								<label for="floatingInput" class="form-label">First Name</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" name="mname" class="form-control form-control-sm" id="floatingInput">
								<label for="floatingInput" class="form-label">Middle Name</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" name="lname" class="form-control form-control-sm" id="floatingInput">
								<label for="floatingInput" class="form-label">Last Name</label>
							</div>
						</div>
					</div>
					<div class="row mb-3">
						<div class="col">
							<div class="form-floating mb-2">
								<input type="date" name="dob" class="form-control form-control-sm" id="dob">
								<label for="dob" class="form-label">Date of Birth</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<select class="form-select" name="className" id="className" required>
									<option selected disabled>Choose .....</option>
									<?php
										$query = $conn->query("SELECT * FROM `class`");
										while ($row = $query->fetch_assoc()) {
											$className = $row["className"];
											$classID = $row["classID"];
											
											echo "<option value=\"".$classID."\">$className</option>";
										}
									?>
									<!-- Add more class options as needed -->
								</select>
								<label for="className" class="form-label">Class Name</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<select class="form-select" name="studentType" id="studentType" required>
									<option selected disabled>Choose .....</option>
									<option value="Day">Day Scholar</option>
									<option value="Boarding">Boarder</option>
									<!-- Add more class options as needed -->
								</select>
								<label for="className" class="form-label">Boarder OR Day Scholar</label>
							</div>
						</div>
					</div>
				</div>
				<!-- Second Section -->
				<div class="mb-4">
					<div class="row mb-2">
						<div class="col">
							<hr>
						</div>
						<div class="col">
							<h6 class="text-center">Parent Information</h6>
						</div>
						<div class="col">
							<hr>
						</div>
					</div>
					<div class="row mb-3">
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" name="fatherName" class="form-control form-control-sm" id="fatherName">
								<label for="dob" class="form-label">Father's Name</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" name="fatherPhone" class="form-control form-control-sm phoneNumber" id="fatherPhone">
								<label for="dob" class="form-label">Father's Phone</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" name="fatherOccupation" class="form-control form-control-sm" id="fatherOccupation">
								<label for="dob" class="form-label">Father's Occupation</label>
							</div>
						</div>
					</div>
					<div class="row mb-3">
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" class="form-control" name="motherName" id="motherName" required>
								<label for="motherName" class="form-label">Mother's Name</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<input type="tel" class="form-control phoneNumber" name="motherPhone" id="motherPhone" required>
								<label for="motherPhone" class="form-label">Mother's Phone</label>
							</div>
						</div>
						<div class="col">
							<div class="form-floating mb-2">
								<input type="text" class="form-control" name="motherOccupation" id="motherOccupation" required>
								<label for="motherOccupation" class="form-label">Mother's Occupation</label>
							</div>
						</div>
					</div>
				</div>
				<input type="hidden" name="page" value="admin">
				<input type="hidden" name="action" value="forms">
				<input type="hidden" name="execute" value="addStudent">
				<button type="submit" class="btn btn-primary">Register Pupil</button>
			</form>
			<?php
		}

		if ($_POST['action'] == "fetchTeacherForm") {
			?>
			<h2 class="mt-5">Teachers Registration Form</h2>
			<form id="teacherAddForm">
				<div class="row mb-3">
					<div class="col">
						<label for="teacherName" class="form-label">Teacher's Name</label>
						<input type="text" class="form-control" id="teacherName" required>
					</div>
					<div class="col">
						<label for="teacherPhone" class="form-label">Teacher's Phone</label>
						<input type="tel" class="form-control" id="teacherPhone" required>
					</div>
				</div>
				<div class="mb-3">
					<label for="subjectsTaught" class="form-label">Subjects Taught</label>
					<input type="text" class="form-control" id="subjectsTaught" required>
				</div>
				<div class="mb-3">
					<label for="streams" class="form-label">Streams</label>
					<input type="text" class="form-control" id="streams" required>
				</div>
				<button type="submit" class="btn btn-primary">Register Teacher</button>
			</form>
			<?php
		}

		if ($_POST["action"] == "fetchForms") {
			?>
			<div class="row mb-2 mt-2">
				<div class="col">
					<button type="button" class="btn btn-sm btn-outline-success" id="addClass">
						<i class="fa fa-list-ol"></i>
						Add Class
					</button>
				</div>
				<div class="col">
					<button type="button" class="btn btn-sm btn-outline-info" id="addSubject">
						<i class="fa fa-graduation-cap"></i>
						Add Subject
					</button>
				</div>
			</div>
			<?php
		}

		if ($_POST['action'] == "classForm") {
			?>
			<form id="classesForm">
				<div class="row mt-2">
					<div class="col-6 mb-2">
						<h4 class="title fw-bold">Add Class</h4>
					</div>
				</div>
				<div class="row mt-2">
					<div class="col-6 mb-2 mt-2">
						<div class="form-floating">
							<input type="text" name="className" id="className" class="form-control form-control-sm">
							<label for="className">Class Name</label>
						</div>
					</div>

					<div class="col-3 mb-2 mt-2">
						<div class="form-floating">
							<input type="number" name="noOfStreams" id="noOfStreams" class="form-control form-control-sm">
							<label for="className">Number of streams</label>
						</div>
					</div>

					<div class="col-3 mb-2 mt-2">
						<div class="row">
							<button type="submit" class="btn btn-circle btn-outline-info">
								<i class="fa-paper-plane-o"></i>
								Add Class
							</button>
						</div>
					</div>
				</div>
			</form>
			<?php
		}

		if($_POST['action'] == "excelPupilForm") {
			?>
			<h2>
				Pupils Registration Upload
			</h2>
			<form enctype="multipart/form-data" id="pupilUploadForm">
				<div class="mb-4">
					<div class="row mb-2">
						<div class="col">
							<hr>
						</div>
						<div class="col">
							<h6 class="text-center">Student Upload Form</h6>
						</div>
						<div class="col">
							<hr>
						</div>
					</div>
					<div class="row mb-2">
						<div class="col-3">
							<h6 class="text-center">
								Upload Here : 
							</h6>
						</div>
						<div class="col-7">
							<input type="file" name="students" id="excel-file" class="form-control" />
						</div>
						<input type="hidden" name="page" value="admin" />
						<input type="hidden" name="action" value="forms" />
						<input type="hidden" name="execute" value="addStudentSpreadsheet" />
						<div class="col-2">
							<button type="submit" class="btn btn-outline-success btn-sm">
								Upload
							</button>
						</div>
					</div>
				</div>
			</form>
			<?php
		}

		if ($_POST['action'] == "forms") {

			if ($_POST['execute'] == "addStudentSpreadsheet") {
				
				$allowed = ['xls', 'xlsx', 'Xlsx', 'csv'];
				$temp_name = $_FILES['students']['tmp_name'];
				$filename = $_FILES['students']['name'];

				$check = explode(".", $filename);
				$file_ext = end($check);
	
				if (in_array($file_ext, $allowed)) {
					$objExcel = \PhpOffice\PhpSpreadsheet\IOFactory::load($temp_name);
					
					foreach ($objExcel->getWorksheetIterator() as $worksheet) {
						$highestrow = $worksheet->getHighestRow();

						$fnameTitle = $worksheet->getCell('B4')->getCalculatedValue();
						$lnameTitle = $worksheet->getCell('D4')->getCalculatedValue();
						$fathersTitle = $worksheet->getCell('H3')->getCalculatedValue();
						$mothersTitle = $worksheet->getCell('K3')->getCalculatedValue();

						$today = date('Y-m-d');

						if ($fnameTitle == 'First Name' && $fathersTitle == 'Father\'s Data' && $mothersTitle == 'Mother\'s Data') {
							for ($row = 5; $row <= $highestrow; $row++) {
								// Pupil details

								$fname = $worksheet->getCell("B".$row)->getCalculatedValue();
								$mname = $worksheet->getCell("C".$row)->getCalculatedValue();
								$lname = $worksheet->getCell("D".$row)->getCalculatedValue();
								$dob = $worksheet->getCell("E".$row)->getValue();
								$class = $worksheet->getCell("F".$row)->getCalculatedValue();
								$studentOrientation = strtoupper($worksheet->getCell("G".$row)->getCalculatedValue());

								if($studentOrientation == "D" || $studentOrientation == "DAY"){
									$type = "DAY";
								} else {
									$type = "BOARDER";
								}

								// Check DOB if IS NUMERICAL
								if (is_numeric($dob)) {
									// Convert the Excel serial number to a DateTime object
									$dobDateTime = Date::excelToDateTimeObject($dob);

									// Format the DateTime object to a string in the desired format
									$dob = $dobDateTime->format('Y-m-d'); // Adjust the format as needed

								}

								// Parents Details

								$fatherName = $worksheet->getCell("H".$row)->getCalculatedValue();
								$fPhone = $worksheet->getCell("I".$row)->getCalculatedValue();
								$fOccupation = $worksheet->getCell("J".$row)->getCalculatedValue();

								$motherName = $worksheet->getCell("K".$row)->getCalculatedValue();
								$mPhone = $worksheet->getCell("L".$row)->getCalculatedValue();
								$mOccupation = $worksheet->getCell("M".$row)->getCalculatedValue();

								// If empty replace space with "-"
								$fatherName = empty($fatherName) ? "-" : $fatherName;
								$fPhone = empty($fPhone) ? "-" : $fPhone; // If you also want to set a default for phone numbers
								$fOccupation = empty($fOccupation) ? "-" : $fOccupation;

								$motherName = empty($motherName) ? "-" : $motherName;
								$mPhone = empty($mPhone) ? "-" : $mPhone; // If you also want to set a default for phone numbers
								$mOccupation = empty($mOccupation) ? "-" : $mOccupation;

								$class = ($class == "1") ? "GRADE 1" : $class;
								$class = ($class == "2") ? "GRADE 2" : $class;
								$class = ($class == "3") ? "GRADE 3" : $class;
								$class = ($class == "4") ? "GRADE 4" : $class;
								$class = ($class == "5") ? "GRADE 5" : $class;
								$class = ($class == "6") ? "GRADE 6" : $class;
								$class = ($class == "7") ? "GRADE 7" : $class;
								$class = ($class == "B") ? "BABY" : $class;
								$class = ($class == "Mid") ? "MIDDLE" : $class;
								$class = ($class == "Pre") ? "PRE-UNIT" : $class;

								$classQuery = $conn->query("SELECT * FROM `class` WHERE `className`='$class'");
								$classRows = $classQuery->num_rows;

								if($classRows > 1) {
									// Fetch class ID
									$fetchID = $classQuery->fetch_assoc();
									$classID = $fetchID['classID'];
								} else {
									// insert class and get Class ID
									$insertClass = $conn->query("INSERT INTO `class` (`className`) VALUES ('$class')");
									$classID = $conn->insert_id;
								}

								// Check if Student is in the database tables
								$query = $conn->query("SELECT * FROM `student` WHERE `firstName`='$fname' AND `lastName`='$lname'");
								$rows = $query->num_rows;

								if ($rows < 1) {
									$query = $conn->query("INSERT INTO `student` (`firstName`, `middleName`, `lastName`, `DateOfBirth`, `classID`, `registerDate`, `status`) 
																	VALUES ('$fname', '$mname', '$lname', '$dob', '$classID', '$today', 'active')");
									$studentID = $conn->insert_id;

									// Create password
									$symbols = "*!@$%^&*";
									$symbol = $symbols[rand(0, strlen($symbols) - 1)];

									$primaryPhone = !empty($fPhone) ? $fPhone : $mPhone;

									$lastPhone = substr($primaryPhone, -2);

									$salt = "Elimika";
									$saltEnd = "Digital";

									$studentPass = $lname.$symbol;
									$studentHashPass = md5($studentPass);
									$studentHashPass = $salt.$studentHashPass.$saltEnd;
									$studentHashPass = password_hash($studentHashPass, PASSWORD_BCRYPT);

									// Check if parent exists
									$query = $conn->query("SELECT * FROM `parents` WHERE `fatherNames`='$fatherName' OR `motherNames`='$motherName'");
									$rows = $query->num_rows;

									if ($rows < 1) {
										//insert parents
										$query = $conn->query("INSERT INTO `parents` (`studentIDs`, `fatherNames`, `fatherPhone`, `fatherOccupation`, `motherNames`, `motherPhone`, `motherOccupation`) 
																			VALUES ('$studentID', '$fatherName', '$fPhone', '$fOccupation', '$motherName', '$mPhone', '$mOccupation')");
										$parentID = $conn->insert_id;

										// Create password
										$symbols = "^!@*!";
										$symbol = $symbols[rand(0, strlen($symbols) - 1)];

										$parentPass = $lname.$lastPhone.$symbol;
										$parentHashPass = md5($parentPass);
										$parentHashPass = $salt.$parentHashPass.$saltEnd;
										$parentHashPass = password_hash($parentHashPass, PASSWORD_BCRYPT);
									} else {
										// Fetch Parents student ID
										$fetch = $query->fetch_assoc();
										$studentIDs = $fetch['studentIDs'];
										$parentID = $fetch['id'];
										$studentIDs = $studentIDs.", ".$studentID;

										// update parent details
										$query = $conn->query("UPDATE `parents` SET `studentIDs`='$studentIDs' WHERE `id`='$parentID'");
									}

									// Check if parentID already exists
									$parentCheckQuery = $conn->query("SELECT * FROM `login_credentials` WHERE `userID`='$parentID'");
									$parentExists = $parentCheckQuery->num_rows > 0;

									// Prepare the SQL for inserting or updating login credentials
									$sqlInserts = [];
									$sqlUpdates = [];

									if ($studentID) {
										$sqlInserts[] = "('$studentID', 'student', '$studentHashPass')";
									}

									if ($parentHashPass) {
										if (!$parentExists) {
											$sqlInserts[] = "('$parentID', 'parent', '$parentHashPass')";
										}
									}

									// Execute inserts if there are any
									if (!empty($sqlInserts)) {
										$sqlInsert = "INSERT INTO `login_credentials` (`userID`, `usertype`, `password`) VALUES " . implode(", ", $sqlInserts);
										if ($conn->query($sqlInsert) === TRUE) {
											echo "New login credentials inserted successfully<br>";
										} else {
											echo "Error: " . $sqlInsert . "<br>" . $conn->error;
										}
									}

									// Execute updates if there are any
									foreach ($sqlUpdates as $sqlUpdate) {
										if ($conn->query($sqlUpdate) === TRUE) {
											echo "Login credentials updated successfully<br>";
										} else {
											echo "Error: " . $sqlUpdate . "<br>" . $conn->error;
										}
									}
									
									if ($query = $conn->query($sqlInsert)) {										

										// insert student Orientation
										$today = date('m-Y');

										$orientation = $conn->query("INSERT INTO `studenttype` (`studentID`, `dateTime`, `typeStatus`, `status`) VALUES ('$studentID','$today','$type','active') ");

										

										$fns = substr($fname, 0, 2);
										$studentUserName = $fns.$lname;

										$message = 'Student Login\nUsername: '.$studentUserName.'\n';
										$message .= 'Password: '.$studentPass.'\n\n';
										

										if (substr($primaryPhone, 0, 1) === '0') {
											// Replace the first '0' with '255'
											$primaryPhone = '255' . substr($primaryPhone, 1);
										} else if(substr($primaryPhone, 0,3) !== '255' || substr($primaryPhone, 0, 1) === '0') {
											// Start with "255" then "$phone"
											$primaryPhone = '255'.$primaryPhone;
										}
										
										if($parentHashPass) {
											$message .= 'Parents Login\n';
											$message .= 'Username: '.$primaryPhone.'\n';
											$message .= 'Password: '.$parentPass;
										}

										// Send login credentials text
										$curl = curl_init();

										curl_setopt_array($curl, array(
										CURLOPT_URL => 'https://messaging-service.co.tz/api/sms/v1/text/single',
										CURLOPT_RETURNTRANSFER => true,
										CURLOPT_ENCODING => '',
										CURLOPT_MAXREDIRS => 10,
										CURLOPT_TIMEOUT => 0,
										CURLOPT_FOLLOWLOCATION => true,
										CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
										CURLOPT_CUSTOMREQUEST => 'POST',
										CURLOPT_POSTFIELDS =>'{"from":"Elimika", "to":"'.$primaryPhone.'",  "text": "'.$message.'", "reference": "aswqetgcv"}',
										CURLOPT_HTTPHEADER => array(
											'Authorization: Basic YmVyZWdlOmp5enQ5OHFxbnpkOWdIVg==',
											'Content-Type: application/json',
											'Accept: application/json'
										),
										));

										$response = curl_exec($curl);

										curl_close($curl);
									}

								} else {
									echo $fname." ".$lname." Exists.";
								}
							}
						} else {
							echo "<span class='fw-bold text text-danger'>";
							echo "Please use prefered template.";
							echo "</span>";
						}

					}

				} else {
					echo "<span class=\"text text-danger fw-bold\"><u>Please upload Spreadsheet file</u>!</span>";
				}
			}

			if($_POST['execute'] == "addStudent"){
				
				$type = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['studentType']))));

				$fname = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['fname']))));
				$mname = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['mname']))));
				$lname = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['lname']))));
				$dob = stripslashes(strip_tags($conn->real_escape_string($_POST['dob'])));
				$class = stripslashes(strip_tags($conn->real_escape_string($_POST['className'])));
				$fatherName = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['fatherName']))));
				$fPhone = stripslashes(strip_tags($conn->real_escape_string($_POST['fatherPhone'])));
				$fatherOccupation = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['fatherOccupation']))));
				$motherName = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['motherName']))));
				$mPhone = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['motherPhone']))));
				$motherOccupation = strtoupper(stripslashes(strip_tags($conn->real_escape_string($_POST['motherOccupation']))));

				// Change type
				if($type == "BOARDING"){
					$type = "BOARDER";
				} else {
					$type = "DAY";
				}

				// echo $_SERVER["REQUEST_METHOD"];

				$date = date('Y-m-d');

				// check if student exits
				$query = $conn->query("SELECT * FROM `student` WHERE `firstname`='$fname' AND `lastname`='$lname'");
				$rows = $query->num_rows;

				if ($rows < 1) {
					$symbols = "*!@$%^&*";
					$symbol = $symbols[rand(0, strlen($symbols) - 1)];					

					$primaryPhone = !empty($fPhone) ? $fPhone : $mPhone;

					if (empty($fPhone)) {
						$fphone = "-";
					}
					
					if (empty($mPhone)) {
						$mPhone = "-";
					}

					$lastPhone = substr($primaryPhone, -2);

					$salt = "Elimika";
					$saltEnd = "Digital";

					$studentInitialPass = $lname.$symbol;
					$studentHashPass = md5($studentInitialPass);
					$studentHashPass = $salt.$studentHashPass.$saltEnd;
					$studentHashPass = password_hash($studentHashPass, PASSWORD_BCRYPT);

					$symbols = "^!@*!";
					$symbol = $symbols[rand(0, strlen($symbols) - 1)];

					$parentInitialPass = $lname.$lastPhone.$symbol;
					$parentHashPass = md5($parentInitialPass);
					$parentHashPass = $salt.$parentHashPass.$saltEnd;
					$parentHashPass = password_hash($parentHashPass, PASSWORD_BCRYPT);

					// insert student into database table
					$query = $conn->query("INSERT INTO `student` (`firstName`, `middleName`, `lastName`, `DateOfBirth`, `classID`, `registerDate`, `status`)
																VALUES ('$fname', '$mname', '$lname', '$dob', '$class', '$date', 'active')");
					
					$studentID = $conn->insert_id;
					// echo "<span class=\"text text-success\">".$fname." ".$lname." Inserted </span>";

					// Check if parent exists
					$query = $conn->query("SELECT * FROM `parents` WHERE `fatherNames`='$fatherName' OR `motherNames`='$motherName'");
					$rows = $query->num_rows;

					if ($rows < 1) {
						//insert parents
						$query = $conn->query("INSERT INTO `parents` (`studentIDs`, `fatherNames`, `fatherPhone`, `fatherOccupation`, `motherNames`, `motherPhone`, `motherOccupation`) 
															VALUES ('$studentID', '$fatherName', '$fPhone', '$fatherOccupation', '$motherName', '$mPhone', '$motherOccupation')");
						$parentID = $conn->insert_id;
					} else {
						// Fetch Parents student ID
						$fetch = $query->fetch_assoc();
						$studentIDs = $fetch['studentIDs'];
						$parentID = $fetch['id'];
						$studentIDs = $studentIDs.", ".$studentID;

						// update parent details
						$query = $conn->query("UPDATE `parents` SET `studentIDs`='$studentIDs' WHERE `id`='$parentID'");
					}

					// insert password

					// create usernames
					
					// student usernames
					$fns = $lastPhone = substr($fname, 0, 2);
					$studentUserName = $fns.$lname;

					// Parent usernames
					$parentUsername = $fPhone;

					// insert login credentials 
					
					$sql = "INSERT INTO `login_credentials` (`userID`, `usertype`, `password`) VALUES ";

					if ($studentID) {
						// insert student
						$sql .= "('$studentID', 'student', '$studentHashPass')";

					}

					if($parentID) {
						// check if parent ID exists
						$query = $conn->query("SELECT * FROM `login_credentials` WHERE `userID`='$parentID' AND `userType`='parent'");

						$rows = $query->num_rows;

						if ($rows < 1){
							$sql .= ", ('$parentID', 'parent', '$parentHashPass')";
						} else {
							echo "Parent already exists";
						}
					}

					// execute insert query
					if ($loginQuery = $conn->query($sql)) {

						// insert student Orientation
						$today = date('m-Y');

						$orientation = $conn->query("INSERT INTO `studenttype` (`studentID`, `dateTime`, `typeStatus`, `status`) VALUES ('$studentID','$today','$type','active') ");

						// Send Message

						$message = 'Student Login\nUsername: '.$studentUserName.'\n';
						$message .= 'Password: '.$studentInitialPass.'\n\n';
						$message .= 'Parents Login\n';
						$message .= 'Username: '.$primaryPhone.'\n';
						$message .= 'Password: '.$parentInitialPass;

						if (substr($primaryPhone, 0, 1) === '0') {
							// Replace the first '0' with '255'
							$primaryPhone = '255' . substr($primaryPhone, 1);
						} else if(substr($primaryPhone, 0,3) === '255') {
							$primaryPhone = $primaryPhone;
						} else {
							// Start with "255" then "$phone"
							$primaryPhone = '255'.$primaryPhone;
						}

						// Send login credentials text
						$curl = curl_init();

						curl_setopt_array($curl, array(
						CURLOPT_URL => 'https://messaging-service.co.tz/api/sms/v1/text/single',
						CURLOPT_RETURNTRANSFER => true,
						CURLOPT_ENCODING => '',
						CURLOPT_MAXREDIRS => 10,
						CURLOPT_TIMEOUT => 0,
						CURLOPT_FOLLOWLOCATION => true,
						CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
						CURLOPT_CUSTOMREQUEST => 'POST',
						CURLOPT_POSTFIELDS =>'{"from":"Elimika", "to":"'.$primaryPhone.'",  "text": "'.$message.'", "reference": "aswqetgcv"}',
						CURLOPT_HTTPHEADER => array(
							'Authorization: Basic YmVyZWdlOmp5enQ5OHFxbnpkOWdIVg==',
							'Content-Type: application/json',
							'Accept: application/json'
						),
						));

						$response = curl_exec($curl);

						curl_close($curl);
					}

				} else {
					echo "<span class=\"text text-warning fw-bold\">";
					echo $fname." ".$lname;
					echo " Exists";
				 	echo "</span>";
				}
			}
		}
	}
}


?>