<?php
ob_start();
session_start();
$chain = "AWdrh78y892Djk*^523*%$#ghgHGHia&%$*)AsfdsLJnLaad";
include("validateLogin.php");
include("includeInformation.php");

if(empty($_POST['rowId']) || empty($_POST['newConnection']) || empty($_POST['companyCode'])) 
{
	echo '3';
	exit();
}
$rowId = $_POST['rowId'];
$newConnection = $_POST['newConnection'];
$changeAll = $_POST['changeAll'];
$companyCode = $_POST['companyCode'];

$oldConnections = '-1';
if($companyCode!=-1)
{
	$oldConnections = '';
	$queryGetAllConnections = "SELECT `Id` FROM `connections` WHERE `CompanyCode`=$companyCode";
	$resultGetAllConnections = mysqli_query($conn, $queryGetAllConnections);
	if( !mysqli_num_rows($resultGetAllConnections) )
	{
		echo '3';
		exit();
	}
	
	$rowGetAllConnections = mysqli_fetch_assoc($resultGetAllConnections);
	$oldConnections.= $rowGetAllConnections['Id'];
	while( $rowGetAllConnections = mysqli_fetch_assoc($resultGetAllConnections) )
		$oldConnections.=','.$rowGetAllConnections['Id'];	
}

$queryGetRandomConnection = "SELECT `Id` FROM `connections` WHERE `CompanyCode`=$newConnection ORDER BY RAND() LIMIT 0,1";
$resultGetRandomConnection = mysqli_query($conn, $queryGetRandomConnection);
if( !mysqli_num_rows($resultGetRandomConnection) )
{
	echo '3';
	exit();
}
else
{
	$rowGetRandomConnection = mysqli_fetch_assoc($resultGetRandomConnection);
}

$getHistoryId = mysqli_query($conn, "SELECT `history_id`, `type` FROM `msg_send_temp` WHERE id=".$rowId);
if( !mysqli_num_rows($getHistoryId) )
{
	echo '1';
	exit();
}
$getHistoryRow = mysqli_fetch_array($getHistoryId);
$historyId =  $getHistoryRow['history_id'];
$oldType =  $getHistoryRow['type'];		
if($changeAll == 0)
{
	$getMsgKey = mysqli_query($conn, "SELECT `msg_key` FROM `temp_history` WHERE id=".$historyId);
	if( !mysqli_num_rows($getMsgKey) )
	{
		echo '1';
		exit();
	} 
	$getMsgRow = mysqli_fetch_array($getMsgKey);
	$msgKey =  $getMsgRow['msg_key'];
	$result = mysqli_query($conn, "UPDATE `msg_send_temp` SET type=".$rowGetRandomConnection['Id']." WHERE `status`='-1' AND `type` IN (".$oldConnections.") AND history_id IN ( SELECT id FROM `temp_history` WHERE msg_key = '".$msgKey."')");
	if($result)
	{
		echo '2';
		exit();
	}
	else
	{
		echo '3';
		exit();
	}	
}
else
{
	$result = mysqli_query($conn, "UPDATE `msg_send_temp` SET `type`=".$rowGetRandomConnection['Id']." WHERE `status`='-1' AND `type` IN (".$oldConnections.")");
	if($result)
	{
		echo '2';
		exit();
	}
	else
	{
		echo '3';
		exit();
	}	
}
ob_end_flush();
?>
