"; print_r($postdata); echo "
";
die;*/
$headers = apache_request_headers();

/*foreach ($headers as $header => $value) {
        if($header=="ALERTSSYSTEMKEY")
        {
                $httpHeader=$value;
        }
}
if($httpHeader!="MAKEalertsSYSTEM1246")
{
        die();
}*/

if ($_POST) {
	$postdata = $_POST;
}else{
	$_POST = json_decode(file_get_contents('php://input'), true);
	$postdata = $_POST;
}

function generate_unique_username_new($sys_username, $lastna, $user_Id){
    $firstname      = $sys_username;//data coming from user
    $lastname       = $lastna;//data coming from user
    $new_username   = $firstname.$lastname;


    global $mysqlimatrix62;
    //$result = $mysqlimatrix62->query("SELECT id FROM users WHERE sys_username='$userName'") or die($mysqli->error());

    $name = "%$firstname%";
	$stmt1 = $mysqlimatrix62->prepare("SELECT id FROM users WHERE sys_username LIKE ? ");
	$stmt1->bind_param("s", $name);
	$stmt1->execute();
	$stmt1->store_result();
	$stmt1->bind_result($id);
	$num_returns = $stmt1->num_rows;
	$stmt1->close();

    // We know username exists if the rows returned are more than 0
    if ( $num_returns > 0 ) {
        $new_username = $sys_username . $lastname .$num_returns;
    }

    return $new_username;
}


