<?php
require_once ("varables.php");

$myJSON['message'] = "0";
$myJSON['mmm'] = array();
if(isset($_POST["nekot"]) && isset($_POST["an1d"] )
		&& isset($_POST["rdtid"])&& isset($_POST["me3od"])
		&& isset($_POST["C_id"])&& isset($_POST["R_di"])
		&& isset($_POST["sort"]))
{
	$toke = $_POST["nekot"];
	$id = $_POST["rdtid"];
	$user_id = $_POST["an1d"];
	$Cid = $_POST["C_id"];
	$Rid = $_POST["R_di"];
	$sort = $_POST["sort"];
	$method =  $_POST["me3od"];
    $connect = @mysqli_connect($hostname,$username,$password,$database);
    if($connect)
    {
        @mysqli_query($connect,"SET CHARACTER SET utf8;");
        $query_token = "SELECT id FROM ".$tbl_sessions." WHERE token = '".$toke."' AND uid ='".$user_id."' AND type ='A' LIMIT 1";
		$tokres=@mysqli_query($connect,$query_token);
        if (!$tokres) {
            $myJSON['message']= "400" ;

        }
		else{

			$countoft = 0;
            while($rowt = @mysqli_fetch_assoc($tokres)){
				array_push($myJSON['mmm'], $rowt);
                $countoft++;
			}
			if($countoft == 0){
				$myJSON['message']= "405" ;
			}
			else{
				if($method == 0){
					$delete_q = "DELETE FROM ".$tbl_routdtl." WHERE rdtid='".$id."'";
					$qcusrouted = "UPDATE ".$tbl_customer." SET routed = 0 WHERE id ='".$Cid."'";
					$delres=@mysqli_query($connect,$delete_q);
					if(!$delres){
						$myJSON['message']= "404" ;
					}
					else{
						$myJSON['message']= "200";
						$ii = @mysqli_query($connect,$qcusrouted);
						if(!$ii)
						echo @mysqli_error($connect);
					}
				}
				else{
					$serch_q = "SELECT rdtid FROM ".$tbl_routdtl." WHERE C_id ='".$Cid."' AND R_id = '".$Rid."'";
					$qcusrouted = "UPDATE ".$tbl_customer." SET routed = 1 WHERE id ='".$Cid."'";
					$serchres=@mysqli_query($connect,$serch_q);
					if($serchres){
						$countoft = 0;
						while($rowt = @mysqli_fetch_assoc($serchres))
							$countoft++;
						if($countoft == 0){
							$myJSON['message']= "200";
							$insert_Q = "INSERT INTO ".$tbl_routdtl." (C_id,R_id,sort)
							VALUES ('".$Cid."','".$Rid."','".$sort."')";
								$insres=@mysqli_query($connect,$insert_Q);
								if(!$insres){
									$myJSON['message']= "404" ;
								}
								else{
									$myJSON['message']= "200" ;
									$ii = @mysqli_query($connect,$qcusrouted);
									if(!$ii)
									echo @mysqli_error($connect);
								}
						}
						else{
							$myJSON['message']= "444" ;
						}
					}
					else
						$myJSON['message']= "000" ;
				}
			}
		}
	}
	 else
		 $myJSON['message']="402";
}
    echo  json_encode($myJSON);

?>
