<?php
    include_once 'opendb.php';
    $filter="";
    $CompID=0;
    $issmfilter=1;
      if (isset($_POST["comp_id"]))
    {
        $CompID=$_POST["comp_id"]; 
         $filter.=" where comp_id=" . $CompID;
    }
    if($CompID==0) {
        $response["message"] = "|No Web Co ID|";
         
            // echo no users JSON
            die( json_encode($response));
    }
    if (isset($_POST["last_edit"]))
    {
        $last_edit=$_POST["last_edit"];
        if ($last_edit=='') $last_edit="0" ;        
        $filter.=" and loc_edit_time >= " . $last_edit  ;
        
    }
      $sql = "SELECT set_value FROM appsettings WHERE set_category='GENERAL' and set_name like 'CUST_SM_FILTER' and comp_id=".$CompID;
        $sresult = $conn->query($sql);
        if ($sresult->num_rows > 0 )
        { 
               if($srow = $sresult->fetch_assoc())
                 {
                   if( $srow["set_value"]=="Yes"){
                       $issmfilter=1;
                   }
                   else {
                       $issmfilter=0;
                   }
                 }
        }
    
    if (isset($_POST["smancode"]) )
    {
        $sql = "SELECT client_type FROM mobile_clients WHERE  counter_code like '".$_POST["smancode"] ."' and comp_id=".$CompID;
        $sresult = $conn->query($sql);
        if ($sresult->num_rows > 0 )
        { 
             if($srow = $sresult->fetch_assoc())
             {
                   if( $srow["client_type"]==0){   //salesman
                       if ($issmfilter==1){
                           // $filter.=" and SMAN_CODE like'" . $_POST["smancode"]."' ";
                       }
                   }
                   elseif( $srow["client_type"]==1) {  //customer
                        $filter.=" and  sub_code like '" . $_POST["smancode"]."' "; 
                   }
             }
        }
    }
    $Qry="SELECT sub_code,latitude,longitude,loc_edit_time from subsidiary ";
    $Qry.=$filter;
    //die($Qry);
    $result = $conn->query($Qry); // or die(mysql_error());
    if ($result->num_rows > 0)
    {
        $rows = array();
        while ($r = mysqli_fetch_assoc($result)) {   
             $rows[] = $r;
        }
        echo json_encode($rows);
     } else
     {   
            $response["message"] = "|No Records|";
            echo json_encode($response);
     }
 $conn->close();
?>