if($postdata)
{


	$data = array();
	
	if(empty($postdata['user_Id']) || empty($postdata['group_Id']) || empty($postdata['sys_username']) || empty($postdata['Email']) || empty($postdata['MobileNo']) || empty($postdata['SetAlertValue']))
	{
		
		$arr=array (
				'status' 		     => 0,
				'message'		     => "Feilds are Empty. Kindly Check.",
				);
		array_push($data,$arr);
				
	}
	else
	{
		$user_Id = addslashes($postdata['user_Id']);
		$group_Id = addslashes($postdata['group_Id']);
		$sys_username = addslashes($postdata['sys_username']);
		$email_id = addslashes($postdata['Email']);
		$mobile_No = addslashes($postdata['MobileNo']);
		$SetAlertType = addslashes($postdata['SetAlertValue']);
		$SetGeoFanceValue = addslashes($postdata['SetGeoFanceValue']);
		$SetSpeedValue = addslashes($postdata['SetSpeedValue']);
		$SetTempFrom = addslashes($postdata['SetTempFromValue']);
		$SetTempTo = addslashes($postdata['SetTempToValue']);
		$IdlingHrs = addslashes($postdata['SetIdlingValue']);
		$alertID= addslashes($postdata['id']);
		//$VehicleNo = addslashes($postdata['setMultipleOption2']);

		if ($postdata['setMultipleOption2']=="All") {
		  //$sys_service_id = 'All';
		  $VehicleNo = 'All';
		}else{
		  $sys_service_id = '';
		  $VehicleNo = '';
		  $setMultipleOption2 = explode(',',$postdata['setMultipleOption2']);
		  foreach ($setMultipleOption2 as $key => $value) {
		    $array  = explode('##',$value);
		    $sys_service_id.= $array[0].',';
		    $VehicleNo.= $array[1].',';
		  }
		  $VehicleNo = rtrim($sys_service_id, ',');
		  //$VehicleNo = rtrim($VehicleNo, ',');
		}

		$alert_user_id = $user_Id;
		$alert_group_id = $group_Id;
		$alert_sys_username = $sys_username;

		//echo 1;die;

		if($VehicleNo!='All')
		{
			/*//echo $sys_username;
			$subuserfullname = generate_unique_username_new($sys_username, '_foralert', $user_Id);
			$defpassword = "654321";

			$success_insert = $mysqlimatrix62->prepare("INSERT INTO matrix.users (fullname, sys_username, sys_password, mobile_number, email_address, sys_active,sys_parent_user) VALUES (?,?,?,?,?,?,?)");
			$success_insert->bind_param('sssssis',$subuserfullname,$subuserfullname,$defpassword,$mobile_No,$email_id,$def_status1,$user_Id);
			$success_insert->execute();
			$success_insert->close();

			$stmt1 = $mysqlimatrix62->prepare("SELECT id FROM matrix.users WHERE sys_username = ? ");
			$stmt1->bind_param("s", $subuserfullname);
			$stmt1->execute();
			$stmt1->store_result();
			$stmt1->bind_result($subuserid);
			$usercount = $stmt1->num_rows;*/

			/*if($usercount>0)
			{
				while ($stmt1->fetch()) {
					$subuser_id = $subuserid;

					$success_insert1 = $mysqlimatrix62->prepare("INSERT INTO matrix.group (name, sys_user_id, sys_parent_group_id, icon, active, sys_modified, sys_created) VALUES (?,?,?,?,?,?,?)");
					$success_insert1->bind_param('ssssiss',$subuserfullname,$subuser_id,$group_Id,$def_status,$def_status1,$currentdatetime,$currentdatetime);
					$success_insert1->execute();
					//$subgroup_id = $success_insert1->insert_id();
					$success_insert1->close();

					$stmt11 = $mysqlimatrix62->prepare("SELECT id FROM matrix.group WHERE sys_user_id = ? and sys_parent_group_id = ? ");
					$stmt11->bind_param("ss", $subuser_id,$group_Id);
					$stmt11->execute();
					$stmt11->store_result();
					$stmt11->bind_result($subgroupid);
					$groupcount = $stmt11->num_rows;


					if($groupcount>0)
					{
						while ($stmt11->fetch()) {
							$subgroup_id = $subgroupid;
							//echo $subgroup_id.'--';
							$success_insert2 = $mysqlimatrix62->prepare("INSERT INTO matrix.group_users (sys_user_id, sys_group_id, active, sys_modified) VALUES (?,?,?,?)");
							$success_insert2->bind_param('ssis',$subuser_id,$subgroup_id,$def_status1,$currentdatetime);
							$success_insert2->execute();
							$success_insert2->close();*/

							/*$stmtdeact = $mysqlimatrix62->prepare("UPDATE matrix.group_services
				                SET active = ?
				                WHERE 
				                sys_service_id in (".$VehicleNo.") and sys_group_id = ? ");
				            $stmtdeact->bind_param("is", $def_status,$group_Id);
				            $result = $stmtdeact->execute();
				            $stmtdeact->close();
*/
							$veharray = (explode(",",$VehicleNo));

							if(count($veharray)>0)
							{
								foreach ($veharray as $key => $sid) {

									$stmt_gserv = $mysqlimatrix62->prepare("SELECT sys_service_id FROM matrix.group_services WHERE sys_service_id = ? AND sys_group_id = ? ");
									$stmt_gserv->bind_param("ss", $sid,$group_Id);
									$stmt_gserv->execute();
									$stmt_gserv->store_result();
									$stmt_gserv->bind_result($id);
									$num_groupserv = $stmt_gserv->num_rows;
									$stmt_gserv->close();

								    if ($num_groupserv == 0) {

								       $insert_services = $mysqlimatrix62->prepare("INSERT INTO matrix.group_services (sys_service_id, sys_group_id, active, sys_modified, sys_added_date) VALUES (?,?,?,?,?)");
										$insert_services->bind_param('ssiss',$sid,$group_Id,$def_status1,$currentdatetime,$currentdatetime);
										$insert_services->execute();
										$insert_services->close();
								    }
								    else
								    {
								    	$stmt = $mysqlimatrix62->prepare("UPDATE matrix.group_services
							                SET active = ?
							                WHERE 
							                sys_service_id = ? and sys_group_id = ? ");
							            $stmt->bind_param("iss", $def_status1,$sid,$group_Id);
							            $result = $stmt->execute();
							            $stmt->close();
								    }

									
								}
							}
						/*}
					}
					$stmt11->close();
				}
			}
			$stmt1->close();
			
			$alert_user_id = $subuser_id;
			$alert_group_id = $subgroup_id;
			$alert_sys_username = $subuserfullname;
			//die;*/
		}

		//echo $alert_sys_username;die;

		//INSERT INTO `alert_userwise` (`id`, `sys_user_id`, `sys_group_id`, `email`, `number`, `poi_idlist`, `overspeed`, `overspeed_geofence`, `nonjourney`, `ac`, `mainpower`, `poi`, `other`, `lastupdate`, `overspeed_value`, `limit_speed`, `nonjourney_hour`, `status`, `is_controlroom`, `alert_type_2`, `diffinminute`, `geofence_check`) VALUES (64, 79408, 51362, 'PAPERS@JAIPURPAPERS.COM,gtractracking@gmail.com', '9828411770,9829015138', NULL, b'1', b'0', b'0', b'0', b'0', b'0', b'0', '2020-12-23 11:54:11', 100, 0, 0, 1, 0, 0, 30, 0);

		$overspeed = 0;
		$overspeed_geofence = 0;
		$nonjourney = 0;
		$ac = 0;
		$mainpower = 0;
		$gps_notworking = 0;
		$poi = 0;
		$other = 0;
		$panic = 0;
		$overspeed_value = 0;
		$limit_speed = 0;
		$nonjourney_hour = 0;
		$geofence_check = 0;
		$temperature = 0;
		$ignition = 0;
		$poi_idlist = '0';

		$stmtcheck = $mysqlimatrix62->prepare("SELECT id,poi_idlist, overspeed, overspeed_geofence, nonjourney, gps_notworking, ac, mainpower, poi, other, lastupdate, overspeed_value, limit_speed, nonjourney_hour, geofence_check, panic, status FROM matrix.alert_userwise WHERE sys_user_id = ? AND sys_group_id = ? ");
		$stmtcheck->bind_param("ss", $alert_user_id,$alert_group_id);
		$stmtcheck->execute();
		$stmtcheck->store_result();
		$stmtcheck->bind_result($chk_id, $chk_poi_idlist, $chk_overspeed, $chk_overspeed_geofence, $chk_nonjourney, $chk_ac, $chk_mainpower, $chk_poi, $chk_other, $chk_lastupdate, $chk_overspeed_value, $chk_limit_speed, $chk_nonjourney_hour, $chk_gps_notworking, $chk_geofence_check, $chk_panic, $chk_status);
		  $num_alertsuserwise = $stmtcheck->num_rows;
		if ($num_alertsuserwise > 0) {
			while($stmtcheck->fetch()){
				$alertid = $chk_id;
				$overspeed = $chk_overspeed;
				$overspeed_geofence = $chk_overspeed_geofence;
				$nonjourney = $chk_nonjourney;
				$ac = $chk_ac;
				$mainpower = $chk_mainpower;
				$gps_notworking = $chk_gps_notworking;
				$gps_disconnect = 0;
				$poi = $chk_poi;
				$other = $chk_other;
				$panic = $chk_panic;
				$overspeed_value = $chk_overspeed_value;
				$limit_speed = $chk_limit_speed;
				$nonjourney_hour = $chk_nonjourney_hour;
				$geofence_check = $chk_geofence_check;
				$poi_idlist = $chk_poi_idlist;
			}
		}
		$stmtcheck->close();

		$alertuser = 0;
		$userpermission = 0;
		$updatealertusers = 0;
		$sys_permission_id1 = 0;

		if($SetAlertType=='OverSpeed') {
			$alertuser = 1;
			$overspeed = 1;
			$overspeed_value = $SetSpeedValue;

		} else if($SetAlertType=='Main Power Disconnect') {
			$alertuser = 1;
			$mainpower = 1;

		} else if($SetAlertType=='GeoFence') {
			$alertuser = 1;
			$geofence_check = 1;
			$poi_idlist = $SetGeoFanceValue;
		} else if($SetAlertType=='AC') {
			$userpermission = 1;
			//$ac = 1;
			$sys_permission_id = 179;
			$sys_permission_id1 = 185;
		} else if($SetAlertType=='GPS Disconnect') {
			$alertuser = 1;
			$gps_notworking = 1;
		} else if($SetAlertType=='Temperature') {
			$temperature = 1;
		} else if($SetAlertType=='Panic') {
			$alertuser = 1;
			$panic = 1;
		} else if($SetAlertType=='Idling') {
			$alertuser = 1;
			$other = 1;
		} else if($SetAlertType=='Ignition') {
			$userpermission = 1;
			//$ignition = 1;
			$sys_permission_id = 181;
		} else if($SetAlertType=='Ignition Night') {
			$userpermission = 1;
			//$ignition = 1;
			$sys_permission_id = 183;
		}

		if ($num_alertsuserwise > 0) {
		    $alertuser = 0;
	        $updatealertusers = 1;
		}

		//echo $updatealertusers.' - '.$alertuser.' - '.$userpermission.' - '.$alertid;die;
		$querytype = 'Updated';

		if($updatealertusers == 1)
		{
			//echo 1;die;

			//$email_id = addslashes($postdata['Email']);
		//$mobile_No = addslashes($postdata['MobileNo']);

//email,number
			$stmt = $mysqlimatrix62->prepare("UPDATE matrix.alert_userwise
                SET status = ?,
                nonjourney = ?,
                overspeed = ?,
                mainpower = ?,
                gps_notworking = ?,
                geofence_check = ?,
                overspeed_value = ?,
                poi_idlist = ?,
                other = ?,
                poi = ?,
                panic = ?,
                overspeed_geofence = ?,
                lastupdate = ?,
				email = ?,
				number = ?
                WHERE 
                id = ? ");
            $stmt->bind_param("iiiiiissiiiisiss", $def_status1,$nonjourney,$overspeed,$mainpower,$gps_notworking,$geofence_check,$overspeed_value,$poi_idlist,$other,$poi,$panic,$overspeed_geofence,$currentdatetime,$alertid,$email_id,$mobile_No);
            $result = $stmt->execute();
            $stmt->close();

            $querytype = 'Updated';

			

//INSERT INTO `alert_managements` (`id`, `user_Id`, `Parent_user_Id`, `group_Id`, `sys_username`, `email_id`, `mobile_No`, `SetAlertType`, `SetGeoFanceValue`, `SetSpeedValue`, `SetTempFrom`, `SetTempTo`, `checkSms`, `IdlingHrs`, `sys_service_id`, `VehicleNo`, `status`, `sms`, `created_at`, `updated_at`) VALUES (33, 4535, 4535, 4561, 'srigoodscarriers', 'jainsanmati@yahoo.com', '9413314716', 'Panic', '', '', '', '', NULL, 0, NULL, 'All', '0', '1', '2023-05-05 07:16:33', '2023-05-20 11:46:30');

$stmt = $mysqli235->prepare("UPDATE `alert_managements`
                SET email_id = ?, mobile_No = ?
                WHERE id = ?");

// Check if preparation was successful
if ($stmt === false) {
    die('Prepare failed: ' . $mysqli235->error);
}

// Bind parameters
$stmt->bind_param("ssi", $email_id, $mobile_No, $alertID);

// Execute the statement
$result = $stmt->execute();

// Check if execution was successful
if ($result === false) {
    die('Execute failed: ' . $stmt->error);
}

// Close the statement
$stmt->close();

// Indicate the type of query
  $querytype = 'Updated';


			//

		} else if($alertuser == 1) {
			//echo 2;die;

			//echo "INSERT INTO matrix.alert_userwise (sys_user_id, sys_group_id, email, number, poi_idlist, overspeed, overspeed_geofence, nonjourney, ac, mainpower, poi, other, lastupdate, overspeed_value, limit_speed, nonjourney_hour, geofence_check, panic, status) VALUES ($alert_user_id,$alert_group_id,$email_id,$mobile_No,$poi_idlist,$overspeed,$overspeed_geofence,$nonjourney,$ac,$mainpower,$poi,$other,$currentdatetime,$overspeed_value,$limit_speed,$nonjourney_hour,$geofence_check,$panic,$def_status1)";die;

			$std = $mysqlimatrix62->prepare("INSERT INTO matrix.alert_userwise (sys_user_id, sys_group_id, email, number, poi_idlist, overspeed, overspeed_geofence, nonjourney, ac, mainpower, gps_notworking, poi, other, lastupdate, overspeed_value, limit_speed, nonjourney_hour, geofence_check, panic, status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
			$std->bind_param('iissiiiiiiiiisiiiiii',$alert_user_id,$alert_group_id,$email_id,$mobile_No,$poi_idlist,$overspeed,$overspeed_geofence,$nonjourney,$ac,$mainpower,$gps_notworking,$poi,$other,$currentdatetime,$overspeed_value,$limit_speed,$nonjourney_hour,$geofence_check,$panic,$def_status1);
			$std->execute();
			$std->close();

            $querytype = 'Inserted';

			//echo 33;die;
			//die;
		}

		if($userpermission == 1) {
			//echo 3;die;
			$stmt1 = $mysqlimatrix62->prepare("SELECT sys_user_id FROM matrix.users_permissions WHERE sys_user_id = ? AND sys_permission_id = ? ");
			$stmt1->bind_param("ss", $alert_user_id,$sys_permission_id);
			$stmt1->execute();
			$stmt1->store_result();
			$stmt1->bind_result($id);
			$num_permissions = $stmt1->num_rows;
			$stmt1->close();

			$querytype = 'Updated';

		    if ($num_permissions == 0) {
		        $std = $mysqlimatrix62->prepare("INSERT INTO matrix.users_permissions (sys_user_id, sys_permission_id) VALUES (?,?)");
				$std->bind_param('ss',$alert_user_id,$sys_permission_id);
				$std->execute();
				$std->close();

				$querytype = 'Inserted';
		    }

		    if($sys_permission_id1!=0 && $sys_permission_id1!='')
		    {
		    	$stmt1 = $mysqlimatrix62->prepare("SELECT sys_user_id FROM matrix.users_permissions WHERE sys_user_id = ? AND sys_permission_id = ? ");
				$stmt1->bind_param("ss", $alert_user_id,$sys_permission_id1);
				$stmt1->execute();
				$stmt1->store_result();
				$stmt1->bind_result($id);
				$num_permissions = $stmt1->num_rows;
				$stmt1->close();

				$querytype = 'Updated';

			    if ($num_permissions == 0) {
			        $std = $mysqlimatrix62->prepare("INSERT INTO matrix.users_permissions (sys_user_id, sys_permission_id) VALUES (?,?)");
					$std->bind_param('ss',$alert_user_id,$sys_permission_id1);
					$std->execute();
					$std->close();

					$querytype = 'Inserted';
			    }
		    }
		}

		//echo 4;die;

		$arr=array (
			'user_id'   		   => $alert_user_id,
			'group_id'   		   => $alert_group_id,
			'alert_sys_username'   => $alert_sys_username,
			'type'   			   => $querytype,
			'status' 		       => 1,
			'message'		       => "Success"
		);
		array_push($data,$arr);
	}
	
	echo json_encode($data);
	
	
}
?>