<?php
include_once('racss.php');
session_start();
if(!isset($_SESSION['titles']) || !isset($_SESSION['positions'])|| !isset($_SESSION['usernames'])){
header("location:index.php");
}

$flt=racss(1);
$con=mysqli_connect("localhost","primarysales","S5L7lF01EQZvQrGK","primarysales_diana");

$q = intval($_GET['q']);

if(isset($_REQUEST['starts'])){
echo "starts ok";	
$starts=$_REQUEST['starts'];}
else{
$starts=date('Y-m-01');}

if(isset($_REQUEST['ends'])){
$ends=$_REQUEST['ends'];}
else{
$ends=date('Y-m-t');}

if(isset($_REQUEST['agents'])){
$agents=$_REQUEST['agents'];}
else{
$agents='all';}

if(isset($_REQUEST['terrys'])){
$terrys=$_REQUEST['terrys'];}
else{
$terrys='all';}

if(isset($_REQUEST['executive'])){
$exce=$_REQUEST['executive'];}
else{
$exce='all';}

if(isset($_REQUEST['rsmname'])){
$rsm=$_REQUEST['rsmname'];}
else{
$rsm='all';}

if(isset($_REQUEST['regions'])){
$regions=$_REQUEST['regions'];}
else{
$regions='all';}

if(strtolower($agents)!='all'){
$flt=$flt." and agent_name='".$agents."' ";}
if(strtolower($terrys)!='all'){
$flt=$flt." and territory_name='".$terrys."' ";}
if(strtolower($exce)!='all'){
$flt=$flt."and executive_name='".$exce."'";}
if(strtolower($rsm)!='all'){
$flt=$flt."and rsm_name='".$rsm."'";}
if(strtolower($regions)!='all'){
$flt=$flt." and region='".$regions."' ";}


$sql = "SELECT distinct agent_name,territory_name FROM agentsmrd ".$flt." and agent_names LIKE '%".$_GET['q']."%' "; 
$result = mysqli_query($con,$sql);

$json = [];
while($row=mysqli_fetch_array($result)){
     $json[] = ['id'=>$row['agent_name'], 'text'=>$row['agent_name'].'--'.$row['territory_name']];
}
echo json_encode($json);
?>
