<?php

require_once __DIR__ . '/db_config.php';

$r = array();
$r["tickets"]= array();


if (isset($_POST["mail"]) ) {
 
$cname=$_POST["cname"];
$email=$_POST["mail"];
$start=$_POST["start"];
$date=$_POST["date"];



$r["start"]=$start;

$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysql_error());

    if(empty($start) && $start!="0"){
        //$query="SELECT count(*) as total WHERE Assignedto='$email' AND t.companyname='$cname' AND t.ticketstatus=('complete' or 'incomplete') ORDER BY t.assigneddateandtime ASC ";
            echo $start;

        $query="SELECT count(*) as total  FROM tickets t INNER JOIN atmdetails f ON t.atmid=f.Id WHERE (t.ticketstatus='complete' or t.ticketstatus='incomplete') AND t.companyname='$cname' AND Assignedto='$email' ";
        if(!empty($date)){
           $query=$query. " AND DATE(t.assigneddateandtime)='$date'";
        }

        $result=mysqli_query($con,$query);
    
        if(!empty($result) && mysqli_num_rows($result) > 0){
            while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
                $r["count"]=$row["total"];
            }
        }
    }else{
        //$query="SELECT f.customername,f.companyname,f.latitude,f.longitude,f.location,f.atmphonenumber,t.ticketnumber,t.questionorcallreason,t.assigneddateandtime,t.ticketnumber,t.companyname as cname,t.ticketstatus,t.ticketstage,t.priority,t.atmid FROM tickets t INNER JOIN atmdetails f ON t.atmid=f.Id WHERE Assignedto='$email' AND t.companyname='$cname' AND t.ticketstatus=('complete' or 'incomplete') ORDER BY t.assigneddateandtime ASC ";
        
         $query="SELECT f.customername,f.companyname,f.latitude,f.longitude,f.location,f.atmphonenumber,t.ticketnumber,t.questionorcallreason,t.assigneddateandtime,t.ticketnumber,t.companyname as cname,t.ticketstatus,t.ticketstage,t.priority,t.atmid,t.ticketstatus FROM tickets t INNER JOIN atmdetails f ON t.atmid=f.Id WHERE (t.ticketstatus='complete' or t.ticketstatus='incomplete') AND t.companyname='$cname' AND Assignedto='$email' ";
         
        if(!empty($date)){
           $query=$query. " AND DATE(t.assigneddateandtime)='$date'";
        }
        
        $query=$query." ORDER BY t.assigneddateandtime ASC LIMIT $start,10";
        
        $result=mysqli_query($con,$query);
        
        if(!empty($result) && mysqli_num_rows($result) > 0){
            while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
                array_push($r["tickets"], $row);
            }
        }
    }
}

echo str_replace("no data available","",json_encode($r));
//echo json_encode($r);
?>