<?php 

require_once 'db_configaswas.php';

$response = array();

if(isset($_GET['apicall'])){
	
	switch($_GET['apicall']){
	    
	    
	     case 'getStvCustom':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '' or $data['item_name'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$item_name=strip_tags(mysqli_real_escape_string($con,$data['item_name']));


$bookings_sql = $con->query("SELECT * FROM `stock` WHERE ClientID='".$ClientID."' and (Purchase_quantity-Sales_quantity)>0 and Product_Name Like '".$item_name."%' group by Product_Name "); 




while($rows = $bookings_sql->fetch_assoc())
{
$am_result['flag'] = '0';
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];
$am_result['Batch'] = $rows['Batch'];
$am_result['Expiry'] = $rows['Expiry'];
$am_result['Purchase_quantity'] = $rows['Purchase_quantity'];
$am_result['Sales_quantity'] = $rows['Sales_quantity'];
$am_result['uPack'] = $rows['uPack'];
$am_result['Unit_Rate'] = $rows['Unit_Rate'];
$am_result['Sales_Rate'] = $rows['Sales_Rate'];
$am_result['Manufacturer'] = $rows['manufacturer'];
$all_amenity[] = $am_result;
}



$test = array('All_Stock'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
	    
	    
	    	    
	    	    	case 'updateUserpws':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['userid'] == '' or $data['password'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$userid= strip_tags(mysqli_real_escape_string($con,$data['userid']));
$password =strip_tags(mysqli_real_escape_string($con,$data['password']));
$DefaultPwd=md5('".$password."');

$con->query("update user set Password='".$DefaultPwd."' where id='".$userid."' ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;
	    
	    	case 'getLastSalesClientid':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['ClientID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$checkexist = $con->query("select max(concat(bill_date,' ',bill_time)) as LastBillDt ,Bill_No from sales1 WHERE ClientID='".$ClientID."' group by ClientID;");
if($checkexist->num_rows != 0)
{
    	$checkProductname = $con->query("select max(concat(bill_date,' ',bill_time)) as LastBillDt ,MAX(Bill_No) as Bill_No from sales1 WHERE ClientID='".$ClientID."' and bill_date > '2023-04-01' group by ClientID")->fetch_assoc();
		$billno=$checkProductname['Bill_No'];
			$last_tym=$checkProductname['LastBillDt'];
    
$returnArr = array("ResponseCode"=>"401","Result"=>"true","ResponseMsg"=>$billno.','.$last_tym);
}
else{
  $returnArr = array("ResponseCode"=>"401","Result"=>"fasle","ResponseMsg"=>"0");  
    
}



}

echo json_encode($returnArr);	



break;
	    
	    case 'getDeadStockViewByItem':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == ''  or $data['From_date'] == '' or $data['To_Range'] == ''    or $data['Supplier'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
$Supplier = strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
$timestampFromDate = strtotime($From_date);
$timestampToDate = strtotime($To_Range);

      $user_sql = $con->query("select distinct * from (
select * from (
select distinct sname,item,cname,stkqty,prate,mrp,sitm,bdt from (

select distinct p.supplier_name as sname,pm.item_description as item,pm.company_name as cname,stkqty,p.invoice_date as dt,Unit as prate,(pm.mrp/pm.pack) as mrp 
 from purchase1 p left join purchase_item1 pm on p.purchase_id=pm.purchase_id and p.ClientID =pm.ClientID
 left join ( 
     select product_name,manufacturer,batch,(purchase_quantity-sales_quantity) as stkqty,mrp,ClientID from stock where 1>0 
     and (purchase_quantity-sales_quantity) >0 and clientid ='".$ClientID."'
           )s on pm.item_description=s.product_name and pm.company_name=s.manufacturer
 and pm.batch = s.Batch and p.ClientID = s.ClientID and pm.ClientID = s.ClientID
where 1>0  and (pm.quantity-pm.retquantity) > 0 and (stkqty) >0
and p.ClientID ='".$ClientID."' and pm.ClientID ='".$ClientID."' and p.ClientID = '".$ClientID."'
    )onee  Left Join
 (
 select distinct item_description as sitm,company_name as scmp,bill_date as bdt from sales1 sa,sales_item1 si where sa.bill_no=si.bill_no and sa.ClientID = si.ClientID  
 and COALESCE(bill_date,'1900-01-01') >='".date("Y-m-d", $timestampFromDate)."' 
      and COALESCE(bill_date,'1900-01-01') <='".date("Y-m-d", $timestampToDate)."'
 and sa.ClientID ='".$ClientID."' and si.ClientID ='".$ClientID."' 
 
 ) two on onee.item=two.sitm and onee.cname = two.scmp
 )finale where sitm is null
 
 
 UNION
 
select * from (
select distinct sname,item,cname,stkqty,prate,mrp,sitm,bdt from (

select distinct os.supplier_name as sname,item_description as item,company_name as cname,stkqty,invoice_date as dt,purchase_rate as prate,(os.mrp/pack) as mrp 
 from opening_stock1 os 
 left join ( 
     select product_name,manufacturer,batch,(purchase_quantity-sales_quantity) as stkqty,mrp,ClientID from stock where 1>0 
     and (purchase_quantity-sales_quantity) >0 and clientid ='".$ClientID."'
           )s on os.item_description=s.product_name and os.company_name=s.manufacturer
 and os.batch = s.Batch and os.ClientID = s.ClientID  
where 1>0  and (os.quantity) > 0 and (stkqty) >0
and os.ClientID ='".$ClientID."' and s.ClientID = '".$ClientID."'
    )onee  Left Join
 (
 select distinct item_description as sitm,company_name as scmp,bill_date as bdt from sales1 sa,sales_item1 si where sa.bill_no=si.bill_no and sa.ClientID = si.ClientID  
 and COALESCE(bill_date,'1900-01-01') >='2023-08-19'
 and sa.ClientID ='".$ClientID."' and si.ClientID ='".$ClientID."'   
 ) two on onee.item=two.sitm and onee.cname = two.scmp
 )finale where sitm is null
 
    )lastS left join ( select distinct item_description as lastsitm,company_name as lastscmp,max(bill_date) as maxbdt from sales1 sa,sales_item1 si where sa.bill_no=si.bill_no and sa.ClientID = si.ClientID and sa.clientid ='".$ClientID."' and si.clientid ='".$ClientID."' 
group by item_description,company_name)lastbdt on lastS.item = lastbdt.lastsitm and lastS.cname = lastbdt.lastscmp
where sname='".$Supplier."'
order by 2;");  

while($rows = $user_sql->fetch_assoc())
{

	$user_result['sname'] = $rows['sname'];
	$user_result['item'] = $rows['item'];
	$user_result['cname'] = $rows['cname'];
	$user_result['stkqty'] = $rows['stkqty'];
		$user_result['prate'] = $rows['prate'];
			$user_result['mrp'] = $rows['mrp'];
    $all_users[] = $user_result;



}

$test = array('DeadStockByItem'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Success","ResultData"=>$test);


echo json_encode($returnArr);		


}

break; 
	     case 'getDeadStockView':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == ''  or $data['From_date'] == '' or $data['To_Range'] == ''    )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
$timestampFromDate = strtotime($From_date);
$timestampToDate = strtotime($To_Range);

      $user_sql = $con->query("select sname,count(sname) as suppcnt,SUM(prate) as maxpr,SUM(mrp) as maxmrp from (
select distinct * from (
select * from (
select distinct sname,item,cname,stkqty,prate,mrp,sitm,bdt from (

select distinct p.supplier_name as sname,pm.item_description as item,pm.company_name as cname,stkqty,p.invoice_date as dt,Unit as prate,(pm.mrp/pm.pack) as mrp 
 from purchase1 p left join purchase_item1 pm on p.purchase_id=pm.purchase_id and p.ClientID =pm.ClientID
 left join ( 
     select product_name,manufacturer,batch,(purchase_quantity-sales_quantity) as stkqty,mrp,ClientID from stock where 1>0 
     and (purchase_quantity-sales_quantity) >0 and clientid ='".$ClientID."'
           )s on pm.item_description=s.product_name and pm.company_name=s.manufacturer
 and pm.batch = s.Batch and p.ClientID = s.ClientID and pm.ClientID = s.ClientID
where 1>0  and (pm.quantity-pm.retquantity) > 0 and (stkqty) >0
and p.ClientID ='".$ClientID."' and pm.ClientID ='".$ClientID."' and p.ClientID = '".$ClientID."'
    )onee  Left Join
 (
 select distinct item_description as sitm,company_name as scmp,bill_date as bdt from sales1 sa,sales_item1 si where sa.bill_no=si.bill_no and sa.ClientID = si.ClientID  
 and COALESCE(bill_date,'1900-01-01') >='".date("Y-m-d", $timestampFromDate)."' 
      and COALESCE(bill_date,'1900-01-01') <='".date("Y-m-d", $timestampToDate)."' 
 and sa.ClientID ='".$ClientID."' and si.ClientID ='".$ClientID."' 
 
 ) two on onee.item=two.sitm and onee.cname = two.scmp
 )finale where sitm is null
 
 
 UNION
 
select * from (
select distinct sname,item,cname,stkqty,prate,mrp,sitm,bdt from (

select distinct os.supplier_name as sname,item_description as item,company_name as cname,stkqty,invoice_date as dt,purchase_rate as prate,(os.mrp/pack) as mrp 
 from opening_stock1 os 
 left join ( 
     select product_name,manufacturer,batch,(purchase_quantity-sales_quantity) as stkqty,mrp,ClientID from stock where 1>0 
     and (purchase_quantity-sales_quantity) >0 and clientid ='".$ClientID."'
           )s on os.item_description=s.product_name and os.company_name=s.manufacturer
 and os.batch = s.Batch and os.ClientID = s.ClientID  
where 1>0  and (os.quantity) > 0 and (stkqty) >0
and os.ClientID ='".$ClientID."' and s.ClientID = '".$ClientID."'
    )onee  Left Join
 (
 select distinct item_description as sitm,company_name as scmp,bill_date as bdt from sales1 sa,sales_item1 si where sa.bill_no=si.bill_no and sa.ClientID = si.ClientID  
      and COALESCE(bill_date,'1900-01-01') <='2023-06-19'
 and COALESCE(bill_date,'1900-01-01') >='2023-08-19'
 and sa.ClientID ='".$ClientID."' and si.ClientID ='".$ClientID."'   
 ) two on onee.item=two.sitm and onee.cname = two.scmp
 )finale where sitm is null
 
    )lastS left join ( select distinct item_description as lastsitm,company_name as lastscmp,max(bill_date) as maxbdt from sales1 sa,sales_item1 si where sa.bill_no=si.bill_no and sa.ClientID = si.ClientID and sa.clientid ='".$ClientID."' and si.clientid ='".$ClientID."' 
group by item_description,company_name)lastbdt on lastS.item = lastbdt.lastsitm and lastS.cname = lastbdt.lastscmp
 
)scnt group by sname");  

while($rows = $user_sql->fetch_assoc())
{

	$user_result['sname'] = $rows['sname'];
	$user_result['suppcnt'] = $rows['suppcnt'];
	$user_result['maxpr'] = $rows['maxpr'];
	$user_result['maxmrp'] = $rows['maxmrp'];
    $all_users[] = $user_result;



}

$test = array('DeadStock'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Success","ResultData"=>$test);


echo json_encode($returnArr);		


}

break; 
	    
	      case 'getSalesBillView':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == '' or $data['Bill_no'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Bill_no = strip_tags(mysqli_real_escape_string($con,$data['Bill_no']));
$app_login_count=0;
$user_sql = $con->query("SELECT * FROM sales_item1 WHERE ClientID='".$ClientID."' and bill_no='".$Bill_no."'"); 

$chekstudentid = $con->query("SELECT * FROM sales1 WHERE ClientID='".$ClientID."' and bill_no='".$Bill_no."'")->fetch_assoc();
      
if (is_null($chekstudentid)){
    
     $app_login_count=0;
}
else{
     $app_login_count=$chekstudentid['bill_date'].','.$chekstudentid['grand_total'].','
     .$chekstudentid['patient'].','.$chekstudentid['doctor'];
}
while($rows = $user_sql->fetch_assoc())
{

	$user_result['bill_no'] = $rows['bill_no'];
	$user_result['bill_date'] = $rows['expiry_date'];
	$user_result['product_name'] = $rows['item_description'];
	$user_result['qty'] = $rows['quantity'];
	$user_result['amount'] = $rows['amount'];
	$user_result['Rate'] = $rows['rate'];
	$user_result['MRP'] = $rows['mrp'];
	$user_result['Batch'] = $rows['batch'];
	$user_result['exp'] = $rows['expiry_date'];
	$user_result['Company_Name'] = $rows['company_name'];
    $all_users[] = $user_result;



}


$test = array('SaleBillsOverview'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$app_login_count,"ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 
	   
	    
	    
	    
	    case 'getEstimateBillView':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == ''  or $data['From_date'] == '' or $data['To_Range'] == '' or $data['Type'] == ''  or $data['Type'] == ''  or $data['Bill_no'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
$Type = strip_tags(mysqli_real_escape_string($con,$data['Type']));
$Bill_no = strip_tags(mysqli_real_escape_string($con,$data['Bill_no']));
$timestampFromDate = strtotime($From_date);
$timestampToDate = strtotime($To_Range);
 $app_login_count=0;

if($Type=='1'){
      $user_sql = $con->query("select bill_no,bill_date,product_name,Company_Name,sum(quantity) as qty,
      ExpDt as  exp,
      Batch,MRP,Rate,sum(amount) as amount from Estimate1 
where clientid ='".$ClientID."'
and bill_date >='".date("Y-m-d", $timestampFromDate)."' 
and bill_date <='".date("Y-m-d", $timestampToDate)."' 

group by bill_no");  
}
else{
      $user_sql = $con->query("select bill_no,bill_date,product_name,Company_Name,sum(quantity) as qty,
       ExpDt as  exp,
      Batch,MRP,Rate,sum(amount) as amount from Estimate1  
where clientid ='".$ClientID."'
and bill_no='".$Bill_no."'
and bill_date >='".date("Y-m-d", $timestampFromDate)."' 
and bill_date <='".date("Y-m-d", $timestampToDate)."' 
group by bill_no,bill_date,product_name;"); 

 	$chekstudentid = $con->query("select sum(amount) as amtsum,Customer_Name,Doctor_Name from (
select bill_no,bill_date,Customer_Name,Doctor_Name,product_name,company_name,batch,quantity,rate,mrp,amount,cgst,sgst,auto_id
from Estimate1 where Clientid ='".$ClientID."'
and bill_date ='".date("Y-m-d", $timestampToDate)."'
    and bill_no='".$Bill_no."'
)summary group by bill_no,bill_date
order by Bill_Date,bill_no")->fetch_assoc();
      
if (is_null($chekstudentid)){
    
     $app_login_count=0;
}
else{
     $app_login_count=$chekstudentid['amtsum'].','
     .$chekstudentid['Customer_Name'].','.$chekstudentid['Doctor_Name'];
}
}







while($rows = $user_sql->fetch_assoc())
{

	$user_result['bill_no'] = $rows['bill_no'];
	$user_result['bill_date'] = $rows['bill_date'];
	$user_result['product_name'] = $rows['product_name'];
	$user_result['qty'] = $rows['qty'];
	$user_result['amount'] = $rows['amount'];
	$user_result['Rate'] = $rows['Rate'];
	$user_result['MRP'] = $rows['MRP'];
	$user_result['Batch'] = $rows['Batch'];
	$user_result['exp'] = $rows['exp'];
	$user_result['Company_Name'] = $rows['Company_Name'];
    $all_users[] = $user_result;



}


$test = array('EstimateBills'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$app_login_count,"ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 
	    
	    
	    
	    
case 'getPurchasePaidStatus':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['Supplier_name'] == '' or $data['Invoice_no'] == '' or  $data['Invoice_date'] == '' or  $data['Client_ID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$Supplier_name=strip_tags(mysqli_real_escape_string($con,$data['Supplier_name']));
$Client_ID=strip_tags(mysqli_real_escape_string($con,$data['Client_ID']));
$Invoice_no=strip_tags(mysqli_real_escape_string($con,$data['Invoice_no']));
$Invoice_date=strip_tags(mysqli_real_escape_string($con,$data['Invoice_date']));
$timestampFromDate = strtotime($Invoice_date);

 	$chekstudentid = $con->query("select PaidAmt from purchase1 p
left join ( select Clientid as LedgCID,Purchase_ID as LedgPID,Particulars as LedgPName,Group_Head as LedgGH,type as LedgType,'CASH PAYMENT' as PaidType,Debit as PaidAmt,Voucher_Date as PaidDt from Ledger where clientid ='".$Client_ID."' and Group_Head ='SUNDRY CREDITORS' and type='CP' 
           UNION
           select Clientid as LedgCID,Purchase_ID as LedgPID,Particulars as LedgPName,Group_Head as LedgGH,type as LedgType,'BANK WITHDRAWAL' as PaidType,Debit as PaidAmt,Voucher_Date as PaidDt from Ledger where clientid ='".$Client_ID."' and Group_Head ='SUNDRY CREDITORS' and type='BW' and status ='P'
          )l on p.ClientID = l.LedgCID and p.supplier_name = l.LedgPName
and p.purchase_id  = l.LedgPID
where 1>0
          
            and ClientID='".$Client_ID."' and LedgCID ='".$Client_ID."'
            and invoice_no ='".$Invoice_no."'
          and supplier_name ='".$Supplier_name."'
      GROUP by invoice_no")->fetch_assoc();
      
if (is_null($chekstudentid)){
    
     $app_login_count=0;
}
else{
     $app_login_count=$chekstudentid['PaidAmt'];
}
	   



  $user_sql = $con->query("select invoice_no,invoice_date,purchase_date,supplier_name,SUM(grand_total) as tot,narration,PaidAmt,PaidType,PaidDt from purchase1 p
left join ( select Clientid as LedgCID,Purchase_ID as LedgPID,Particulars as LedgPName,Group_Head as LedgGH,type as LedgType,'CASH PAYMENT' as PaidType,Debit as PaidAmt,Voucher_Date as PaidDt from Ledger where clientid ='".$Client_ID."' and Group_Head ='SUNDRY CREDITORS' and type='CP' 
           UNION
           select Clientid as LedgCID,Purchase_ID as LedgPID,Particulars as LedgPName,Group_Head as LedgGH,type as LedgType,'BANK WITHDRAWAL' as PaidType,Debit as PaidAmt,Voucher_Date as PaidDt from Ledger where clientid ='".$Client_ID."' and Group_Head ='SUNDRY CREDITORS' and type='BW' and status ='P'
          )l on p.ClientID = l.LedgCID and p.supplier_name = l.LedgPName
and p.purchase_id  = l.LedgPID
where 1>0
          
            and ClientID='".$Client_ID."' and LedgCID ='".$Client_ID."'
            and invoice_no ='".$Invoice_no."'
          and supplier_name ='".$Supplier_name."'
      GROUP by ClientID,purchase_date,supplier_name,invoice_no,invoice_date,PaidAmt,PaidType,PaidDt");  



while($rows = $user_sql->fetch_assoc())
{

	$user_result['PaidAmt'] = $rows['PaidAmt'];
	$user_result['PaidType'] = $rows['PaidType'];
	$user_result['PaidDt'] = $rows['PaidDt'];
    $all_users[] = $user_result;



}


$test = array('PurchasePaidStatus'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$app_login_count,"ResultData"=>$test);


echo json_encode($returnArr);		




}

break;
	    
	    
	    case 'getAllStockByClientFilter':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '' or $data['Type'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Type=strip_tags(mysqli_real_escape_string($con,$data['Type']));

   if($ClientID =='0')
{
$bookings_sql = $con->query("select * from stock where Purchase_quantity-Sales_quantity > 0 LIMIT 1000"); 
}
else{
    
    if($Type == '1'){
     $bookings_sql = $con->query("select '0' as flag,stock.* from stock where Product_Name not in ( select distinct ProductName from StockVerification where ClientID ='".$ClientID."') and ClientID ='".$ClientID."' and (Purchase_quantity-Sales_quantity)>0 group by Product_Name 
UNION 
select '1' as flag,stock.* from stock where Product_Name in ( select distinct ProductName from StockVerification where ClientID ='".$ClientID."') and ClientID ='".$ClientID."' and (Purchase_quantity-Sales_quantity)>0 group by Product_Name 
 LIMIT 10");    
    }
    
    
    if($Type == '2'){
        
        $bookings_sql = $con->query("select '2' as flag,stock.* from stock where ClientID ='".$ClientID."' and (Purchase_quantity-Sales_quantity)>0 and Product_Name in ( select distinct item_description from Edit_Sales_Item1 where ClientID ='".$ClientID."' and bill_no in ( select distinct bill_no from Edit_Sales1 where ClientID ='".$ClientID."' and bill_date >='2023-11-01' and bill_date <='2023-12-13')) "); 
    }
    
    if($Type =='3'){
       $bookings_sql = $con->query("select '3' as flag,stock.* from stock where ClientID ='".$ClientID."' and (Purchase_quantity-Sales_quantity)>0 and Product_Name in ( select distinct product from Cleared_SalesInvoices where ClientID ='".$ClientID."' and Cleared_Date >='2023-10-01' and Cleared_Date <='2023-11-09' ) order by flag desc,Product_Name  ");     
        
    }
    
       if($Type =='5'){
       $bookings_sql = $con->query("select '5' as flag,st.* from (

select distinct sitem,scid from (SELECT distinct item_description as sitem,clientid as scid FROM sales_item1 where clientid = '".$ClientID."' and COALESCE(SRate_DiscountP,0) >0  and bill_no in ( select distinct bill_no from sales1 where clientid ='".$ClientID."' and bill_date >='2023-10-31' 
and bill_date <='2023-11-01' ))si left join ( 
    select distinct item_description as esitem,clientid as escid FROM Edit_Sales_Item1  where clientid = '".$ClientID."' and COALESCE(SRate_Discount,0) =0 and bill_no in ( select distinct bill_no from Edit_Sales1  where clientid ='".$ClientID."' and bill_date >='2023-10-31' and bill_date <='2023-11-01' )
)esi on si.sitem = esi.esitem  and scid = escid
where scid ='".$ClientID."' and escid = '".$ClientID."')si left join ( select * from stock where clientid ='".$ClientID."' group by Product_Name) st on si.sitem = st.product_name and si.scid = st.clientid;");     
        
    }
    
       if($Type =='4'){
       $bookings_sql = $con->query("select '4' as flag,st.* from stock st left join ( select distinct ClientID as EstCID,Product_Name as EstPName from Estimate1 where ClientID ='".$ClientID."')est 
on st.ClientID= est.EstCID and st.product_name = est.EstPName where ClientID ='50' and (Purchase_quantity-Sales_quantity)>0 and est.EstPName is null  ");     
        
    }

}



while($rows = $bookings_sql->fetch_assoc())
{
    $am_result['flag'] = $rows['flag'];
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];
$am_result['Batch'] = $rows['Batch'];
$am_result['Expiry'] = $rows['Expiry'];
$am_result['Purchase_quantity'] = $rows['Purchase_quantity'];
$am_result['Sales_quantity'] = $rows['Sales_quantity'];
$am_result['uPack'] = $rows['uPack'];
$am_result['Unit_Rate'] = $rows['Unit_Rate'];
$am_result['Sales_Rate'] = $rows['Sales_Rate'];
$am_result['Manufacturer'] = $rows['manufacturer'];
$all_amenity[] = $am_result;
}



$test = array('All_Stock'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
		
	    
	     case 'getStockSummarybyRange':
	
	
    $data = json_decode(file_get_contents('php://input'), true);
    $all_users=null;
if($data['ClientID'] == ''  or $data['From_date'] == '' or $data['To_Range'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
$timestampFromDate = strtotime($From_date);
$timestampToDate = strtotime($To_Range);

  $user_sql = $con->query("select product_name as product_name,comp as comp,batch as batch,qty as qty,
prate as avgprate,srate as avgsrate,mrp as avgmrp,MRPPack as MRPPack,Pack as Pack,prate*qty as totprate,srate*qty as totsrate,mrp*qty as totmrp,
expdt  from (


select product_name as product_name,comp as comp,batch as batch,
sum(qty+qty1) as qty,max(prate) as prate,sum(srate)/sum(qty) as srate,
sum(mrp)/sum(qty) as mrp,sum(MRPPack)/sum(qty) as MRPPack,max(Pack) as Pack,max(expdt) as expdt from(



select product_name as product_name,comp as comp,batch as batch,
sum(qty) as qty,0 as qty1,avg(prate) as prate,avg(srate)* sum(qty) as srate,
avg(mrp)* sum(qty) as mrp,avg(MRPPack)* sum(qty) as MRPPack,max(Pack) as Pack,flag 
,COALESCE(expdt,'1900-01-01') as expdt from (

select ClientID,'2020-01-01'  as dat,item_description as product_name,company_name as comp,batch as batch,
quantity  as qty,purchase_rate as prate,sale_rate as srate,
(mrp/pack) as mrp,MRP as MRPPack,Pack as Pack,opening_stock_id as no,1 as flag,expiry_date as expdt 
From opening_stock1 
Where COALESCE(purchase_rate,0) <> 0  and clientid = '".$ClientID."'
Union
select ClientID,'2020-01-01' as dat,item_description as product_name,company_name as comp,batch as batch,
quantity as qty,(mrp/pack)-((mrp/pack)*'20'/100) as prate,sale_rate as srate,(mrp/pack) as mrp,MRP as MRPPack,Pack as Pack,opening_stock_id as no,2 as flag,expiry_date as expdt 
From opening_stock1 where clientid = '".$ClientID."'  
and COALESCE(purchase_rate,0) = 0

Union

select p.ClientID,p.purchase_date as dat,pi.item_description as product_name,pi.company_name as comp,
pi.batch as batch,sum(pi.quantity+replace(pi.free,'F',0)) as qty,
max(pi.unit) as prate,max(pi.sale_rate) as srate,
max(pi.mrp/pi.pack) as mrp,max(pi.MRP) as MRPPack,max(pi.Pack) as Pack,
pi.purchase_id as no,3 as flag,expery_date  as expdt 
from purchase1 p,purchase_item1 pi
Where p.purchase_id = pi.purchase_id and p.clientid = '".$ClientID."' and pi.clientid = '".$ClientID."'
group by p.purchase_date,pi.item_description,pi.company_name,pi.batch,expery_date,pi.purchase_id,p.ClientID

Union
select ClientID,return_date as dat,item_description as product_name,company_name as comp,batch as batch,
return_quantity as qty,0 as prate,0 as srate,0 as mrp,0 as MRPPack,0 as Pack,
return_id as no,8 as flag ,'' as  expdt 
From Sales_Return1  where clientid = '".$ClientID."'
 
Union
select t.ClientID,t.transfer_date as dat,ti.item_description as product_name,ti.company_name as comp,
ti.batch as batch,ti.quantity as qty,ti.purchase_rate/ti.pack as prate,
ti.sale_rate/ti.pack as srate,ti.mrp/ti.pack as mrp,ti.mrp as MRPPack,ti.Pack as Pack,ti.transfer_id as no,
4 as flag,expiry_date  as expdt 
from transfer1 t,transfer_item1 ti
Where t.transfer_no = ti.transfer_no And t.Type = ti.Type
and t.type='I' and ti.type='I'
and t.clientid = '".$ClientID."' and ti.clientid ='".$ClientID."'
Union
select r.ClientID,r.replacement_date as dat,ri.item_description as product_name,ri.company_name as comp,
ri.batch as batch,ri.quantity as qty,ri.unit as prate,
ri.sale_rate as srate,ri.mrp/ri.pack as mrp,ri.mrp as MRPPack,ri.Pack as Pack,
0 as no,6 as flag,expiry  as expdt 
from replacement1 r,replacement_item1 ri
Where r.replacement_id = ri.replacement_id and r.clientid = '".$ClientID."' and ri.clientid = '".$ClientID."'
)as N1 
where dat<='".date("Y-m-d", $timestampToDate)."' 
group by product_name,comp,batch,flag,expdt 
Union
select product_name as product_name,comp as comp,batch as batch,0 as qty,sum(qty) as qty1,
prate as prate,srate as srate,mrp as mrp,MRPPack as MRPPack,Pack as Pack,sum(flag) as flag  
,COALESCE(expdt,'1900-01-01') as expdt 
from(

   select s.Clientid,s.bill_date as dat,si.item_description as product_name,si.company_name as comp,
si.batch as batch,-1*si.quantity as qty,0 as prate,0 as srate,0 as mrp,0 as MRPPack,0 as Pack,
0 as no,7 as flag,expiry_date  as expdt 
from sales1 s,sales_item1 si
Where s.bill_no = si.bill_no and s.clientid = '".$ClientID."' and si.clientid = '".$ClientID."'

Union
select t.Clientid,t.transfer_date as dat,ti.item_description as product_name,ti.company_name as comp,
ti.batch as batch, -1*ti.quantity as qty,0 as prate,
0 as srate,0 as mrp,0 as MRPPack,0 as Pack,ti.transfer_id as no,
10 as flag,expiry_date  as expdt 
from transfer1 t,transfer_item1 ti
Where t.transfer_no = ti.transfer_no And t.Type = ti.Type
and t.type='O' and ti.type='O' and t.clientid = '".$ClientID."' and ti.clientid = '".$ClientID."'

)as N2
where dat<='".date("Y-m-d", $timestampToDate)."' 
group by product_name,comp,batch,prate,srate,mrp,MRPPack,Pack 
,expdt 
) as N3
group by product_name,comp,batch 
Having sum(qty)+sum(qty1) > 0
and sum(qty)>0 
) N4  

 where 1>0  

order by product_name,comp,batch");  


     
  
        
    
while($rows = $user_sql->fetch_assoc())
{

    $user_result['Product_name'] = $rows['product_name'];
    $user_result['Company_Name'] = $rows['comp'];
    $user_result['Batch'] = $rows['batch'];
    $user_result['Qty'] = $rows['qty'];
    $user_result['avgprate'] = $rows['avgprate'];
    $user_result['avgsrate'] = $rows['avgsrate'];
    $user_result['avgmrp'] = $rows['avgmrp'];
        $user_result['Pack'] = $rows['Pack'];
    $user_result['MRPPack'] = $rows['MRPPack'];
    $user_result['totprate'] = $rows['totprate'];
    $user_result['totsrate'] = $rows['totsrate'];
    $user_result['totmrp'] = $rows['totmrp'];
    $user_result['expdt'] = $rows['expdt'];
    $all_users[] = $user_result;
}

$test = array('StockSummarybyRange'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	




}
        echo json_encode($returnArr);

break;
	    
	    		case 'sendToAswasWholesale':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['orderNo'] == ''   )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$orderNo = strip_tags(mysqli_real_escape_string($con,$data['orderNo']));

$con->query("update received_orders1 set  st_reason='ASWAS' where (OrderNo='".$orderNo."')");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login updated ");  
}
 
echo json_encode($returnArr);
		
break; 
	    
	    

case 'getOrdersbyWholesale':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['Supplier'] == '' or $data['Wholesale_ID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$Supplier=strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
$Wholesale_ID=strip_tags(mysqli_real_escape_string($con,$data['Wholesale_ID']));

if($Supplier == '0'){
  $user_sql = $con->query("select  rcd1.*,cli.Wholesale_ID,cli.Type  from received_orders1 rcd1
left JOIN clients cli ON rcd1.ClientID=cli.ClientID
left JOIN clients cl ON rcd1.Supplier = cl.ClientName
where cl.Wholesale_ID='".$Wholesale_ID."' and  cl.Type='W'  and rcd1.del_status != 2 and rcd1.st_reason='ASWAS'  and rcd1.Wh_recieved_status = 0");  
}
else{
   $user_sql = $con->query("select  rcd1.*,cli.Wholesale_ID,cli.Type  from received_orders1 rcd1
left JOIN clients cli ON rcd1.ClientID=cli.ClientID
left JOIN clients cl ON rcd1.Supplier = cl.ClientName
where cl.ClientName='".$Supplier."' and  cl.Type='W'  and rcd1.del_status != 2 and rcd1.st_reason='ASWAS' and rcd1.Wh_recieved_status = 0"); 
}




while($rows = $user_sql->fetch_assoc())
{

	$user_result['ClientID'] = $rows['ClientID'];
	$user_result['ProductName'] = $rows['ProductName'];
	$user_result['Manufacturer'] = $rows['Company'];
	$user_result['Pack'] = $rows['Pack'];
	$user_result['Wholesale_id'] = $rows['Wholesale_ID'];
	$user_result['Quantity'] = $rows['Quantity'];
	$user_result['OrderDate'] = $rows['OrderDate'];
	$user_result['OrderNo'] = $rows['OrderNo'];
    $all_users[] = $user_result;



}


$test = array('OrderByClient'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"OrderList Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 
	    
	    
	    
	     case 'getItemGeneralforcustomer':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_amenity=null;
	if( $data['item_name'] == '' or $data['ClientID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {


			$item_name=strip_tags(mysqli_real_escape_string($con,$data['item_name']));

			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));


$bookings_sql = $con->query("select product_name,ShortID,sum(stkqty) as stkqty,max(MRP) as MRP,max(SRate) as SRate from (

select product_name,manufacturer as ShortID,sum(purchase_quantity-sales_quantity) as stkqty,max(mrp) as MRP,max(Sales_Rate) as SRate from stock 
where product_name like '".$item_name."' and ClientID='".$ClientID."'
group by product_name,manufacturer
UNION
select Product_Name,short_id as ShortID,0 as stkqty,0 as MRP,0 as SRate from Product 
where product_name like '".$item_name."' and ClientID='".$ClientID."'
    )prdct  group by product_name,ShortID ORDER by 1;");





while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['product_name'];
$am_result['ShortID'] = $rows['ShortID'];
$am_result['stkqty'] = $rows['stkqty'];
$am_result['MRP'] = $rows['MRP'];
$am_result['SRate'] = $rows['SRate'];
$all_amenity[] = $am_result;
}


$test = array('All_StockClubbedCustomer'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	


}

echo json_encode($returnArr);		
	
break;
	    
	    
	        		case 'getProductDetailsbyNamecust':


					$data = json_decode(file_get_contents('php://input'), true);
					if( $data['Product_Name'] == '')
					{
						$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	
					}
	
					else {
					
						$Product_Name =$data['Product_Name'];
		
	$c = $con->query("SELECT MAX(MRP) as maxmrp ,SUM(Purchase_quantity -Sales_quantity) as stk ,uPack,manufacturer,Sales_Rate FROM `stock` WHERE Product_Name='".$Product_Name."' ");
	$c = $c->fetch_assoc();
	$test = array('Stock_Details'=>$c );
	
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	}
	
	
	
	
	
				
					echo json_encode($returnArr);	
	
	
	
	
	
					break;
	    
	    
	    	    
		case 'updatePlayerid':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['user_id'] == ''  or $data['player_id'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
$player_id = strip_tags(mysqli_real_escape_string($con,$data['player_id']));

$con->query("update user set  player_id='".$player_id."' where (id='".$user_id."')");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login updated ");  
}
 
echo json_encode($returnArr);
		
break; 
	    
	    
	    
	    
	    	    		case 'Forceuserlogout':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['user_id'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
 	$chekstudentid = $con->query("SELECT * FROM tbl_settings WHERE user_id='".$user_id."'")->fetch_assoc();
$app_login_count=$chekstudentid['enable_forcelogout'];

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$app_login_count);  

}
echo json_encode($returnArr);
		
break;
	    
	    		case 'getLastOrderId':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['date'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$date = strip_tags(mysqli_real_escape_string($con,$data['date']));

	$checkmob = $con->query("SELECT COALESCE(OrderNo,'0') as OrderNo FROM `received_orders1` WHERE ClientID='".$ClientID."' and OrderDate='".$date."' and st_reason IS  NULL and del_status !=  2 ORDER by OrderNo desc LIMIT 1");

	if($checkmob->num_rows != 0)
	{
	   	$chekstudentid = $con->query("SELECT OrderNo FROM `received_orders1` WHERE ClientID='".$ClientID."' and OrderDate='".$date."' and st_reason IS  NULL and del_status !=  2 ORDER by OrderNo desc LIMIT 1")->fetch_assoc(); 
	   	   $app_login_count=substr($chekstudentid['OrderNo'], -4);
	}
	else{
	    $app_login_count=0;
	}
 



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$app_login_count);  

}
echo json_encode($returnArr);
		
break; 
	
	    
	    
	    
	    	case 'getSalesReportbyRangeCustom':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		
		if($data['From_date'] == '' or $data['To_Range'] == '' or $data['From_dateprev'] == '' or $data['To_Rangeprev'] == '' or  $data['ClientID'] == '' or $data['Avgamount'] == '' or $data['cond'] == ''  )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$cond = strip_tags(mysqli_real_escape_string($con,$data['cond']));
			$Avgamount = strip_tags(mysqli_real_escape_string($con,$data['Avgamount']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
            $From_dateprev = strip_tags(mysqli_real_escape_string($con,$data['From_dateprev']));
			$To_Rangeprev = strip_tags(mysqli_real_escape_string($con,$data['To_Rangeprev']));
	
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);

            $timestampFromDateprev = strtotime($From_dateprev);
			$timestampToDateprev = strtotime($To_Rangeprev);
			
			
			$chekstudentid = $con->query("select SUM(grand_total) as ntot from sales1 where 1>0
			and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
		")->fetch_assoc();
			$class_id=$chekstudentid['ntot'];


            		
			$chekstudentidprev = $con->query("select sum(grand_total)/count(DISTINCT bill_date) as ntot from sales1 where 1>0
			and bill_date >='".date("Y-m-d", $timestampFromDateprev)."'
			and bill_date <='".date("Y-m-d", $timestampToDateprev)."'
			and ClientID='".$ClientID."'
		")->fetch_assoc();
			$class_idprev=$chekstudentidprev['ntot'];
			
	
			
	
		    if($cond=='1'){
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by bill_date asc");   
		    }
		    
		        else if($cond=='2'){
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by bill_date desc");   
		    }
		            else if($cond=='3'){
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by tot asc");   
		    }
		            else if($cond=='4') {
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by tot desc");   
		    }
		        else if($cond=='5') {
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag,(maxbill-minbill) as nbill from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by nbill asc");   
		    }
		    
		       else  {
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag,(maxbill-minbill) as nbill from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by nbill desc");   
		    }
		 
		


		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Bill Date'] = $rows['bill_date'];
			$user_result['Total Bill Amount'] = $rows['tot'];
			$user_result['Total Paid Amount'] = $rows['totnew'];
			$user_result['BillNo'] = $rows['billno'];
			$user_result['Minbill'] = $rows['minbill'];
			$user_result['Maxbill'] = $rows['maxbill'];
						$user_result['Flag'] = $rows['flag'];
	
			$all_users[] = $user_result;
		}

		$test = array('SalesReportbyRange'=>$all_users,"CurrentTotal"=>$class_id,"PreviousTotal"=>$class_idprev);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$class_id,"ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
		
		
	    
	    
	    	    	    
	    case 'getExpiryReportByItem':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '' or  $data['From_date'] == '' or $data['To_Range'] == '' or  $data['supplier'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$supplier=strip_tags(mysqli_real_escape_string($con,$data['supplier']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
				$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);

$bookings_sql = $con->query("select product_name,company_name,COALESCE(supplier_name,'') as supplier_name,stkqty,(ss.stkqty*PRate) as PAmt,(ss.stkqty*SRate) as SAmt from (

 select  product_name,manufacturer,sum(stkqty) as stkqty,max(PRate) as PRate,Max(SRate) as SRate from ( 
 select product_name,manufacturer,batch,expiry,(purchase_quantity-sales_quantity) as stkqty,unit_rate as PRate,sales_rate as SRate from stock where clientid ='".$ClientID."'
 and (purchase_quantity-sales_quantity)>0  and
 COALESCE(expiry,'1900-01-01') <='".date("Y-m-d", $timestampToDate)."'
 )stk group by product_name,manufacturer
    
) ss left join (
 
 
  
     select max(id) as id,clientid,item_description,company_name,supplier_name from (


Select COALESCE(max(((year(purchase_date)*3650000) + (month(purchase_date)*120000) + (day(purchase_date))+p.purchase_id) *100000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$ClientID."'   and p.ClientID ='".$ClientID."'   group by pi.clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$ClientID."'   and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name

Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."'   and ti.ClientID ='".$ClientID."'   group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."'  And ti.clientid='".$ClientID."'  group by ti.clientid,item_description,company_name,branch
 


) p4   group by clientid,item_description,company_name
 
     )supp on ss.product_name = supp.item_description and ss.manufacturer = supp.company_name
     WHERE supplier_name='".$supplier."'
    order by supplier_name"); 



while($rows = $bookings_sql->fetch_assoc())
{
$am_result['product_name'] = $rows['product_name'];
$am_result['company_name'] = $rows['company_name'];
$am_result['stkqty'] = $rows['stkqty'];
$am_result['PAmt'] = $rows['PAmt'];
$am_result['SAmt'] = $rows['SAmt'];
$all_amenity[] = $am_result;
}



$test = array('All_ExpiryByItem'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Expiry Product Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 
	    
	    
	    
	    	    
	    case 'getExpiryReportPrimary':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '' or  $data['From_date'] == '' or $data['To_Range'] == '' or  $data['supplier'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			
			
		
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$supplier=strip_tags(mysqli_real_escape_string($con,$data['supplier']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
				$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		
		
		if($supplier == '0'){
		  $bookings_sql = $con->query("select supplier_name,count(product_name) as cnt,sum(PAmt) as PAmt,sum(SAmt) as SAmt from (
    
select product_name,company_name,COALESCE(supplier_name,'') as supplier_name,stkqty,(ss.stkqty*PRate) as PAmt,(ss.stkqty*SRate) as SAmt from (

 select  product_name,manufacturer,sum(stkqty) as stkqty,max(PRate) as PRate,Max(SRate) as SRate from ( 
 select product_name,manufacturer,batch,expiry,(purchase_quantity-sales_quantity) as stkqty,unit_rate as PRate,sales_rate as SRate from stock where clientid ='".$ClientID."'
 and (purchase_quantity-sales_quantity)>0 and   
 COALESCE(expiry,'1900-01-01') <='".date("Y-m-d", $timestampToDate)."'
 )stk group by product_name,manufacturer
    
) ss left join (
 
 
  
     select max(id) as id,clientid,item_description,company_name,supplier_name from (


Select COALESCE(max(((year(purchase_date)*3650000) + (month(purchase_date)*120000) + (day(purchase_date))+p.purchase_id) *100000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$ClientID."'   and p.ClientID ='".$ClientID."'   group by pi.clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$ClientID."'   and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name

Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."'   and ti.ClientID ='".$ClientID."'   group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."'  And ti.clientid='".$ClientID."'  group by ti.clientid,item_description,company_name,branch
 


) p4  group by clientid,item_description,company_name
 
     )supp on ss.product_name = supp.item_description and ss.manufacturer = supp.company_name
    )cnt where supplier_name !='' group by supplier_name
    order by supplier_name");   
		}
		else{
		    
		    $bookings_sql = $con->query("select supplier_name,count(product_name) as cnt,sum(PAmt) as PAmt,sum(SAmt) as SAmt from (
    
select product_name,company_name,COALESCE(supplier_name,'') as supplier_name,stkqty,(ss.stkqty*PRate) as PAmt,(ss.stkqty*SRate) as SAmt from (

 select  product_name,manufacturer,sum(stkqty) as stkqty,max(PRate) as PRate,Max(SRate) as SRate from ( 
 select product_name,manufacturer,batch,expiry,(purchase_quantity-sales_quantity) as stkqty,unit_rate as PRate,sales_rate as SRate from stock where clientid ='".$ClientID."'
 and (purchase_quantity-sales_quantity)>0 and   
expiry <='".date("Y-m-d", $timestampToDate)."'
 )stk group by product_name,manufacturer
    
) ss left join (
 
 
  
     select max(id) as id,clientid,item_description,company_name,supplier_name from (


Select COALESCE(max(((year(purchase_date)*3650000) + (month(purchase_date)*120000) + (day(purchase_date))+p.purchase_id) *100000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$ClientID."'   and p.ClientID ='".$ClientID."'   group by pi.clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$ClientID."'   and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name

Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."'   and ti.ClientID ='".$ClientID."'   group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."'  And ti.clientid='".$ClientID."'  group by ti.clientid,item_description,company_name,branch
 


) p4  group by clientid,item_description,company_name
 
     )supp on ss.product_name = supp.item_description and ss.manufacturer = supp.company_name
    )cnt WHERE supplier_name='".$supplier."' group by supplier_name
    order by supplier_name"); 
		    
		}





while($rows = $bookings_sql->fetch_assoc())
{
$am_result['supplier_name'] = $rows['supplier_name'];
$am_result['cnt'] = $rows['cnt'];
$am_result['PAmt'] = $rows['PAmt'];
$am_result['SAmt'] = $rows['SAmt'];
$all_amenity[] = $am_result;
}



$test = array('All_Expiry'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Expiry Product Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
	    
	    
	    
	    
	    
	    case 'getAllStockByClientDemo':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '' or $data['item_name'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$item_name=strip_tags(mysqli_real_escape_string($con,$data['item_name']));

$bookings_sql = $con->query("select * from stock where ClientID='".$ClientID."' and Product_Name Like '".$item_name."' and Purchase_quantity-Sales_quantity > 0  GROUP BY Product_Name,Batch ORDER BY Product_Name ASC"); 



while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];
$am_result['Batch'] = $rows['Batch'];
$am_result['Expiry'] = $rows['Expiry'];
$am_result['Purchase_quantity'] = $rows['Purchase_quantity'];
$am_result['Sales_quantity'] = $rows['Sales_quantity'];
$am_result['uPack'] = $rows['uPack'];
$am_result['Unit_Rate'] = $rows['Unit_Rate'];
$am_result['Sales_Rate'] = $rows['Sales_Rate'];
$am_result['Manufacturer'] = $rows['manufacturer'];
$all_amenity[] = $am_result;
}



$test = array('All_Stock'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
	    
	    
	    case 'getClearedBills':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['Client_ID'] == ''  or $data['From_date'] == '' or $data['To_Range'] == ''  or $data['Type'] == '' or $data['user_id'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$Client_ID=strip_tags(mysqli_real_escape_string($con,$data['Client_ID']));
					$user_id=strip_tags(mysqli_real_escape_string($con,$data['user_id']));
					$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$Type = strip_tags(mysqli_real_escape_string($con,$data['Type']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
				$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		//CLEARED
		if($Type =='0' ){
		    
		    if($user_id =='0' ){
		        	$user_sql = $con->query("SELECT * FROM `Cleared_SalesInvoices` WHERE ClientID='".$Client_ID."' and Cleared_Date >='".date("Y-m-d", $timestampFromDate)."'  and Cleared_Date <='".date("Y-m-d", $timestampToDate)."' and Flag='CLEAR'");
		    }
		    else{
		       	$user_sql = $con->query("SELECT * FROM `Cleared_SalesInvoices` WHERE ClientID='".$Client_ID."' and Cleared_Date >='".date("Y-m-d", $timestampFromDate)."'  and Cleared_Date <='".date("Y-m-d", $timestampToDate)."' and Flag='CLEAR'"); 
		        
		    }
		    	
				  	 
		}
		else{
		   	
		    if($user_id =='0' ){
		        	$user_sql = $con->query("SELECT * FROM `Cleared_SalesInvoices` WHERE ClientID='".$Client_ID."' and Cleared_Date >='".date("Y-m-d", $timestampFromDate)."'  and Cleared_Date <='".date("Y-m-d", $timestampToDate)."' and Flag='DELETE'"); 
		}
		    
		    else{
		        
		       	$user_sql = $con->query("SELECT * FROM `Cleared_SalesInvoices` WHERE ClientID='".$Client_ID."' and Cleared_Date >='".date("Y-m-d", $timestampFromDate)."'  and Cleared_Date <='".date("Y-m-d", $timestampToDate)."' and Flag='DELETE'"); 
		} 
		    }
		   		
		   		
				  	
				
		  
				
			
		while($rows = $user_sql->fetch_assoc())
		{

			$user_result['Bill_No'] = $rows['Bill_No'];
			$user_result['Product'] = $rows['Product'];
			$user_result['Company'] = $rows['Company'];
			$user_result['Quantity'] = $rows['Quantity'];
			$user_result['Batch'] = $rows['Batch'];
			$user_result['Rate'] = $rows['Rate'];
			$user_result['MRP'] = $rows['MRP'];
			$user_result['User'] = '0';
			$user_result['Amount'] = $rows['Amount'];
			$user_result['Cleared_Date'] = $rows['Cleared_Date'];
			$user_result['Cleared_Time'] = $rows['Cleared_Time'];
			$user_result['Flag'] = $rows['Flag'];
			$user_result['Computer_Name'] = $rows['Computer_Name'];;
			$all_users[] = $user_result;
		}

		$test = array('ClearedBills'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    
	    case 'addShopsortorder':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['ClientID'] == '' or $data['MClientID'] == '' or $data['sortid'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$MClientID = strip_tags(mysqli_real_escape_string($con,$data['MClientID']));
$sortid = strip_tags(mysqli_real_escape_string($con,$data['sortid']));

    $checkexist = $con->query("select * from tbl_shop_sorting where ClientID='".$ClientID."' and Managed_ClientID='".$MClientID."'");
    
    if($checkexist->num_rows != 0)
{
    
    $con->query("update tbl_shop_sorting set sort_id='".$sortid."' where ClientID='".$ClientID."' and   Managed_ClientID='".$MClientID."' ");
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Shop already assigned to client");
}
else{
    
    
  	$con->query("insert into tbl_shop_sorting(`ClientID`,`Managed_ClientID`,`sort_id`)values('".$ClientID."','".$MClientID."','".$sortid."')");

	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Assign Request added Successfully!");  
}
    




}

echo json_encode($returnArr);	



break;
	    
	    
	    case 'IsCusinappupdateavailable':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['versioncode'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$versioncode=strip_tags(mysqli_real_escape_string($con,$data['versioncode']));
		$checkversioncode = $con->query("select * from tbl_cusInappupdates
	")->fetch_assoc();
		$vcode=$checkversioncode['VersionCode'];

		if($versioncode < $vcode ){
		 	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Update avaialble");	   
		}
		else{
		  	$returnArr = array("ResponseCode"=>"200","Result"=>"false","ResponseMsg"=>"No updates avaialble"); 
		}

		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	     	case 'updatClientlocation':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['latitude'] == '' or $data['longitude'] == '' or $data['ClientID'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$latitude= strip_tags(mysqli_real_escape_string($con,$data['latitude']));
$longitude =strip_tags(mysqli_real_escape_string($con,$data['longitude']));
$ClientID =strip_tags(mysqli_real_escape_string($con,$data['ClientID']));


$con->query("update clients set Lat='".$latitude."',Lng='".$longitude."' where ClientID='".$ClientID."' ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Location Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;
	    
	    
	    
	     case 'getItemAvailabilityForAswas':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['item_name'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$item_name=strip_tags(mysqli_real_escape_string($con,$data['item_name']));
			
		    	
				  		$user_sql = $con->query("SELECT p.product_name,short_id,p.ClientID,Clientname,Location,stockqty FROM Product p left join ( select ClientID,clientname,Location from clients )c  on p.ClientID = c.clientid 
left join ( select ClientID,purchase_quantity-sales_quantity as stockqty,Product_Name,manufacturer from stock ) st on p.clientid = st.clientid and c.clientid = st.clientid and p.Product_Name = st.product_name 
and p.Short_ID = st.manufacturer
where p.product_name like '".$item_name."' and Clientname is not null order by stockqty");
		
		
		  
			
		while($rows = $user_sql->fetch_assoc())
		{

			$user_result['ClientID'] = $rows['ClientID'];
			$user_result['Product_Name'] = $rows['product_name'];
			$user_result['short_id'] = $rows['short_id'];
			$user_result['ClientName'] = $rows['clientname'];
			$user_result['stockqty'] = $rows['stockqty'];
				$user_result['Location'] = $rows['Location'];
			
			$all_users[] = $user_result;
		}

		$test = array('ItemAvailabilityInfo'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    
	    	    case 'getGenericItembyproduct':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_amenity=null;
	if($data['email'] == '' or $data['item_name'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {

	$email=strip_tags(mysqli_real_escape_string($con,$data['email']));
			$item_name=strip_tags(mysqli_real_escape_string($con,$data['item_name']));


$bookings_sql = $con->query("select distinct GPLast.EnteredProduct,GPLast.EnteredComp,GPLast.GenProduct,GPLast.GenComp,COALESCE(stkqty,0) as stkqty from ( 
 select *  from ( 

select product_name as EnteredProduct,company_name as EnteredComp,ClientID as EnteredClientID, GROUP_CONCAT(distinct combgeneric_name ) Gen1 From GenericCombination_Products
     where Product_Name ='".$item_name."'  
group by Product_Name
     
 )GP1 left join ( 

select product_name as GenProduct,company_name as GenComp,ClientID as GenClientID, GROUP_CONCAT(distinct combgeneric_name ) Gen2 From GenericCombination_Products  
group by Product_Name
     
  )GP2 on GP1.Gen1 = GP2.Gen2  
  
 )GPLast 
 left join ( select product_name,manufacturer,sum(purchase_quantity-sales_quantity) as stkqty,clientid from stock WHERE clientid in ( select distinct clients.clientid from tbl_assigned_shops JOIN clients ON tbl_assigned_shops.Managed_ClientID=clients.ClientID JOIN user ON tbl_assigned_shops.ClientID=user.userid where user.UserName=('".$email."')) 
            
            group by product_name )stk on stk.product_name = GPLast.genproduct and stk.manufacturer = GPLast.gencomp where 1>0 
Having COALESCE(stkqty,0) > 0");


while($rows = $bookings_sql->fetch_assoc())
{
$am_result['EnteredProduct'] = $rows['EnteredProduct'];
$am_result['EnteredComp'] = $rows['EnteredComp'];
$am_result['GenProduct'] = $rows['GenProduct'];
$am_result['GenComp'] = $rows['GenComp'];
$am_result['stkqty'] = $rows['stkqty'];
$all_amenity[] = $am_result;
}



$test = array('AllGeneric'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	


}

echo json_encode($returnArr);		
	
break;
	    
	    
	    	    	    
	    case 'getItemAvailabilitySearchPrimary':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_amenity=null;
	if( $data['item_name'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {


			$item_name=strip_tags(mysqli_real_escape_string($con,$data['item_name']));



$bookings_sql = $con->query(" SELECT DISTINCT Product_Name FROM Product WHERE Product_Name  LIKE  '".$item_name."'");





while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['Product_Name'];;
$all_amenity[] = $am_result;
}



$test = array('All_StockClubbed'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	


}

echo json_encode($returnArr);		
	
break;
	    
	    
	        
	      	       case 'getItemAvailabilitySearch':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['item_name'] == '' or $data['ClientID'] == '' or $data['MClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
	
	
	
			$item_name=strip_tags(mysqli_real_escape_string($con,$data['item_name']));
		    	
		   $ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		       $MClientID=strip_tags(mysqli_real_escape_string($con,$data['MClientID']));
		    	if($ClientID =='0'){
		    	    
		    	     $user_sql = $con->query("select 1 as flag,COALESCE(tablesort,999999) as tablesort,product_name,manufacturer as short_id,clientid,clientname,Location,Area,Phone,sum(stockqty) as stockqty,MRP,uPack,Sales_Rate,LastUpdateDt,sort_id from ( select product_name,manufacturer,batch,c.clientid,clientname,type2,(purchase_quantity-sales_quantity) as stockqty,Location,Area,Phone,MRP,uPack,Sales_Rate,LastUpdateDt,c.sort_id,tss.sort_id as tablesort from stock s left join clients c on s.ClientID = c.clientid left join ( select username,max(dt) as LastUpdateDt from onlinelog group by username )dd on s.ClientID = dd.username and c.ClientID = dd.username 
left join tbl_shop_sorting tss on c.ClientID = tss.Managed_ClientID 
where (purchase_quantity-sales_quantity) >0 and c.clientid and product_name =  '".$item_name."' and tss.ClientID ='".$MClientID."'  )cl group by clientname,clientid,product_name,manufacturer 


UNION 
select 2 as flag,999999 as tablesort,product_name,manufacturer as short_id,c.clientid,clientname,Location,Area,Phone,sum(purchase_quantity-sales_quantity) as stockqty,MRP,uPack,Sales_Rate,LastUpdateDt,sort_id from clients c left join stock s on c.clientid = s.ClientID 
left join ( select username,max(dt) as LastUpdateDt from onlinelog group by username )dd on c.ClientID = dd.username and s.ClientID = dd.username 
where (purchase_quantity-sales_quantity) >0 and c.clientid and product_name = '".$item_name."' and c.ClientID not in (  select distinct Managed_ClientID from tbl_shop_sorting ) 

group by product_name,manufacturer,c.clientid,clientname,Location,Area,Phone,MRP,uPack,Sales_Rate,LastUpdateDt,sort_id

order by flag,COALESCE(tablesort,999999) asc,stockqty desc,sort_id asc;"); 
		    	}
		    	
		    	else{
		    	    
		    	      $user_sql = $con->query("select 1 as flag,COALESCE(tablesort,999999) as tablesort,product_name,manufacturer as short_id,clientid,clientname,Location,Area,Phone,sum(stockqty) as stockqty,MRP,uPack,Sales_Rate,LastUpdateDt,sort_id from ( select product_name,manufacturer,batch,c.clientid,clientname,type2,(purchase_quantity-sales_quantity) as stockqty,Location,Area,Phone,MRP,uPack,Sales_Rate,LastUpdateDt,c.sort_id,tss.sort_id as tablesort from stock s left join clients c on s.ClientID = c.clientid left join ( select username,max(dt) as LastUpdateDt from onlinelog group by username )dd on s.ClientID = dd.username and c.ClientID = dd.username 
left join tbl_shop_sorting tss on c.ClientID = tss.Managed_ClientID 
where (purchase_quantity-sales_quantity) >0 and c.clientid and product_name =  '".$item_name."' and s.clientid='".$ClientID."' and c.clientid='".$ClientID."' and tss.ClientID ='".$MClientID."'  )cl group by clientname,clientid,product_name,manufacturer 


UNION 
select 2 as flag,999999 as tablesort,product_name,manufacturer as short_id,c.clientid,clientname,Location,Area,Phone,sum(purchase_quantity-sales_quantity) as stockqty,MRP,uPack,Sales_Rate,LastUpdateDt,sort_id from clients c left join stock s on c.clientid = s.ClientID 
left join ( select username,max(dt) as LastUpdateDt from onlinelog group by username )dd on c.ClientID = dd.username and s.ClientID = dd.username 
where (purchase_quantity-sales_quantity) >0 and c.clientid and product_name = '".$item_name."' and s.clientid='".$ClientID."' and c.clientid='".$ClientID."' and c.ClientID not in (  select distinct Managed_ClientID from tbl_shop_sorting ) 

group by product_name,manufacturer,c.clientid,clientname,Location,Area,Phone,MRP,uPack,Sales_Rate,LastUpdateDt,sort_id

order by flag,COALESCE(tablesort,999999) asc,stockqty desc,sort_id asc;");
		    	    
		    	}
		    	   
		    
		
				  		
		
		
	
		while($rows = $user_sql->fetch_assoc())
		{

			$user_result['ClientID'] = $rows['clientid'];
			$user_result['Product_Name'] = $rows['product_name'];
			$user_result['short_id'] = $rows['short_id'];
			$user_result['ClientName'] = $rows['clientname'];
			$user_result['stockqty'] = $rows['stockqty'];
			$user_result['Location'] = $rows['Location'];
			$user_result['Area'] = $rows['Area'];
			$user_result['MRP'] = $rows['MRP'];
			$user_result['uPack'] = $rows['uPack'];
			$user_result['Sales_Rate'] = $rows['Sales_Rate'];
			$user_result['Phone'] = $rows['Phone'];
			$user_result['LastUpdateDt'] = $rows['LastUpdateDt'];
			$all_users[] = $user_result;
		}

		$test = array('ItemAvailabilityInfo'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    	case 'updateorderreasondelete':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['reason'] == '' or $data['orderNo'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$reason= strip_tags(mysqli_real_escape_string($con,$data['reason']));
$orderNo =strip_tags(mysqli_real_escape_string($con,$data['orderNo']));


$con->query("update received_orders1 set st_reason='".$reason."',del_status=1 where orderNo='".$orderNo."' ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;
		
		
			    	case 'cancelreshedule':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['ClientTo'] == '' or $data['OrderID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID= strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$ClientTo =strip_tags(mysqli_real_escape_string($con,$data['ClientTo']));
$OrderID =strip_tags(mysqli_real_escape_string($con,$data['OrderID']));

$con->query("delete from customer_orders where Order_Id='".$OrderID."' and ClientID='".$ClientTo."'");

if($con){
    
  $con->query("update customer_orders set sh_from='0',sh_to='0',Status='N'   where Order_Id='".$OrderID."' and ClientID='".$ClientID."'   ");  
}



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;
	    
	    
	    
	    
	    	            	case 'updateorderreason':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['reason'] == '' or $data['orderNo'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$reason= strip_tags(mysqli_real_escape_string($con,$data['reason']));
$orderNo =strip_tags(mysqli_real_escape_string($con,$data['orderNo']));


$con->query("update received_orders1 set st_reason='".$reason."' where orderNo='".$orderNo."' ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;
	    
	    
	    	    
	    case 'getAllItemForMerge':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_amenity=null;
if($data['ClientID'] == '' or $data['Supplier'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {


$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Supplier=strip_tags(mysqli_real_escape_string($con,$data['Supplier']));


$bookings_sql = $con->query("select distinct item_description,company_name,supplier_name from ( select distinct item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi on p.purchase_id= pi.purchase_id and p.ClientID= pi.ClientID where p.ClientID ='".$ClientID."' and pi.ClientID ='".$ClientID."' and supplier_name ='".$Supplier."' and item_description not in ( select distinct product_name from PharmApp_Substitutes ) UNION select distinct item_description,company_name,supplier_name from opening_stock1 where ClientID ='".$ClientID."' and supplier_name ='".$Supplier."' and item_description not in ( select distinct product_name from PharmApp_Substitutes ) )supp order by 1 Limit 10"); 




while($rows = $bookings_sql->fetch_assoc())
{
$am_result['item_description'] = $rows['item_description'];
$am_result['company_name'] = $rows['company_name'];
$am_result['supplier_name'] = $rows['supplier_name'];
$all_amenity[] = $am_result;
}



$test = array('All_ItemMerge'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	

	

	


}

echo json_encode($returnArr);		
	
break;
	    
	    	    
	    
	    	    case 'Isinappupdateavailable':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['versioncode'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$versioncode=strip_tags(mysqli_real_escape_string($con,$data['versioncode']));
		$checkversioncode = $con->query("select * from tbl_Inappupdates
	")->fetch_assoc();
		$vcode=$checkversioncode['VersionCode'];

		if($versioncode < $vcode  ){
		 	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Update avaialble");	   
		}
		else{
		  	$returnArr = array("ResponseCode"=>"200","Result"=>"false","ResponseMsg"=>"No updates avaialble"); 
		}

		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	    
	    case 'getProductDetailsForPOrder':


				$data = json_decode(file_get_contents('php://input'), true);
				if($data['ClientID'] == '' or $data['Supplier_name'] == '' or $data['item_description'] == '')
				{
					$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");

				}

				else {
					$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
					$item_description = strip_tags(mysqli_real_escape_string($con,$data['item_description']));
					$Supplier_Name = strip_tags(mysqli_real_escape_string($con,$data['Supplier_name']));

$c = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate,COALESCE(stk,0) as stk,PRate_Pack,mrpPack,supplier_name
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(COALESCE(stk,0)))/max(COALESCE(pack,0))) as reqqty,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack
from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,mrp from (

    
Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

    
   
select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and s.clientid='".$ClientID."'  
and si.clientid='".$ClientID."'  
     and item_description ='".$item_description."'

 
    
) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$ClientID."'  
      and product_name ='".$item_description."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(


Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$ClientID."'   and p.ClientID ='".$ClientID."'    
 and item_description ='".$item_description."' and supplier_name ='".$Supplier_Name."'       
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$ClientID."'   and COALESCE(supplier_name,'')<>''
and item_description ='".$item_description."' and supplier_name ='".$Supplier_Name."'       

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$ClientID."'   and p.ClientID ='".$ClientID."'  and item_description ='".$item_description."' and supplier_name ='".$Supplier_Name."'        group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$ClientID."'   and COALESCE(supplier_name,'')<>'' and item_description ='".$item_description."' and supplier_name ='".$Supplier_Name."'        group by clientid,item_description,company_name,supplier_name
 
) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$ClientID."'    
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0
) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
 
where c.type='R' 
)onea group by item_description,company_name    
 
)sqtywithstk   where item_description ='".$item_description."' and supplier_name ='".$Supplier_Name."'   
           group by  item_description   
order by  1 ");
$c = $c->fetch_assoc();
$test = array('Porderp_details'=>$c );
$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Item details","ResultData"=>$test);





				}
				

				echo json_encode($returnArr);	





				break;
	    
	    
	    
	    case 'getSupplierSortOrder':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['sort_count'] == '' or $data['ClientID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{

$invoice_no="0";
$sort_count = strip_tags(mysqli_real_escape_string($con,$data['sort_count']));
$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$checkProductname = $con->query("select * from supplier where sort_id='".$sort_count."' and ClientID='".$ClientID."'")->fetch_assoc();
if($checkProductname >0){
  $invoice_no=$checkProductname['Supplier_Name'];  
}

if($invoice_no==null){
  $returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"0");  
}
else{
    $returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$invoice_no);
}




}

echo json_encode($returnArr);	



break;
	    
	    
	    
	            	case 'updateuserpwd':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['mobile'] == '' or $data['password'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$password= strip_tags(mysqli_real_escape_string($con,$data['password']));
$mobile =strip_tags(mysqli_real_escape_string($con,$data['mobile']));
$hashpwd=md5($password);;


$con->query("update user set PassWord='".$hashpwd."' where Mobile='".$mobile."' ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;
	    
	    
	    
	    case 'isUserExist':

$data = json_decode(file_get_contents('php://input'), true);


if(  $data['mobile'] == '' ) 
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {

$mobile =strip_tags(mysqli_real_escape_string($con,$data['mobile']));


	$checkmob = $con->query("select * from user where Mobile='".$mobile."'");

	if($checkmob->num_rows != 0)
	{
$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Account Already exist please login to proceed");
	}
	else{

	
	
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"No Account associated with this mobile no:!");

	}



}


echo json_encode($returnArr);
break;
	    
	    
	      	case 'isSuppliersortupdate':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['Supplier_Name'] == '' or $data['count'] == ''    )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Supplier_Name = strip_tags(mysqli_real_escape_string($con,$data['Supplier_Name']));
$count = strip_tags(mysqli_real_escape_string($con,$data['count']));


$con->query("update supplier set sort_id='".$count."' where ClientID='".$ClientID."' and Supplier_Name='".$Supplier_Name."'");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;
	    
	    
	    
	    
	    case 'getAllStockByClientLikeCustomerMain':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_amenity=null;
if($data['ClientID'] == '' or $data['Pattn'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {


$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Pattn=strip_tags(mysqli_real_escape_string($con,$data['Pattn']));

if($ClientID =='0')
{
$bookings_sql = $con->query("select * from stock WHERE LOWER(Product_Name) LIKE '".$Pattn."%' GROUP BY Product_Name  ORDER BY Product_Name"); 
}
else{
/*$bookings_sql = $con->query("select * from stock where ClientID='".$ClientID."' and LOWER(Product_Name) LIKE '".$Pattn."%' and Purchase_quantity-Sales_quantity > 0 GROUP BY Product_Name  ORDER BY Product_Name "); */

$bookings_sql = $con->query("select * from stock where ClientID='".$ClientID."' and LOWER(Product_Name) LIKE '".$Pattn."' and  (Purchase_quantity -Sales_quantity)>0 GROUP BY Product_Name  ORDER BY Product_Name  "); 
}



while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];
$am_result['Batch'] = $rows['Batch'];
$am_result['Expiry'] = $rows['Expiry'];
$am_result['Purchase_quantity'] = $rows['Purchase_quantity'];
$am_result['Sales_quantity'] = $rows['Sales_quantity'];
$am_result['uPack'] = $rows['uPack'];
$am_result['Unit_Rate'] = $rows['Unit_Rate'];
$am_result['Sales_Rate'] = $rows['Sales_Rate'];
$am_result['Manufacturer'] = $rows['manufacturer'];

$all_amenity[] = $am_result;
}



$test = array('All_Stock'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	

	

	


}

echo json_encode($returnArr);		
	
break; 	

	    
	    
	    		case 'getMobilecountbyid':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['user_id'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
 	$chekstudentid = $con->query("SELECT app_login_count FROM user WHERE id='".$user_id."'")->fetch_assoc();
$app_login_count=$chekstudentid['app_login_count'];

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$app_login_count);  

}
echo json_encode($returnArr);
		
break; 
	   
	    
	    
	    
		case 'isLoginCount̥update':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['user_id'] == '' or $data['status'] == ''  or $data['authentication'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
$authentication = strip_tags(mysqli_real_escape_string($con,$data['authentication']));
$app_login_count=0;

if($authentication =='1'){
     $con->query("update user set app_login_count='".$status."'  where (id='".$user_id."')");
if($con){
     $con->query("update tbl_settings set enable_forcelogout='0' where (user_id='".$user_id."')");
}
$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login updated ");
}
else{
    	$chekstudentid = $con->query("SELECT max_users,user.app_login_count FROM `tbl_settings` JOIN user on tbl_settings.user_id=user.id WHERE user.id='".$user_id."' and user_id='".$user_id."'")->fetch_assoc();
$max_users=$chekstudentid['max_users'];
$app_login_count=$chekstudentid['app_login_count'];
if($max_users == $app_login_count ){
    
 $returnArr = array("ResponseCode"=>"200","Result"=>"false","ResponseMsg"=>"Max user exceeds");     
}
else{
    $y=$app_login_count+1;
  $con->query("update user set app_login_count='".$y."' where (id='".$user_id."')");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login updated ");  
}
 
}


		  

}
echo json_encode($returnArr);
		
break; 
	    
	    
	    
	    
	    	    	      case 'getSalesInfoByCustomerMobProducts':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['Client_ID'] == '' or $data['Bill_no'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$Client_ID=strip_tags(mysqli_real_escape_string($con,$data['Client_ID']));
				$Bill_no=strip_tags(mysqli_real_escape_string($con,$data['Bill_no']));
		
		    	
				  		$user_sql = $con->query("select * from Customer_Product where Client_ID='".$Client_ID."' and Bill_No='".$Bill_no."' group  by Product_name asc ");
		
		
		  
			
		while($rows = $user_sql->fetch_assoc())
		{

			$user_result['Product_name'] = $rows['Product_name'];
			$user_result['Company_Name'] = $rows['Company_Name'];
			$user_result['Rack_No'] = $rows['Rack_No'];
			$user_result['Course'] = $rows['Course'];
			$user_result['Period'] = $rows['Period'];
			$user_result['Qty'] = $rows['Qty'];
			$user_result['Narration'] = $rows['Narration'];
			$user_result['Date'] = $rows['Date'];
			$user_result['Bill_No'] = $rows['Bill_No'];
			$user_result['YearID'] = $rows['YearID'];
			$user_result['Remainder_Date'] = $rows['Remainder_Date'];
			$user_result['Required_Date'] = $rows['Required_Date'];
			$user_result['Duration'] = $rows['Duration'];
			$user_result['Doctor_Name'] = $rows['Doctor_Name'];
			$user_result['Patient_Name'] = $rows['Patient_Name'];
			$user_result['Bill_Date'] = $rows['Bill_Date'];
			$all_users[] = $user_result;
		}

		$test = array('SalescustomerInfo'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    
	    	      case 'getSalesInfoByCustomerMob':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['Client_ID'] == '' or $data['Customer_mob'] == '' or $data['From_date'] == '' or $data['To_Range'] == ''  or $data['Type'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$Client_ID=strip_tags(mysqli_real_escape_string($con,$data['Client_ID']));
				$Customer_mob=strip_tags(mysqli_real_escape_string($con,$data['Customer_mob']));
					$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$Type = strip_tags(mysqli_real_escape_string($con,$data['Type']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
				$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		
		if($Type =='1'){
		    	
				  		$user_sql = $con->query("select * from Customer_Product where Client_ID='".$Client_ID."' and Bill_No='".$Customer_mob."' group by Bill_No order by Date asc ");
		}
		else{
		   	
				  		$user_sql = $con->query("select * from Customer_Product where Client_ID='".$Client_ID."' and Bill_No='".$Customer_mob."' and Date >='".date("Y-m-d", $timestampFromDate)."' and Date <='".date("Y-m-d", $timestampToDate)."' group by Bill_No order by Date asc  "); 
		}
				
		  
				
			
		while($rows = $user_sql->fetch_assoc())
		{

			$user_result['Product_name'] = $rows['Product_name'];
			$user_result['Company_Name'] = $rows['Company_Name'];
			$user_result['Rack_No'] = $rows['Rack_No'];
			$user_result['Course'] = $rows['Course'];
			$user_result['Period'] = $rows['Period'];
			$user_result['Qty'] = $rows['Qty'];
			$user_result['Narration'] = $rows['Narration'];
			$user_result['Date'] = $rows['Date'];
			$user_result['Bill_No'] = $rows['Bill_No'];
			$user_result['YearID'] = $rows['YearID'];
			$user_result['Remainder_Date'] = $rows['Remainder_Date'];
			$user_result['Required_Date'] = $rows['Required_Date'];
			$user_result['Duration'] = $rows['Duration'];
			$user_result['Doctor_Name'] = $rows['Doctor_Name'];
			$user_result['Patient_Name'] = $rows['Patient_Name'];
			$user_result['Bill_Date'] = $rows['Bill_Date'];
			$all_users[] = $user_result;
		}

		$test = array('SalescustomerInfo'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    
	    
	    		case 'del_FromPorderreq';

	    
	$data = json_decode(file_get_contents('php://input'), true);
	if($data['id'] == ''  )
	{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	}

	else{

		$id = strip_tags(mysqli_real_escape_string($con,$data['id']));
		$con->query("delete from received_orders1  where OrderNo='".$id."'  ");

		
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Item Deleted successfully ");


		echo json_encode($returnArr);	

	}
			



	break;
	    
	    
	    
	    	    
	    	case 'getSupplierbyspname':


			$data = json_decode(file_get_contents('php://input'), true);
			if($data['ClientID'] == '' or $data['Supplier'] == '' )
			{
			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
			}
			
			else {
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$Supplier=strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
	    		
  $c = $con->query("SELECT * from PharmApp_Sp_Substitutes where ClientID='".$ClientID."' and Supplier_Name='".$Supplier."'");

$c = $c->fetch_assoc();
$test = array('PSupplierList'=>$c );

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);
}


			echo json_encode($returnArr);	

			break;
	    
	    
	    
	    
	   	case 'addToSpsubstitutes':
				
			$data = json_decode(file_get_contents('php://input'), true);
		 
			
if($data['ClientID'] == '' or $data['Pharmapp_Supplier'] == ''  or $data['Supplier_Name'] == '' or $data['SupplierId'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Pharmapp_Supplier = strip_tags(mysqli_real_escape_string($con,$data['Pharmapp_Supplier']));
$Supplier_Name = strip_tags(mysqli_real_escape_string($con,$data['Supplier_Name']));
$SupplierId = strip_tags(mysqli_real_escape_string($con,$data['SupplierId']));

$user_sql = $con->query("SELECT * FROM `PharmApp_Sp_Substitutes` where Supplier_Name='".$Supplier_Name."' and ClientID ='".$ClientID."' and Pharmapp_Supplier='".$Pharmapp_Supplier."'");
	if($user_sql->num_rows != 0){
	   $returnArr = array("ResponseCode"=>"200","Result"=>"false","ResponseMsg"=>"Supplier substitute already exist!"); 
	}
	else{
	   $con->query("insert into PharmApp_Sp_Substitutes(`ClientID`,`Pharmapp_Supplier`,`Supplier_Name`,`SupplierId`)values
('".$ClientID."','".$Pharmapp_Supplier."','".$Supplier_Name."','".$SupplierId."')");

if($con){
 $returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Supplier substitute兩 added Successfully!");     
}
 
	}




}

echo json_encode($returnArr);	

 

	break;
	    
	      case 'getStockVerificationReport':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['Client_ID'] == '' or $data['view'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$Client_ID=strip_tags(mysqli_real_escape_string($con,$data['Client_ID']));
				$view=strip_tags(mysqli_real_escape_string($con,$data['view']));
				
				if($view =='1'){
				  		$user_sql = $con->query("select Id, sv.clientid,dt,productname,sv.manufacturer,actualstock,verifiedstock,trigdt,trigtm,unit_rate,(purchase_quantity-sales_quantity) as stockqty,(ActualStock-VerifiedStock) as reqstock,(unit_rate*ActualStock) as actualrate,(unit_rate*verifiedstock) as verifiedrate from StockVerification sv 
left join stock s on sv.ClientID = s.ClientID and sv.ProductName = s.Product_Name and sv.Manufacturer=s.manufacturer 
where sv.clientid ='".$Client_ID."' and s.clientid ='".$Client_ID."' and verifiedstock >0 group by Id desc");  
				}
				else{
				    		$user_sql = $con->query("select Id, sv.clientid,dt,productname,sv.manufacturer,actualstock,verifiedstock,trigdt,trigtm,unit_rate,(purchase_quantity-sales_quantity) as stockqty,(ActualStock-VerifiedStock) as reqstock,(unit_rate*ActualStock) as actualrate,(unit_rate*verifiedstock) as verifiedrate from StockVerification sv 
left join stock s on sv.ClientID = s.ClientID and sv.ProductName = s.Product_Name and sv.Manufacturer=s.manufacturer 
where sv.clientid ='".$Client_ID."' and s.clientid ='".$Client_ID."' and Id ='".strip_tags(mysqli_real_escape_string($con,$data['Id']))."' and verifiedstock >0 group by productname");
				}
	



		while($rows = $user_sql->fetch_assoc())
		{

			$user_result['clientid'] = $rows['clientid'];
			$user_result['Id'] = $rows['Id'];
			$user_result['dt'] = $rows['dt'];
			$user_result['productname'] = $rows['productname'];
			$user_result['manufacturer'] = $rows['manufacturer'];
			$user_result['actualstock'] = $rows['actualstock'];
			$user_result['verifiedstock'] = $rows['verifiedstock'];
			$user_result['trigdt'] = $rows['trigdt'];
			$user_result['trigtm'] = $rows['trigtm'];
			$user_result['unit_rate'] = $rows['unit_rate'];
			$user_result['stockqty'] = $rows['stockqty'];
			$user_result['reqstock'] = $rows['reqstock'];
			$user_result['actualrate'] = $rows['actualrate'];
			$user_result['verifiedrate'] = $rows['verifiedrate'];
			$all_users[] = $user_result;
		}

		$test = array('StockVerificationReport'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    	  
	    
	    		  	case 'isPackageUpdate':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['user_id'] == '' or $data['pack'] == ''    )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
$pack = strip_tags(mysqli_real_escape_string($con,$data['pack']));


$con->query("update user set Package_ID='".$pack."' where id='".$user_id."'");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Notes saved successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;

	    
	    
	    	    
	    	case 'addToReceivedODHistory':
				
			$data = json_decode(file_get_contents('php://input'), true);
		 
			
if($data['ClientID'] == '' or $data['OrderNo'] == ''  or $data['OrderDate'] == '' or $data['Supplier'] == '' 
or $data['ProductName'] == '' or $data['Company'] == '' or $data['Pack'] == '' or $data['Quantity'] == '' 
or $data['TotalQuantity'] == '' or $data['Stock'] == '' or $data['SalesQuantity'] == '' or $data['Status'] == ''
or $data['Rate'] == '' or $data['unitRate'] == '' or $data['insertnew'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$OrderNo = strip_tags(mysqli_real_escape_string($con,$data['OrderNo']));
$OrderDate = strip_tags(mysqli_real_escape_string($con,$data['OrderDate']));
$Supplier = strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
$ProductName = strip_tags(mysqli_real_escape_string($con,$data['ProductName']));
$Company = strip_tags(mysqli_real_escape_string($con,$data['Company']));
$Pack = strip_tags(mysqli_real_escape_string($con,$data['Pack']));
$Quantity = strip_tags(mysqli_real_escape_string($con,$data['Quantity']));
$TotalQuantity = strip_tags(mysqli_real_escape_string($con,$data['TotalQuantity']));
$Stock = strip_tags(mysqli_real_escape_string($con,$data['Stock']));
$SalesQuantity = strip_tags(mysqli_real_escape_string($con,$data['SalesQuantity']));
$Status = strip_tags(mysqli_real_escape_string($con,$data['Status']));
$Rate = strip_tags(mysqli_real_escape_string($con,$data['Rate']));
$unitRate = strip_tags(mysqli_real_escape_string($con,$data['unitRate']));
$insertnew = strip_tags(mysqli_real_escape_string($con,$data['insertnew']));
$org = strip_tags(mysqli_real_escape_string($con,$data['org']));

if($insertnew =='1'){
    	$con->query("delete from received_orders1  where OrderNo='".$OrderNo."'  and ProductName='".$ProductName."' ");
  $con->query("insert into received_orders1(`ClientID`,`OrderNo`,`OrderDate`,`Supplier`,
`ProductName`,`Company`,`Pack`,`Quantity`,`TotalQuantity`,`Status`,`Rate`,`unitRate`,`Stock`,`SalesQuantity`,`org`)values
('".$ClientID."','".trim($OrderNo )."','".$OrderDate."','".$Supplier."','".$ProductName."',
'".$Company."','".$Pack."','".$Quantity."','".$TotalQuantity."','".$Status."','".$Rate."','".$unitRate."','".$Stock."','".$SalesQuantity."','".$org."')");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"New Purchase order has been added Successfully!");  
    
}
else{
    
    $con->query("update received_orders1 set ClientID ='".$ClientID."' ,OrderNo='".trim($OrderNo)."' ,OrderDate='".$OrderDate."' 

,Supplier='".$Supplier."' ,ProductName='".$ProductName."' ,Company='".$Company."' ,Pack='".$Pack."' ,Quantity='".$Quantity."'

,TotalQuantity='".$TotalQuantity."' ,Status='".$Status."' ,Rate='".$Rate."' ,unitRate='".$unitRate."' ,Stock='".$Stock."'

,SalesQuantity='".$SalesQuantity."' where ProductName='".$ProductName."' and OrderNo='".$OrderNo."'"); 


$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Purchase order has been updated Successfully!");
    
}






}

echo json_encode($returnArr);	

 

	break;
	    
	    
	    
	    	    	    case 'getExistingProductStatus':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['OrderNo'] == '' or $data['ClientID'] == '' or $data['Item_Description'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$OrderNo=strip_tags(mysqli_real_escape_string($con,$data['OrderNo']));
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$Item_Description=strip_tags(mysqli_real_escape_string($con,$data['Item_Description']));
		$Status_pro="";

		$user_sql = $con->query("SELECT * FROM `received_orders1` where OrderNo='".$OrderNo."' and ClientID ='".$ClientID."' and ProductName='".$Item_Description."'  and OrderID IS NULL GROUP by OrderNo");
		if($user_sql->num_rows != 0)
{
 
    	while($rows = $user_sql->fetch_assoc())
		{

				$user_result['ClientID'] = $rows['ClientID'];
		$user_result['OrderNo'] = $rows['OrderNo'];
		$user_result['Supplier'] = $rows['Supplier'];
		$user_result['ProductName'] = $rows['ProductName'];
		$user_result['Company'] = $rows['Company'];
		$user_result['Pack'] = $rows['Pack'];
		$user_result['Quantity'] = $rows['Quantity'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['Status'] = $rows['Status'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['unitRate'] = $rows['unitRate'];
		$user_result['Rate'] = $rows['Rate'];
		$user_result['Stock'] = $rows['Stock'];
		$user_result['SalesQuantity'] = $rows['SalesQuantity'];
		$user_result['OrderDate'] = $rows['OrderDate'];
			$all_users[] = $user_result;
		}
}
else{
   
}

	

		$test = array('AvailableOrderDraftsHisory2'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    	    case 'getExistingProductbyOrderid':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['Supplier'] == '' or $data['Item_Description'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$Supplier=strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
		$Item_Description=strip_tags(mysqli_real_escape_string($con,$data['Item_Description']));
		$Status_pro="";

		$user_sql = $con->query("SELECT * FROM `received_orders1` where Supplier='".$Supplier."' and ClientID ='".$ClientID."' and ProductName='".$Item_Description."'  and OrderID IS NULL and st_reason IS NULL GROUP by OrderNo LIMIT 1");
		if($user_sql->num_rows != 0)
{
    $Status_pro='ITEM EXIST';
    	while($rows = $user_sql->fetch_assoc())
		{

				$user_result['ClientID'] = $rows['ClientID'];
		$user_result['OrderNo'] = $rows['OrderNo'];
		$user_result['Supplier'] = $rows['Supplier'];
		$user_result['ProductName'] = $rows['ProductName'];
		$user_result['Company'] = $rows['Company'];
		$user_result['Pack'] = $rows['Pack'];
		$user_result['Quantity'] = $rows['Quantity'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['Status'] = $rows['Status'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['unitRate'] = $rows['unitRate'];
		$user_result['Rate'] = $rows['Rate'];
		$user_result['Stock'] = $rows['Stock'];
		$user_result['SalesQuantity'] = $rows['SalesQuantity'];
		$user_result['OrderDate'] = $rows['OrderDate'];
			$all_users[] = $user_result;
		}
}
else{
   	$user_sql = $con->query("SELECT * FROM `received_orders1` where Supplier='".$Supplier."' and ClientID ='".$ClientID."'  and OrderID IS NULL and st_reason IS NULL GROUP by OrderNo"); 
   	  $Status_pro='0';
    	while($rows = $user_sql->fetch_assoc())
		{

				$user_result['ClientID'] = $rows['ClientID'];
		$user_result['OrderNo'] = $rows['OrderNo'];
		$user_result['Supplier'] = $rows['Supplier'];
		$user_result['ProductName'] = $rows['ProductName'];
		$user_result['Company'] = $rows['Company'];
		$user_result['Pack'] = $rows['Pack'];
		$user_result['Quantity'] = $rows['Quantity'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['Status'] = $rows['Status'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['unitRate'] = $rows['unitRate'];
		$user_result['Rate'] = $rows['Rate'];
		$user_result['Stock'] = $rows['Stock'];
		$user_result['SalesQuantity'] = $rows['SalesQuantity'];
		$user_result['OrderDate'] = $rows['OrderDate'];
			$all_users[] = $user_result;
		}
}

	

		$test = array('AvailableOrderDrafts'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$Status_pro,"ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    	    
	    case 'getNotificationCount':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['user_id'] == '' or $data['date'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$user_id=strip_tags(mysqli_real_escape_string($con,$data['user_id']));
			$date=strip_tags(mysqli_real_escape_string($con,$data['date']));

		$user_sql = $con->query("SELECT * FROM delivery_shedule WHERE user_id='".$user_id."' and date_of_delivery='".$date."'");

		while($rows = $user_sql->fetch_assoc())
		{

			$user_result['Order_id'] = $rows['Order_id'];
			$user_result['executive_name'] = $rows['executive_name'];
			$user_result['executive_mob'] = $rows['executive_mob'];
			$user_result['day'] = $rows['day'];
				$user_result['date_of_delivery'] = $rows['date_of_delivery'];
		
			$user_result['ClientID'] = $rows['ClientID'];
		
		
	
			$all_users[] = $user_result;
		}

		$test = array('TotNotification'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    
	    
	    	case 'addDeliveryShedule':
				
			$data = json_decode(file_get_contents('php://input'), true);
		 
			
if($data['ClientID'] == '' or $data['Order_id'] == ''  or $data['user_id'] == '' or $data['executive_name'] == '' 
or $data['executive_mob'] == '' or $data['day'] == '' or $data['date_of_delivery'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Order_id = strip_tags(mysqli_real_escape_string($con,$data['Order_id']));
$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
$executive_name = strip_tags(mysqli_real_escape_string($con,$data['executive_name']));
$executive_mob = strip_tags(mysqli_real_escape_string($con,$data['executive_mob']));
$day = strip_tags(mysqli_real_escape_string($con,$data['day']));
$date_of_delivery = strip_tags(mysqli_real_escape_string($con,$data['date_of_delivery']));
$timestamporderDate = strtotime($date_of_delivery);


$con->query("insert into delivery_shedule(`Order_id`,`ClientID`,`user_id`,`executive_name`,
`executive_mob`,`day`,`date_of_delivery`)values
('".$Order_id."','".trim($ClientID)."','".$user_id."','".$executive_name."',
'".$executive_mob."','".$day."','".date("Y-m-d", $timestamporderDate)."')");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Delivery Sheduled Successfully!");


}

echo json_encode($returnArr);	

 

	break;


	    
	       
	     case 'getLiabilityReportForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' or  $data['Type'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$Type = strip_tags(mysqli_real_escape_string($con,$data['Type']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);

if($Type == '1'){
    	$user_sql = $con->query("select * from DatewiseAvgStock_Value1 where (Liability_Value - Sales_Rate)>500 and ClientID='".$ClientID."'
		and  StockValue_Date >='".date("Y-m-d", $timestampFromDate)."' and StockValue_Date <='".date("Y-m-d", $timestampToDate)."' ");
}
else{
    	$user_sql = $con->query("select * from DatewiseAvgStock_Value1 where  ClientID='".$ClientID."'
		and  StockValue_Date >='".date("Y-m-d", $timestampFromDate)."' and StockValue_Date <='".date("Y-m-d", $timestampToDate)."' ");
}
	

		while($rows = $user_sql->fetch_assoc())
		{
	
			$user_result['StockValue_Date'] = $rows['StockValue_Date'];
			$user_result['StockValue_Time'] = $rows['StockValue_Time'];
			$user_result['Purchase_Rate'] = $rows['Purchase_Rate'];
			$user_result['MRP'] = $rows['MRP'];
			$user_result['Sales_Rate'] = $rows['Sales_Rate'];
			$user_result['Liability_Value'] = $rows['Liability_Value'];
			
			$all_users[] = $user_result;
		}

		$test = array('LiabilityReportForClient'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    	case 'updatePharmappOrderID':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['OrderID'] == '' or $data['PharmappOrderID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$OrderID = strip_tags(mysqli_real_escape_string($con,$data['OrderID']));
$PharmappOrderID = strip_tags(mysqli_real_escape_string($con,$data['PharmappOrderID']));

$con->query("update received_orders1 set OrderID='".$PharmappOrderID."'
 where (OrderNo='".$OrderID."')  and OrderID IS NULL LIMIT 99 ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Success!");
		  

}


echo json_encode($returnArr);	

	 


			break;
	    
	     case 'getEditTransferDtListForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' or $data['Type'] =='' or $data['Trno'] =='')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$Type = strip_tags(mysqli_real_escape_string($con,$data['Type']));
		$Trno = strip_tags(mysqli_real_escape_string($con,$data['Trno']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);

		$user_sql = $con->query("select Clientid,transfer_no,Branch,invoice_no,Type,amount,edtamount,edit_id from (

select t.transfer_date,t.transfer_no,t.clientid as ClientID,Branch,Invoice_No,t.type as type,sum((round((sale_rate/pack),3)*quantity)) as amount 
 from transfer1 t left join transfer_item1 ti on t.transfer_no = ti.transfer_no 
and t.Clientid = ti.Clientid and t.type = ti.type 
group by t.transfer_no,t.clientid,Branch,Invoice_No,t.type
)tr left join (
    
    select edt.edit_id,edt.transfer_no as edttransfer_no,edt.clientid as edtClientID,Branch as edtbranch,edt.type as edttype,sum((round((sale_rate/pack),3)*quantity)) as edtamount 
 from edit_transfer1 edt 
    left join edit_transfer_item1 edti on edt.transfer_no = edti.transfer_no 
and edt.Clientid = edti.Clientid and edt.type = edti.type and edt.edit_id = edti.edit_id 
    where edt.ClientID = '".$ClientID."' and edt.Edit_date >='".date("Y-m-d", $timestampFromDate)."' and edt.Edit_date <='".date("Y-m-d", $timestampToDate)."'and edt.Transfer_no='".$Trno."' and edt.type='".$Type."'
group by edt.transfer_no,edt.clientid,Branch,edt.type,edit_id
    
)edttr on tr.clientid = edttr.edtClientID and tr.transfer_no = edttr.edttransfer_no and tr.type= edttr.edttype
where amount <> edtamount");

		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Clientid'] = $rows['Clientid'];
			$user_result['transfer_no'] = $rows['transfer_no'];
			$user_result['Branch'] = $rows['Branch'];
			$user_result['Invoice_No'] = $rows['invoice_no'];
			$user_result['type'] = $rows['Type'];
			$user_result['amount'] = $rows['amount'];
			$user_result['edtamount'] = $rows['edtamount'];
			$user_result['edit_id'] = $rows['edit_id'];
	
			$all_users[] = $user_result;
		}

		$test = array('EditTransferDetailsList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	     case 'getEditTransferReportForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' or $data['Type'] =='')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$Type = strip_tags(mysqli_real_escape_string($con,$data['Type']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		
		$user_sql = $con->query("select edt.transfer_no as edttransfer_no,edt.clientid as edtClientID,Branch as edtbranch,edt.type as edttype,sum((round((sale_rate/pack),3)*quantity)) as edtamount ,edt.Edit_date as edate
 from edit_transfer1 edt 
    left join edit_transfer_item1 edti on edt.transfer_no = edti.transfer_no 
and edt.Clientid = edti.Clientid and edt.type = edti.type and edt.edit_id = edti.edit_id 
    where edt.ClientID = '".$ClientID."' and edt.Edit_date >='".date("Y-m-d", $timestampFromDate)."' and edt.Edit_date <='".date("Y-m-d", $timestampToDate)."' and edt.Type='".$Type."'
group by edt.transfer_no,edt.ClientID,Branch,edt.Type");

		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['edttransfer_no'] = $rows['edttransfer_no'];
			$user_result['edtClientID'] = $rows['edtClientID'];
			$user_result['edtbranch'] = $rows['edtbranch'];
			$user_result['edttype'] = $rows['edttype'];
			$user_result['edtamount'] = $rows['edtamount'];
			$user_result['edate'] = $rows['edate'];
		
			$all_users[] = $user_result;
		}

		$test = array('EditTransferPrimaryList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	    case 'getAllCustomerOrderbyshopsw':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == '' or $data['user_id'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
	$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
	$user_id=strip_tags(mysqli_real_escape_string($con,$data['user_id']));

	if($user_id !=0){

		$user_sql = $con->query("select Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,user_id,Name,Status,notes,bill_img,c_notes,BillNo,ClientID
		from customer_orders WHERE user_id='".$user_id."'  GROUP BY Order_Id ORDER BY id DESC");
	}
	else{

		$user_sql = $con->query("select Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,user_id,Name,Status,notes,bill_img,c_notes,BillNo,ClientID
		from customer_orders WHERE ClientID='".$ClientID."'  GROUP BY Order_Id ORDER BY id DESC");;
	}
	

while($rows = $user_sql->fetch_assoc())
{

$user_result['OrderId'] = $rows['Order_Id'];
$user_result['Order_Date'] = $rows['Order_Date'];
$user_result['qnos'] = $rows['qnos'];
$user_result['amount'] = $rows['amount'];
$user_result['Doctor_name'] = $rows['Doctor_name'];
$user_result['Patients_name'] = $rows['Patients_name'];
$user_result['Name'] = $rows['Name'];
$user_result['user_id'] = $rows['user_id'];
$user_result['Status'] = $rows['Status'];
$user_result['Notes'] = $rows['notes'];
$user_result['Bill'] = $rows['bill_img'];
$user_result['CNotes'] = $rows['c_notes'];
$user_result['BillNo'] = $rows['BillNo'];
$user_result['ClientID'] = $rows['ClientID'];
$all_users[] = $user_result;
	



}


$test = array('AllCustomerOrderbyAdmin'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 
	    
	    
	    
	    	     case 'getConsolidatedReportForClients':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			if($data['email'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' or $data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$email=strip_tags(mysqli_real_escape_string($con,$data['email']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);

			  	    $user_sql = $con->query("select username,Clientid,clientname,address1,address2,address3,Area,clientLocation,AssignedID,GT,avgsales from (

select cl.clientid,clientname,AssignedID,sum(grand_total) as GT,sum(grand_total)/countdt as avgsales,address1,address2,address3,Area,clientLocation from sales1 s left join 
(
select tas.clientid,clientname,managed_clientid as AssignedID,address1,address2,address3,Area,cs.Location as clientLocation from tbl_assigned_shops tas
LEFT JOIN clients cs ON tas.Managed_ClientID =  cs.ClientID)cl on s.ClientID = cl.AssignedID
left join ( 
    select clientid,count(dt) as countdt from (
    select distinct clientid,bill_date as dt from sales1 where 
    bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."' 
    )dat group by clientid)cntdt on s.ClientID = cntdt.clientid     
where cl.clientid ='".$ClientID."'
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
group by clientname,AssignedID,address1,address2,address3
)details left join ( select username,userid from user ) usr on details.clientid = usr.userid
where UserName=('".$email."')");  
			    
			
		
		

		while($rows = $user_sql->fetch_assoc())
		{
		    $user_result['ClientName'] = $rows['clientname'].' - '.$rows['clientLocation'].' , ' .$rows['Area'];
			$user_result['AssignedID'] = $rows['AssignedID'];
			$user_result['GT'] = $rows['GT'];
			$user_result['Avgsales'] = $rows['avgsales'];
		
		
			$all_users[] = $user_result;
		}

		$test = array('ConsolidatedList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	    		
			    	case 'getVStockbyproduct':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['Item_Name'] == '' or $data['ClientID'] == '' or $data['TrigDt'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$Item_Name = strip_tags(mysqli_real_escape_string($con,$data['Item_Name']));
$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$TrigDt= strip_tags(mysqli_real_escape_string($con,$data['TrigDt']));
$checkProductname = $con->query("select * from StockVerification where ProductName='".$Item_Name."' and ClientID='".$ClientID."' and Cflag='1' and TrigDt>='".$TrigDt."'")->fetch_assoc();
$invoice_no=$checkProductname['ProductName'];
$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$invoice_no);



}

echo json_encode($returnArr);	



break;
	    
	    
	    	    	case 'getClientBanners':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == ''   or $data['effect_date'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$effect_date=strip_tags(mysqli_real_escape_string($con,$data['effect_date']));
		
		

	
			$user_sql = $con->query("SELECT * from tbl_banner where ClientID='".$ClientID."' and '".$effect_date."' BETWEEN from_date and to_date and banner_status='1'");


		
		while($rows = $user_sql->fetch_assoc())
		{
			
			$user_result['Banner_desc'] = $rows['banner_desc'];
			$user_result['Banner_img'] = $rows['banner_img'];
			$all_users[] = $user_result;
		}

		$test = array('BannerList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Banner List","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break;
	    
	    
	    	case 'getUpdatedPermissionList':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['user_id'] == ''  or $data['pack_id'] == ''  )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

			$pack_id=strip_tags(mysqli_real_escape_string($con,$data['pack_id']));
			$user_id=strip_tags(mysqli_real_escape_string($con,$data['user_id']));
		

	
			$user_sql = $con->query("select tbl_userpermissions.id as perID, status , per_from,per_to,tbl_permissionActions.act_slug,tbl_permissionActions.act_payment
from tbl_userpermissions

JOIN tbl_permissionActions on tbl_userpermissions.per_act = tbl_permissionActions.id
where tbl_userpermissions.Package_ID = '".$pack_id."' and tbl_userpermissions.Client_ID = '".$ClientID."' and tbl_userpermissions.User_ID = '".$user_id."' ");


		
		while($rows = $user_sql->fetch_assoc())
		{
			
			$user_result['perID'] = $rows['perID'];
			$user_result['status'] = $rows['status'];
			$user_result['per_from'] = $rows['per_from'];
			$user_result['per_to'] = $rows['per_to'];
			$user_result['act_slug'] = $rows['act_slug'];
				$user_result['act_payment'] = $rows['act_payment'];
		
		
	
			$all_users[] = $user_result;
		}

		$test = array('UpdatedPermissions'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission List","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
		
		
		  	case 'isPerupdate':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['per_id'] == ''   )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$per_id = strip_tags(mysqli_real_escape_string($con,$data['per_id']));


$con->query("update tbl_userpermissions set status='1' where per_act='".$per_id."'");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Notes saved successfully!");
		  

}


echo json_encode($returnArr);	

	 
		break;

	    
	    
	    
	    	    	case 'isNotesupdate':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['Order_Id'] == '' or $data['notes'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Order_Id = strip_tags(mysqli_real_escape_string($con,$data['Order_Id']));
$notes = strip_tags(mysqli_real_escape_string($con,$data['notes']));


$con->query("update customer_orders set c_notes='".$notes."' where (ClientID='".$ClientID."') and Order_Id='".$Order_Id."' ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Notes saved successfully!");
		  

}


echo json_encode($returnArr);	

	 


			break;
	    
	    
	    
	    		case 'isCstatusupdate':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['status'] == '' or $data['item'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
$item = strip_tags(mysqli_real_escape_string($con,$data['item']));


$con->query("update customer_orders set c_status='".$status."' where (ClientID='".$ClientID."') and Product_Name='".$item."' ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Status Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 


			break;
			
			
			
			    	case 'getFreeStockbyClientid':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['Item_Name'] == '' or $data['ClientID'] == '' or $data['Company_Name'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$Item_Name = strip_tags(mysqli_real_escape_string($con,$data['Item_Name']));
$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Company_Name = strip_tags(mysqli_real_escape_string($con,$data['Company_Name']));

$invoice_no="0";
$invoice_date="1900-01-01";
$supplier_name="TEST";
$OfferQty="0";
$schemediscount="0";
$schemediscount1="0";
$schemediscountpercent="0";

$checkProductname = $con->query("select  * from (

select p.purchase_id,invoice_no,invoice_date,supplier_name ,item_description ,company_name ,(pi.quantity/pi.pack) as OfferQty,pio.pioqty as Qty,schemediscount,SchemeDiscountPer,pi.Clientid as fclientid from purchase1 p  
left join purchase_item1 pi on p.purchase_id = pi.purchase_id and p.ClientID = pi.ClientID
left join ( select unit,PurchaseAutoID,purchase_id,amount,(quantity/pack) as pioqty,pack,clientid from purchase_item1 where amount<>'FR' and clientid ='".$ClientID."' )
pio on pi.purchase_id=pio.purchase_id and pi.PurchaseAutoID - 1 = pio.PurchaseAutoID and pi.ClientID = pio.clientid where 1>0 and pi.amount='FR'
and pi.ClientID='".$ClientID."' and p.ClientID='".$ClientID."'
and item_description ='".$Item_Name."' and company_name ='".$Company_Name."'

UNION

select p.purchase_id,invoice_no,invoice_date,supplier_name ,item_description ,company_name ,0 as OfferQty,(pi.quantity/pack) as Qty,schemediscount,SchemeDiscountPer,pi.Clientid as fclientid from purchase1 p  
left join purchase_item1 pi on p.purchase_id = pi.purchase_id and p.ClientID = pi.ClientID
where 1>0 and SchemeDiscountPer >0 and SchemeDiscount >0
and pi.ClientID='".$ClientID."' and p.ClientID='".$ClientID."'
and item_description ='".$Item_Name."' and company_name ='".$Company_Name."'
)frscheme
order by 1 desc limit 1")->fetch_assoc();

if (is_null($checkProductname)){
    
    
    
$returnArr = array("ResponseCode"=>"200","Result"=>"false","ResponseMsg"=>"No Schemes found"); 

}
else{
    	$invoice_no=$checkProductname['invoice_no'];
		$invoice_date=$checkProductname['invoice_date'];
		$supplier_name=$checkProductname['supplier_name'];
		$OfferQty=$checkProductname['OfferQty'];
		$schemediscount=$checkProductname['Qty'];
		$schemediscount1=$checkProductname['schemediscount'];
	    $schemediscountpercent=$checkProductname['SchemeDiscountPer'];
				
    
$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$invoice_no.','.$invoice_date.','.$supplier_name.','.$OfferQty.','.$schemediscount.','.$schemediscount1.','."0");
}





}

echo json_encode($returnArr);	



break;
	   

	    
	    
	    	case 'getProdStockbyClientid':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['Item_Name'] == '' or $data['ClientID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$Item_Name = strip_tags(mysqli_real_escape_string($con,$data['Item_Name']));
$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$checkexist = $con->query("SELECT SUM(Purchase_quantity-Sales_quantity) as qnt FROM `stock` WHERE Product_Name='".$Item_Name."' and ClientID='".$ClientID."'");
if($checkexist->num_rows != 0)
{
    	$checkProductname = $con->query("SELECT SUM(Purchase_quantity-Sales_quantity) as qnt FROM `stock` WHERE Product_Name='".$Item_Name."' and ClientID='".$ClientID."' LIMIT 1")->fetch_assoc();
		$item_name=$checkProductname['qnt'];
    
$returnArr = array("ResponseCode"=>"401","Result"=>"true","ResponseMsg"=>$item_name);
}
else{
  $returnArr = array("ResponseCode"=>"401","Result"=>"fasle","ResponseMsg"=>"0");  
    
}



}

echo json_encode($returnArr);	



break;
	    
	    
	    	    
	    case 'getLoginIDforEditSales':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));


$bookings_sql = $con->query("SELECT LoginID FROM `Edit_Sales1` WHERE ClientID='".$ClientID."' GROUP by LoginID"); 


while($rows = $bookings_sql->fetch_assoc())
{
$am_result['LoginID'] = $rows['LoginID'];

$all_amenity[] = $am_result;
}



$test = array('LoginIDforEditSales'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
		
		
	    
	    
	    	case 'addtoPharmappSubstitutes':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['Item_Name'] == '' or $data['Manufacturer'] == '' or $data['PharmApp_Product'] == '' or $data['Product_ID'] == '' or $data['Supplier_Name'] == '' or $data['Supplier_ID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$Item_Name = strip_tags(mysqli_real_escape_string($con,$data['Item_Name']));
$Manufacturer = strip_tags(mysqli_real_escape_string($con,$data['Manufacturer']));
$PharmApp_Product = strip_tags(mysqli_real_escape_string($con,$data['PharmApp_Product']));
$Supplier_ID = strip_tags(mysqli_real_escape_string($con,$data['Supplier_ID']));
$Product_ID = strip_tags(mysqli_real_escape_string($con,$data['Product_ID']));
$Supplier_Name = strip_tags(mysqli_real_escape_string($con,$data['Supplier_Name']));
$checkexist = $con->query("select * from PharmApp_Substitutes where Product_Name='".$Item_Name."' and SupplierId='".$Supplier_ID."'");
if($checkexist->num_rows != 0)
{
    	$checkProductname = $con->query("select * from PharmApp_Substitutes where Product_Name='".$Item_Name."' and SupplierId='".$Supplier_ID."' ")->fetch_assoc();
		$item_name=$checkProductname['PharmApp_Product'];
    
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>$item_name);
}
else
{
    
    $ADD_TO_USER=$con->query("insert into PharmApp_Substitutes(`Product_Name`,`Manufacturer`,`PharmApp_Product`,`Product_ID`,
`Supplier_Name`,`SupplierId`)values
('".$Item_Name."','".$Manufacturer."','".$PharmApp_Product."','".$Product_ID."','".$Supplier_Name."','".$Supplier_ID."')");


	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Substitude added successfully");
	
	

}


}

echo json_encode($returnArr);	



break;
	    
	    			
	case 'hasPharmAppSubstitutes':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['Item_Name'] == '' or $data['Supplier_ID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$Item_Name = strip_tags(mysqli_real_escape_string($con,$data['Item_Name']));
$Supplier_ID = strip_tags(mysqli_real_escape_string($con,$data['Supplier_ID']));
$checkexist = $con->query("select * from PharmApp_Substitutes where Product_Name='".$Item_Name."'  and SupplierId='".$Supplier_ID."' ");
if($checkexist->num_rows != 0)
{
    	$checkProductname = $con->query("select * from PharmApp_Substitutes where Product_Name='".$Item_Name."' and SupplierId='".$Supplier_ID."'")->fetch_assoc();
		$item_name=$checkProductname['PharmApp_Product'];
		$pid=$checkProductname['Product_ID'];
    
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>$item_name.','.$pid);
}
else
{


	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"No Matching Products found");
	
	

}


}

echo json_encode($returnArr);	



break;
	    
	    
	    case 'getSupplierbyPharmappList':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['Supplier_Name'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$Supplier_Name=strip_tags(mysqli_real_escape_string($con,$data['Supplier_Name']));


$bookings_sql = $con->query("select * from PharmApp_Supplier"); 


while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Supplier_ID'] = $rows['Supplier_ID'];
$am_result['Supplier_Name'] = $rows['Supplier_Name'];
$am_result['District_Name'] = $rows['District_Name'];
$am_result['Auto'] = $rows['Auto'];

$all_amenity[] = $am_result;
}



$test = array('SupplierPharmappList'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
	    
	    
	    
case 'getAllIteminrcorder':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));


$bookings_sql = $con->query("select * from received_orders1 where ClientID='".$ClientID."'"); 


while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['ProductName'];

$all_amenity[] = $am_result;
}



$test = array('All_ItemRCV'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
		
	    
	    
	    case 'getPrevPorderhistory':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == '' or $data['Item'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
	$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
	$Item=strip_tags(mysqli_real_escape_string($con,$data['Item']));

		$user_sql = $con->query("SELECT OrderNo,OrderDate,Quantity,Supplier from received_orders1 WHERE ProductName='".$Item."' and ClientID='".$ClientID."' ORDER By OrderDate desc;");
	

	
while($rows = $user_sql->fetch_assoc())
{

$user_result['OrderNo'] = $rows['OrderNo'];
$user_result['OrderDate'] = $rows['OrderDate'];
$user_result['Quantity'] = $rows['Quantity'];
$user_result['Supplier'] = $rows['Supplier'];
$all_users[] = $user_result;
	



}


$test = array('AllPrevhistory'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break;
	    
	    
	    	case 'getPermissionList':


			$data = json_decode(file_get_contents('php://input'), true);
			if($data['ClientID'] == '' or $data['user_id'] == '' )
			{
			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
			}
			
			else {
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$user_id=strip_tags(mysqli_real_escape_string($con,$data['user_id']));
	if($user_id=="0"){
	    		
  $c = $con->query("SELECT tbl_versions.ver_name,tbl_packages.Pack_Name,tbl_packages.Pack_From,tbl_packages.Pack_To,tbl_userpermissions.user_id,user.userid as Clientid,user.Name,
clients.ClientName,tbl_activitypermission.*,
ta.p1_isViewMore ,ta.p1_isTotalPurchase from tbl_userpermissions 
JOIN user ON tbl_userpermissions.user_id=user.id
JOIN tbl_activitypermission ON tbl_userpermissions.user_id=tbl_activitypermission.user_id
JOIN tbl_versions ON tbl_userpermissions.verision_id=tbl_versions.id
JOIN tbl_packages ON tbl_userpermissions.package_id=tbl_packages.id
JOIN clients ON tbl_activitypermission.client_id=clients.ClientID
JOIN ( select p1_isViewMore,user_id as userid2,p1_isTotalPurchase,client_id as clientid2 from tbl_activitypurchasepermission) ta ON 
clients.ClientID=ta.clientid2
WHERE tbl_activitypermission.client_id='".$ClientID."' AND
ta.clientid2='".$ClientID."' LIMIT 1");
	}
	else{
	   		
  $c = $con->query("SELECT tbl_versions.ver_name,tbl_packages.Pack_Name,tbl_packages.Pack_From,tbl_packages.Pack_To,tbl_userpermissions.user_id,user.userid as Clientid,user.Name,
clients.ClientName,tbl_activitypermission.*,
ta.p1_isViewMore ,ta.p1_isTotalPurchase from tbl_userpermissions 
JOIN user ON tbl_userpermissions.user_id=user.id
JOIN tbl_activitypermission ON tbl_userpermissions.user_id=tbl_activitypermission.user_id
JOIN tbl_versions ON tbl_userpermissions.verision_id=tbl_versions.id
JOIN tbl_packages ON tbl_userpermissions.package_id=tbl_packages.id
JOIN clients ON tbl_activitypermission.client_id=clients.ClientID
JOIN ( select p1_isViewMore,user_id as userid2,p1_isTotalPurchase,client_id as clientid2 from tbl_activitypurchasepermission) ta ON 
clients.ClientID=ta.clientid2
WHERE tbl_activitypermission.client_id='".$ClientID."' AND
ta.clientid2='".$ClientID."' AND
tbl_activitypermission.user_id='".$user_id."' AND
ta.userid2='".$user_id."'"); 
	    
	}
  

$c = $c->fetch_assoc();
$test = array('PermisionList'=>$c );

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);
}


			echo json_encode($returnArr);	

			break;
	    
	    	case 'getLoginReportPrimaryForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);

		
		$user_sql = $con->query("select login_date,Firstloginuser,LastLogoutUser,logintime,logouttime from (
select min(in_time) as logintime,max(out_time) as logouttime,login_date from Login1 l
left join Password pwd on l.password_id = pwd.UserID                        
where l.ClientID ='".$ClientID."' and pwd.ClientID ='".$ClientID."'
and login_date>='".date("Y-m-d", $timestampFromDate)."'
and login_date<='".date("Y-m-d", $timestampToDate)."'
group by login_date 
)lg left join (
    
 select username as FirstloginUser,login_date as lgdt2,(in_time) as in_time from Login1 l 
left join Password pwd on l.password_id = pwd.UserID  
where l.ClientID ='".$ClientID."' and pwd.ClientID ='".$ClientID."'  
and login_date>='".date("Y-m-d", $timestampFromDate)."'
and login_date<='".date("Y-m-d", $timestampToDate)."'
)lg2 on  lg.login_date = lg2.lgdt2 and lg.logintime = lg2.in_time

left join (    
 select username as LastLogoutUser,login_date as lgdt3,out_time from Login1 l 
left join Password pwd on l.password_id = pwd.UserID  
where l.ClientID ='".$ClientID."' and pwd.ClientID ='".$ClientID."'  
and login_date>='".date("Y-m-d", $timestampFromDate)."'
and login_date<='".date("Y-m-d", $timestampToDate)."'    
)lg3 on  lg.login_date = lg3.lgdt3 and lg2.lgdt2 = lg3.lgdt3 and lg.logouttime = lg3.out_time");

		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Login_Date'] = $rows['login_date'];
			$user_result['Firstloginuser'] = $rows['FirstloginUser'];
			$user_result['LastLogoutUser'] = $rows['LastLogoutUser'];
			$user_result['logintime'] = $rows['logintime'];
			$user_result['logouttime'] = $rows['logouttime'];
	
			$all_users[] = $user_result;
		}

		$test = array('LoginReportPrimaryList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
		case 'getCurrentSaleitembybill':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == ''   or $data['Bill_id'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$Bill_id=strip_tags(mysqli_real_escape_string($con,$data['Bill_id']));

		$chekstudentid = $con->query("select SUM(amount) as tot,LoginID from sales_item1
JOIN sales1 ON sales_item1.bill_no=sales1.bill_no
		where 1>0  
		and sales_item1.ClientID ='".$ClientID."' 
		and sales1.ClientID ='".$ClientID."'
		and sales_item1.bill_no = '".$Bill_id."'
		and sales1.bill_no = '".$Bill_id."'
		")->fetch_assoc();
		$sumval=$chekstudentid['tot'];
		$loginuser=$chekstudentid['LoginID'];
	
			$user_sql = $con->query("select * from sales_item1 where 1>0 and ClientID ='".$ClientID."'
			and bill_no = '".$Bill_id."' order by item_description");
		
		while($rows = $user_sql->fetch_assoc())
		{
			
			$user_result['Item_Description'] = $rows['item_description'];
			$user_result['Quantity'] = $rows['quantity'];
			$user_result['Batch'] = $rows['batch'];
			$user_result['Rate'] = $rows['rate'];
			$user_result['Amount'] = $rows['amount'];
		
		
	
			$all_users[] = $user_result;
		}

		$test = array('Salesitemsearch'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$sumval.','.$loginuser,"ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    	case 'getEditReportByItembyeditid':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == ''   or $data['Bill_id'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$Bill_id=strip_tags(mysqli_real_escape_string($con,$data['Bill_id']));

	
			$user_sql = $con->query("select es.bill_no as bno,Item_description,quantity,batch,Min(es.edit_id) as minid,Rate,amount,grand_total from Edit_Sales1 es 
			left join Edit_Sales_Item1 esi on es.Bill_No = esi.bill_no and es.edit_id = esi.edit_id where es.ClientID ='".$ClientID."'
			and esi.ClientID ='".$ClientID."'
			and es.edit_id = '".$Bill_id."' and esi.edit_id = '".$Bill_id."'
			group by Item_description,quantity,batch,grand_total,Rate,amount
			order by 5");
		
		while($rows = $user_sql->fetch_assoc())
		{
			
			$user_result['Item_Description'] = $rows['Item_description'];
			$user_result['Quantity'] = $rows['quantity'];
			$user_result['Batch'] = $rows['batch'];
			$user_result['MinId'] = $rows['minid'];
			$user_result['Rate'] = $rows['Rate'];
			$user_result['Amount'] = $rows['amount'];
			$user_result['Grand_Total'] = $rows['grand_total'];
		
	
			$all_users[] = $user_result;
		}

		$test = array('EditReportbyItem'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	    
	    	     case 'addPOrderListSingle':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['query'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$query = $data['query'];

					

$con->multi_query($query);

if($con){
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Status Updated successfully!");
}
else{
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Failed to update");

}

		  

}
echo json_encode($returnArr);
		
break; 
	    
	    
	    		case 'getPurchaseReportbyRangeBySupplier1':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['date'] == ''  or $data['ClientID'] == '' or $data['Supplier'] == '' or $data['narration'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$date = strip_tags(mysqli_real_escape_string($con,$data['date']));
			$Supplier = strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
					$Narration = strip_tags(mysqli_real_escape_string($con,$data['narration']));

			if($Supplier =='0' && $Narration =='0'){

				$user_sql = $con->query("select purchase1.clientid,purchase_date,purchase1.supplier_name,Mobile,Phone1,SUM(grand_total) as tot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance,invoice_no from purchase1
JOIN supplier ON supplier.supplier_name=purchase1.supplier_name

where 1>0
				and purchase_date  >='".$date."'
				and purchase_date  <='".$date."'
				and purchase1.ClientID='".$ClientID."'
		  GROUP by ClientID,purchase_date,supplier_name");

			}
				else if($Supplier =='0' && $Narration !='0'){

				$user_sql = $con->query("select purchase1.clientid,purchase_date,purchase1.supplier_name,Mobile,Phone1,SUM(grand_total) as tot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance,invoice_no,narration from purchase1
JOIN supplier ON supplier.supplier_name=purchase1.supplier_name

where 1>0
				and purchase_date  >='".$date."'
				and purchase_date  <='".$date."'
				and purchase1.ClientID='".$ClientID."'
				and narration !=''
		  GROUP by ClientID,purchase_date,supplier_name");

			}
			
				else if($Supplier !='0' && $Narration =='0'){

				$user_sql = $con->query("select purchase1.clientid,purchase_date,purchase1.supplier_name,Mobile,Phone1,SUM(grand_total) as tot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance,invoice_no from purchase1
JOIN supplier ON supplier.supplier_name=purchase1.supplier_name

where 1>0
				and purchase_date  >='".$date."'
				and purchase_date  <='".$date."'
				and purchase1.ClientID='".$ClientID."'
				and purchase1.supplier_name='".$Supplier."'
			
		  GROUP by ClientID,purchase_date,supplier_name");

			}
			else{
				$user_sql = $con->query("select purchase1.clientid,purchase_date,purchase1.supplier_name,Mobile,Phone1,SUM(grand_total) as tot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance,invoice_no from purchase1 
				JOIN supplier ON supplier.supplier_name=purchase1.supplier_name
				where 1>0
				and purchase_date  >='".$date."'
				and purchase_date  <='".$date."'
				and purchase1.ClientID='".$ClientID."' and purchase1.supplier_name='".$Supplier."' and narration !=''
		  GROUP by ClientID,purchase_date,supplier_name");

			}

		
		
		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Supplier Name'] = $rows['supplier_name'];
			$user_result['Grand Total'] = $rows['tot'];
				$user_result['Invoice'] = $rows['invoice_no'];
				$user_result['Mobile'] = $rows['Mobile'];
				$user_result['Phone1'] = $rows['Phone1'];
					$user_result['Adjustment'] = $rows['adjustment'];
						$user_result['Netbalance'] = $rows['NetBalance'];
	
			$all_users[] = $user_result;
		}

		$test = array('PurchaseReportbyRangebySupplier'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Supplier List","ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
	    
	    
	     case 'getPTotalCCForClient1':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$user_result=null;
			$all_users=array();
			$Status=0;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' or $data['Supplier'] == ''  )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$Supplier = strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);
			
			if($Supplier == '0'){

				$user_sql = $con->query("select 'cash' as flg, SUM(grand_total) as tot from purchase1 where 1>0 
				and purchase_date >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date <='".date("Y-m-d", $timestampToDate)."' 
				and ClientID='".$ClientID."' and type ='d' and supplier_name='".$Supplier."'
				GROUP by ClientID 
				UNION select 'credit' as flg, SUM(grand_total) as tot from purchase1 where 1>0 
				and purchase_date >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date <='".date("Y-m-d", $timestampToDate)."' 
				and ClientID='".$ClientID."' and type <>'d'  GROUP by ClientID");

			}
			else{

				$user_sql = $con->query("select 'cash' as flg, SUM(grand_total) as tot from purchase1 where 1>0 
				and purchase_date >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date <='".date("Y-m-d", $timestampToDate)."' 
				and ClientID='".$ClientID."' and type ='d' and supplier_name='".$Supplier."'
				GROUP by ClientID 
				UNION select 'credit' as flg, SUM(grand_total) as tot from purchase1 where 1>0 
				and purchase_date >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date <='".date("Y-m-d", $timestampToDate)."' 
				and ClientID='".$ClientID."' and type <>'d' and supplier_name='".$Supplier."' GROUP by ClientID");

			}
	
			
		
		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Flag'] = $rows['flg'];
			$user_result['Tot'] = $rows['tot'];
			
	
			$all_users[] = $user_result;
		}
	

		$test = array('PurchaseCCList'=>$all_users);
			if($user_result != null){

				if($Supplier == '0'){
					$chekstudentid = $con->query("select SUM(grand_total) as tot from purchase1  where 1>0
					and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
					and purchase_date  <='".date("Y-m-d", $timestampToDate)."' 
					and ClientID='".$ClientID."'
			  GROUP by ClientID")->fetch_assoc();
					$Status=$chekstudentid['tot'];
				}
				else{

					$chekstudentid = $con->query("select SUM(grand_total) as tot from purchase1  where 1>0
					and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
					and purchase_date  <='".date("Y-m-d", $timestampToDate)."' 
					and ClientID='".$ClientID."' and supplier_name='".$Supplier."'
			  GROUP by ClientID")->fetch_assoc();
					$Status=$chekstudentid['tot'];
				}
		    
	
		    
		}
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$Status,"ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
	    
	    	    case 'getPurchaseReportbyRange1':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			$class_id=0;
		if($data['From_date'] == '' or $data['To_Range'] == '' or $data['ClientID'] == '' or $data['Supplier'] == '' or $data['narration'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$Supplier = strip_tags(mysqli_real_escape_string($con,$data['Supplier']));
				$Narration = strip_tags(mysqli_real_escape_string($con,$data['narration']));
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);
			
			if($Supplier == '0' && $Narration =='0' ){

				$chekstudentid = $con->query("select SUM(grand_total) as ntot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."'
				")->fetch_assoc();
				$class_id=$chekstudentid['ntot'];
				$class_id2=$chekstudentid['adjustment'];
				$class_id3=$chekstudentid['NetBalance'];
	
				$user_sql = $con->query("select purchase_date,supplier_name,SUM(grand_total+adjustment) as tot from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."'
					 GROUP BY  purchase_date
				ORDER BY purchase_date");

			}
				if($Supplier == '0' && $Narration =='0' ){

				$chekstudentid = $con->query("select SUM(grand_total) as ntot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."'
				")->fetch_assoc();
				$class_id=$chekstudentid['ntot'];
				$class_id2=$chekstudentid['adjustment'];
				$class_id3=$chekstudentid['NetBalance'];
	
				$user_sql = $con->query("select purchase_date,supplier_name,SUM(grand_total+adjustment) as tot from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."'
					 GROUP BY  purchase_date
				ORDER BY purchase_date");

			}
				else if($Supplier == '0' && $Narration !='0' ){

				$chekstudentid = $con->query("select SUM(grand_total) as ntot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."' and narration !=''
				")->fetch_assoc();
				$class_id=$chekstudentid['ntot'];
				$class_id2=$chekstudentid['adjustment'];
				$class_id3=$chekstudentid['NetBalance'];
	
				$user_sql = $con->query("select purchase_date,supplier_name,SUM(grand_total+adjustment) as tot from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."' and narration !=''
					 GROUP BY  purchase_date
				ORDER BY purchase_date");

			}
			
				else if($Supplier != '0' && $Narration =='0' ){

				$chekstudentid = $con->query("select SUM(grand_total) as ntot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."' and supplier_name='".$Supplier."'
				")->fetch_assoc();
				$class_id=$chekstudentid['ntot'];
				$class_id2=$chekstudentid['adjustment'];
				$class_id3=$chekstudentid['NetBalance'];
	
				$user_sql = $con->query("select purchase_date,supplier_name,SUM(grand_total+adjustment) as tot from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."' 	and supplier_name='".$Supplier."'
					 GROUP BY  purchase_date
				ORDER BY purchase_date");

			}
			else{
				$chekstudentid = $con->query("select SUM(grand_total) as ntot,sum(adjustment) as adjustment,SUM(grand_total+adjustment) as NetBalance from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."'
				and supplier_name='".$Supplier."' and narration !=''
				")->fetch_assoc();
						$class_id=$chekstudentid['ntot'];
				$class_id2=$chekstudentid['adjustment'];
				$class_id3=$chekstudentid['NetBalance'];
	
				$user_sql = $con->query("select purchase_date,supplier_name,SUM(grand_total+adjustment) as tot from purchase1  where 1>0
				and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
				and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
				and ClientID='".$ClientID."'
				and supplier_name='".$Supplier."' and narration !=''
				GROUP BY  purchase_date
				ORDER BY purchase_date");


			}
		
		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Purchase Date'] = $rows['purchase_date'];
			$user_result['Supplier Name'] = $rows['supplier_name'];
			$user_result['Grand Total'] = $rows['tot'];
	
			$all_users[] = $user_result;
		}

		$test = array('PurchaseReportbyRange'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$class_id.','.$class_id2.','.$class_id3,"ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
	    
	    
	    
	    
		case 'isPermissionForPOFIRST':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['key'] == ''  or $data['start_key'] == ''  or $data['end_key'] == '' or  $data['spinner_name'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$key = strip_tags(mysqli_real_escape_string($con,$data['key']));
$start_key = strip_tags(mysqli_real_escape_string($con,$data['start_key']));
$end_key = strip_tags(mysqli_real_escape_string($con,$data['end_key']));
$spinner_name = strip_tags(mysqli_real_escape_string($con,$data['spinner_name']));

$con->query("update tbl_spinnerpermission set set_key='".$key."',start_key='".$start_key."',End_key='".$end_key."'
 where (client_id='".$ClientID."')  and spinner_name='".$spinner_name."'");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 


			break;
	    
	    		case 'getPOSpinnerList':


			$data = json_decode(file_get_contents('php://input'), true);
			if($data['ClientID'] == '' or $data['Slug'] == '')
			{
			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
			}
			
			else {
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
				$Slug=strip_tags(mysqli_real_escape_string($con,$data['Slug']));

$c = $con->query("select * from tbl_spinnerpermission where client_id='".$ClientID."' and spinner_name='".$Slug."' ");
$c = $c->fetch_assoc();
$test = array('SpinnerList'=>$c );

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login successfull","ResultData"=>$test);
}


			echo json_encode($returnArr);	

			break;
	    
	    case 'getEditReportMinId':
	
	
				$data = json_decode(file_get_contents('php://input'), true);
				$all_users=null;
			if($data['ClientID'] == ''   or $data['Bill_id'] == '')
			{
			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
			}
			
			else {
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$Bill_id=strip_tags(mysqli_real_escape_string($con,$data['Bill_id']));
	
		
				$user_sql = $con->query("select Min(es.edit_id) as minid, es.bill_no as bno,count(es.edit_id) as cnt,es.LoginID,es.Edit_Date from Edit_Sales1 es 
				left join Edit_Sales_Item1 esi on es.Bill_No = esi.bill_no and es.edit_id = esi.edit_id where es.ClientID ='".$ClientID."'
				and esi.ClientID ='".$ClientID."'
				and es.Bill_No = '".$Bill_id."' and esi.Bill_No =  '".$Bill_id."'
				group by es.Edit_ID,esi.Edit_ID");
			
			while($rows = $user_sql->fetch_assoc())
			{
				
				
				$user_result['MinId'] = $rows['minid'];
				$user_result['LoginID'] = $rows['LoginID'];
				$user_result['Billno'] = $rows['bno'];
				$user_result['Count'] = $rows['cnt'];
				$user_result['EditDate'] = $rows['Edit_Date'];
				$all_users[] = $user_result;
			}
	
			$test = array('EditReportbyMinId'=>$all_users);
			
			
			
			$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
			
			
			
			
			}
					echo json_encode($returnArr);
			
			break; 
	    
	    
	     case 'getEditReportForClients':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' or $data['user_id'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		$fromnew=""."00:00:00";
			$tonew=""."24:00:00";
			
			if($user_id=="0"){
			    $user_sql = $con->query("select 'EDIT' as Flag,edit_id,edit_date,es.bill_no,es.grand_total as esGT,cs.grand_total as CurSGT,es.LoginID as UserName FROM sales1 cs 
		left join Edit_Sales1 es on cs.bill_no=es.bill_no
		and COALESCE(cs.clientid,'') = COALESCE(es.clientid,'')
		WHERE es.clientid = '".$ClientID."' and cs.clientid = '".$ClientID."'
		and round(COALESCE(es.Grand_Total,0),2) <>round(COALESCE(cs.Grand_Total,0),2)
		and Edit_Flag='e'
					and edit_date >='".date("Y-m-d", $timestampFromDate).".".$fromnew."'
		and edit_date <='".date("Y-m-d", $timestampToDate).".".$tonew."'
		group by es.bill_no
		UNION
		
		SELECT 'DELETE' as Flag,edit_id,edit_date,bill_no,grand_total as esGT,0 as CurSGT,'' as UserName FROM Edit_Sales1  
		WHERE clientid = '".$ClientID."'  
		and Edit_Flag='d'
		and edit_date >='".date("Y-m-d", $timestampFromDate).".".$fromnew."'
		and edit_date <='".date("Y-m-d", $timestampToDate).".".$tonew."'
	group by bill_no
		order by edit_date 
		");
			}
			else{
			  	    $user_sql = $con->query("select 'EDIT' as Flag,edit_id,edit_date,es.bill_no,es.grand_total as esGT,cs.grand_total as CurSGT,es.LoginID as UserName FROM sales1 cs 
		left join Edit_Sales1 es on cs.bill_no=es.bill_no
		and COALESCE(cs.clientid,'') = COALESCE(es.clientid,'')
		WHERE es.clientid = '".$ClientID."' and cs.clientid = '".$ClientID."' and es.LoginID='".$user_id."' 
		and round(COALESCE(es.Grand_Total,0),2) <>round(COALESCE(cs.Grand_Total,0),2)
		and Edit_Flag='e'
					and edit_date >='".date("Y-m-d", $timestampFromDate).".".$fromnew."'
		and edit_date <='".date("Y-m-d", $timestampToDate).".".$tonew."'
		group by es.bill_no
		UNION
		
		SELECT 'DELETE' as Flag,edit_id,edit_date,bill_no,grand_total as esGT,0 as CurSGT,'' as UserName FROM Edit_Sales1  
		WHERE clientid = '".$ClientID."'  
		and Edit_Flag='d'
		and edit_date >='".date("Y-m-d", $timestampFromDate).".".$fromnew."'
		and edit_date <='".date("Y-m-d", $timestampToDate).".".$tonew."'
	group by bill_no
		order by edit_date 
		");  
			    
			}
		
		

		while($rows = $user_sql->fetch_assoc())
		{
		    $user_result['Flag'] = $rows['Flag'];
			$user_result['Edit_id'] = $rows['edit_id'];
			$user_result['Edit_date'] = $rows['edit_date'];
			$user_result['Bill_no'] = $rows['bill_no'];
			$user_result['Grand_total'] = $rows['esGT'];
			$user_result['Cur_total'] = $rows['CurSGT'];
			$user_result['UserName'] = $rows['UserName'];
		
			$all_users[] = $user_result;
		}

		$test = array('EditReportList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	    
	    		case 'getSaleHomeCardList':


			$data = json_decode(file_get_contents('php://input'), true);
			if($data['ClientID'] == '' or $data['Date_now'] == '' or $data['Date_previous'] == '')
			{
			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
			}
			
			else {
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$Date_now = strip_tags(mysqli_real_escape_string($con,$data['Date_now']));
			$Date_previous = strip_tags(mysqli_real_escape_string($con,$data['Date_previous']));
			

$c = $con->query("select sum(PrevDaySales) as PrevDaySales,sum(CurrentDaySales) as CurrentDaySales,sum(avgbalane) as avgbalane
from (

SELECT sum(grand_total) as PrevDaySales,0 as CurrentDaySales,0 as avgbalane FROM `sales1`   
where 1>0
and clientid = '".$ClientID."'  
and bill_date ='".$Date_previous."'

Union

SELECT 0 as PrevDaySales,sum(grand_total) as CurrentDaySales,0 as avgbalane FROM `sales1`   
where 1>0
and clientid = '".$ClientID."'  
and bill_date ='".$Date_now."'

Union

select 0 as PrevDaySales,0 as CurrentDaySales,COALESCE(btotal/countdate,0) as avgbalane from (
select count(bill_date) as countdate,sum(btotal) as btotal from (
SELECT bill_date,sum(grand_total) as btotal FROM `sales1`   
where 1>0
and clientid = '".$ClientID."'  
and bill_date ='".$Date_now."'
group by bill_date    
)avgbalance1
)avgbalanceNEW
    
 )aa");
$c = $c->fetch_assoc();
$test = array('SaleHomeCardList'=>$c );

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login successfull","ResultData"=>$test);
}


			echo json_encode($returnArr);	

			break;
	    
	    	 	case 'getEditReportByItem':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == ''   or $data['Bill_id'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$Bill_id=strip_tags(mysqli_real_escape_string($con,$data['Bill_id']));

	
			$user_sql = $con->query("select es.bill_no as bno,Item_description,quantity,batch,Min(es.edit_id) as minid,Rate,amount,grand_total from Edit_Sales1 es 
			left join Edit_Sales_Item1 esi on es.Bill_No = esi.bill_no and es.edit_id = esi.edit_id where es.ClientID ='".$ClientID."'
			and esi.ClientID ='".$ClientID."'
			and es.Bill_No = '".$Bill_id."' and esi.Bill_No = '".$Bill_id."'
			group by Item_description,quantity,batch,grand_total,Rate,amount
			order by 5");
		
		while($rows = $user_sql->fetch_assoc())
		{
			
			$user_result['Item_Description'] = $rows['Item_description'];
			$user_result['Quantity'] = $rows['quantity'];
			$user_result['Batch'] = $rows['batch'];
			$user_result['MinId'] = $rows['minid'];
			$user_result['Rate'] = $rows['Rate'];
			$user_result['Amount'] = $rows['amount'];
			$user_result['Grand_Total'] = $rows['grand_total'];
		
	
			$all_users[] = $user_result;
		}

		$test = array('EditReportbyItem'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
		case 'getTotalSalesForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
		$class_id=0;
		if($data['ClientID'] == '' or $data['FromDate'] == '' or $data['ToDate'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$FromDate=strip_tags(mysqli_real_escape_string($con,$data['FromDate']));
		$ToDate=strip_tags(mysqli_real_escape_string($con,$data['ToDate']));
		
			
	
		$chekstudentid = $con->query("select sum(grand_total)/count(DISTINCT bill_date) as nsum  from sales1 where 1>0
		and ClientID='".$ClientID."' and  bill_date>='".$FromDate."' AND
bill_date<='".$ToDate."'
	")->fetch_assoc();
		$class_id=$chekstudentid['nsum'];
		
	
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$class_id);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 
	    
		case 'getTotalPurchaseForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
		$class_id=0;
		if($data['ClientID'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		
			
		$chekstudentid = $con->query("select SUM(grand_total) as ntot from purchase1  where 1>0
	
		and ClientID='".$ClientID."'
		")->fetch_assoc();
		$class_id=$chekstudentid['ntot'];
		
	
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$class_id);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 
	    
	    
	    	case 'getCashSalesIndividual':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' or $data['Type'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$Type=strip_tags(mysqli_real_escape_string($con,$data['Type']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);

		if($Type=='CASH')
		{
			$user_sql = $con->query("select 'cash' flg,bill_no,SUM(paid_amount) as tot,customer_name from sales1 where 1>0
			and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			 and ClientID='".$ClientID."' and COALESCE(type,'')='D'   and CCard=''
			 group by bill_no
			");
		}
		else if($Type=='CARD'){
		
			$user_sql = $con->query("select 'card' flg,bill_no,SUM(CCardAmount) as tot,customer_name from sales1 where 1>0
			and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."' and COALESCE(type,'')='D' 
			and CCard<>''
			group by bill_no");

		}
		else{

			$user_sql = $con->query("select 'credit' flg,bill_no, SUM(grand_total) as tot,customer_name from sales1 where 1>0
			and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."' and COALESCE(type,'')='c' 
			group by bill_no");
		

		}
		


		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Flag'] = $rows['flg'];
			$user_result['Bill No'] = $rows['bill_no'];
			$user_result['Total'] = $rows['tot'];
					$user_result['customer_name'] = $rows['customer_name'];
	
			$all_users[] = $user_result;
		}

		$test = array('SalesIndividualCCList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
		case 'getDenomionationList':


			$data = json_decode(file_get_contents('php://input'), true);
			if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '')
			{
			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
			}
			
			else {
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);

$c = $con->query("select dt,sum(PrevDenTotal) as PrevDenTotal,sum(OpAmount) as OpAmount,sum(CashSales) as CashSales,sum(CreditSales) as CreditSales,sum(CardSales) as CardSales,sum(SRAmount) as SRAmount,Sum(Paid) as Paid,sum(DenominationAmt) as DenominationAmt from ( 

	select -1 as Flag,0 as cntbno,Entry_Date as dt,UserName as name,
	0 as PrevDenTotal,Opening_Amount as OpAmount,0 as CashSales,0 as CreditSales,0 as CardSales,0 as SRAmount,0 as DenominationAmt,0 as Paid,'' as tp from CashAccount_Closing1  Where 1>0 
	and Entry_Date >='".date("Y-m-d", $timestampFromDate)."'
	and Entry_Date <='".date("Y-m-d", $timestampFromDate)."'
	and clientid =  '".$ClientID."'
		
	Union 
	select 1 as flag,count(bill_no) as cntbno,bill_date as dt,loginid as name,
	0 as PrevDenTotal,0 as OpAmount,sum(((granD_total-(grand_total* cash_discount*.01))-(ccardamount))) as CashSales,0 as CreditSales,0 as CardSales,0 as SRAmount,0 as DenominationAmt,
	sum(paid_amount) as Paid,type as tp from sales1   where 1>0 
	and type ='D' and COALESCE(CType,'') = '' 
	and bill_date >='".date("Y-m-d", $timestampFromDate)."'
	and bill_date <='".date("Y-m-d", $timestampFromDate)."'
	and ClientID = '".$ClientID."'
	group by name,bill_date,type    
	Union
	 select 2 as flag,count(bill_no) as cntbno,bill_date as dt,loginid as name,0 as OpAmount,0 as CashSales,sum(grand_total-(grand_total* cash_discount*.01)) as CreditSales,0 as CardSales,0 as SRAmount,0 as DenominationAmt,
	0 as PrevDenTotal,sum(paid_amount) as Paid,type as tp from sales1   where 1>0 and (type ='C' or type ='') and COALESCE(CType,'') = '' 
	and bill_date >='".date("Y-m-d", $timestampFromDate)."'
	and bill_date <='".date("Y-m-d", $timestampFromDate)."'
		 and ClientID = '".$ClientID."'
	group by name,bill_date,type 
	Union 
	select 3 as Flag,count(bill_no) as cntbno,bill_date as dt,loginid as name,
	0 as PrevDenTotal,0 as OpAmount,0 as CashSales,0 as CreditSales,sum(grand_total-(grand_total* cash_discount*.01)) as CardSales,0 as SRAmount,0 as DenominationAmt,sum(paid_amount) as Paid,type as tp from sales1 where 1>0 and COALESCE(CType,'') <> '' 
	and bill_date >='".date("Y-m-d", $timestampFromDate)."'
	and bill_date <='".date("Y-m-d", $timestampFromDate)."'
	 and ClientID = '".$ClientID."'
	group by name,bill_date,type,CType
	Union
		select 4 as Flag,0 as cntbno,return_date as dt,'' as name,0 as PrevDenTotal,0 as OpAmount,0 as CashSales,0 as CreditSales,0 as CardSales,COALESCE(sum((amount+Adjustment)-Discount),0) as SRAmount,0 as DenominationAmt,0 as Paid,
	'' as tp from Sales_Return1  where 1>0
	and return_date >='".date("Y-m-d", $timestampFromDate)."'
	and return_date <='".date("Y-m-d", $timestampFromDate)."'
		  and ClientID = '".$ClientID."'
	group by  return_date
	Union 
   
		select 5 as Flag,0 as cntbno,Entry_Date as dt,UserName as name,
	0 as PrevDenTotal,0 as OpAmount,0 as CashSales,0 ,0 as CardSales,0 as SRAmount,((2000*Multiple_2000)+(500*Multiple_500)+(200*Multiple_200)+(100*Multiple_100)+(50*Multiple_50)+(20*Multiple_20)+(10*Multiple_10)+(5*Multiple_5)+(2*Multiple_2)+(1*Multiple_1)+(Multiple_FVP * .50)) as DenominationAmt,0 as Paid,'' as tp from CashAccount_Closing1 Where 1>0 
	and Entry_Date >='".date("Y-m-d", $timestampFromDate)."'
	and Entry_Date <='".date("Y-m-d", $timestampFromDate)."'
			 and ClientID = '".$ClientID."'
		
	) as t1 group by dt");
$c = $c->fetch_assoc();
$test = array('Denomination_List'=>$c );

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login successfull","ResultData"=>$test);
}


			echo json_encode($returnArr);	

			break;
	    
	    
		case 'getEditPurchaseReportForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		
		$user_sql = $con->query("select edit_id,edit_date,ep.purchase_id,ep.grand_total,cp.curtotal FROM `Edit_Purchase1` ep 
		left join ( select distinct purchase_id as curbno,grand_total as curtotal,ClientID from purchase1 )cp on ep.purchase_id=cp.curbno
		and ep.clientid = cp.clientid
		WHERE ep.clientid = '".$ClientID."' and cp.clientid = '".$ClientID."'
			and edit_date >='".date("Y-m-d", $timestampFromDate)."'
	    and edit_date <='".date("Y-m-d", $timestampToDate)."'
		and Round (COALESCE(ep.grand_total,0),2) <> Round(COALESCE(cp.curtotal,0),2)
		order by edit_date,ep.purchase_id");

		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Edit_id'] = $rows['edit_id'];
			$user_result['Edit_date'] = $rows['edit_date'];
			$user_result['Bill_no'] = $rows['purchase_id'];
			$user_result['Grand_total'] = $rows['grand_total'];
			$user_result['Cur_total'] = $rows['curtotal'];
		
			$all_users[] = $user_result;
		}

		$test = array('EditReportList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    
	    case 'getEditReportForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		
		$user_sql = $con->query("select edit_id,edit_date,es.bill_no,es.grand_total,cs.curtotal FROM `Edit_Sales1` es 
		left join ( select distinct bill_no as curbno,grand_total as curtotal,ClientID from sales1 )cs on es.bill_no=cs.curbno
		and es.clientid = cs.clientid
		WHERE es.clientid = '".$ClientID."' 
		and cs.clientid = '".$ClientID."'
		and edit_date >='".date("Y-m-d", $timestampFromDate)."'
	    and edit_date <='".date("Y-m-d", $timestampToDate)."'
		and Round (COALESCE(es.grand_total,0),2) <> Round(COALESCE(cs.curtotal,0),2)
		order by edit_date,es.bill_no");

		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Edit_id'] = $rows['edit_id'];
			$user_result['Edit_date'] = $rows['edit_date'];
			$user_result['Bill_no'] = $rows['bill_no'];
			$user_result['Grand_total'] = $rows['grand_total'];
			$user_result['Cur_total'] = $rows['curtotal'];
		
			$all_users[] = $user_result;
		}

		$test = array('EditReportList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    	case 'getLoginReportForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);

		
		$user_sql = $con->query("select username,min(in_time) as logintime,max(out_time) as logouttime,login_date,max(salescount) as salescount,max(purchasecount) as purchasecount,max(editsalescount) as editsalescount,sum(editpurchasecount) as editpurchasecount from Login1 l
		left join Password pwd on l.password_id = pwd.UserID
		left join (
		 
		  select loginid as lgid,count(bill_no) as salescount,0 as purchasecount,0 AS editsalescount,0 as editpurchasecount from sales1 where ClientID ='".$ClientID."'
		  and date(bill_date)>='".date("Y-m-d", $timestampFromDate)."'
            and date(bill_date)<='".date("Y-m-d", $timestampFromDate)."'
		  group by loginid  
		  UNION
		  select loginid as lgid,0 as salescount,count(purchase_id) as purchasecount,0 AS editsalescount,0 as editpurchasecount from purchase1 where ClientID ='".$ClientID."'   
		  and date(purchase_date)>='".date("Y-m-d", $timestampFromDate)."'
            and date(purchase_date)<='".date("Y-m-d", $timestampFromDate)."'
		  group by loginid 
			UNION
		  select loginid as lgid,0 as salescount,0 as purchasecount,count(edit_id) AS editsalescount,0 as editpurchasecount from Edit_Sales1   
		  where ClientID ='".$ClientID."'   
		  and date(edit_date)>='".date("Y-m-d", $timestampFromDate)."'
            and date(edit_date)<='".date("Y-m-d", $timestampFromDate)."'
		  group by loginid
            
            UNION
		  select loginid as lgid,0 as salescount,0 as purchasecount,0 AS editsalescount,count(edit_id) as editpurchasecount from Edit_Purchase1   
		  where ClientID ='".$ClientID."'   
		  and date(edit_date)>='".date("Y-m-d", $timestampFromDate)."'
            and date(edit_date)<='".date("Y-m-d", $timestampFromDate)."'
		  group by loginid
            
		 )tt on pwd.UserName = tt.lgid
		  
		where l.ClientID ='".$ClientID."' and pwd.ClientID ='".$ClientID."'
		and date(login_date)>='".date("Y-m-d", $timestampFromDate)."'
        and date(login_date)<='".date("Y-m-d", $timestampFromDate)."'
		group by username,login_date 
		order by 2");

		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Username'] = $rows['username'];
			$user_result['Login_time'] = $rows['logintime'];
			$user_result['Logout_time'] = $rows['logouttime'];
			$user_result['Login_date'] = $rows['login_date'];
			$user_result['Sales_Count'] = $rows['salescount'];
			$user_result['Purchase_count'] = $rows['purchasecount'];
			$user_result['Edit_count'] = $rows['editsalescount'];
			$user_result['Edit_Purchasecount'] = $rows['editpurchasecount'];
			$all_users[] = $user_result;
		}

		$test = array('LoginReportList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    	case 'getMultiInvoicebySupplier':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_users=null;
		
		if($data['ClientID'] == '' or $data['Supplier_Name'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$Supplier_Name = strip_tags(mysqli_real_escape_string($con,$data['Supplier_Name']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);
			
				$chekstudentid = $con->query("select clientid,purchase_date,supplier_name,SUM(grand_total+adjustment) as tot,sum(adjustment) as adjustment,sum(grand_total+adjustment) as NetBalance,invoice_no from purchase1  where 1>0
				and purchase_date  >='".$From_date."'
				and purchase_date  <='".$From_date."'
				and purchase1.ClientID='".$ClientID."' and purchase1.supplier_name='".$Supplier_Name."'
		  GROUP by ClientID,purchase_date,supplier_name
				")->fetch_assoc();
				$class_id=$chekstudentid['tot'];
				$class_id2=$chekstudentid['adjustment'];
				$class_id3=$chekstudentid['NetBalance'];
		

			$user_sql = $con->query("select invoice_no,invoice_date,purchase_date,supplier_name,SUM(grand_total+adjustment) as tot,narration from purchase1  where 1>0
            and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
            and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
            and ClientID='".$ClientID."'
            and supplier_name='".$Supplier_Name."'
      GROUP by ClientID,purchase_date,supplier_name,invoice_no,invoice_date");
		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Invoice_no'] = $rows['invoice_no'];
				$user_result['Invoice_latest'] = $rows['invoice_no'];
			$user_result['Invoice_date'] = $rows['invoice_date'];
			$user_result['Invoice_total'] = $rows['tot'];
			$user_result['Narration'] = $rows['narration'];
		
			$all_users[] = $user_result;
		}

		$test = array('MultiInvoicePurchase'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$class_id.','.$class_id2.','.$class_id3,"ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
	    	case 'getSettingsmod':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
		
		if($data['ClientID'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
	
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"");
		
		
				
		
		
		}
		echo json_encode($returnArr);
		break; 
	    
	    
	    case 'getCustomerNamebyMob':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['uid'] == '' or $data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$uid = strip_tags(mysqli_real_escape_string($con,$data['uid']));
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

if($ClientID == 0 && $uid !=0)
{
	$user_sql = $con->query("select Patients_name as patient,Doctor_name as doctor from customer_orders  where  user_id='".$uid."' GROUP BY  Patients_name,Doctor_name");

}
else{
	$user_sql = $con->query("select patient,doctor from sales1  where 1>0
		
			and ClientID='".$ClientID."'
			     GROUP BY  patient,doctor
        ");


}
		
		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Patients_name'] = $rows['patient'];
			$user_result['Doctor_name'] = $rows['doctor'];
		
	
			$all_users[] = $user_result;
		}

		$test = array('CustomerList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
	    
	   
	    case 'getSTotalIndividualCCForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		
		$user_sql = $con->query("select 'cash' flg,bill_no,paid_amount as tot,customer_name,patient  from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
		 and ClientID='".$ClientID."' and type='D'  and CCard=''
	
		UNION 
		select 'credit' flg,bill_no, grand_total as tot,customer_name,patient  from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
		and ClientID='".$ClientID."' and type='c'

		UNION 
		select 'card' flg,bill_no,CCardAmount as tot,customer_name,patient  from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
		and ClientID='".$ClientID."' and type='D'
		and CCard<>''
		 order by bill_no");

		while($rows = $user_sql->fetch_assoc())
		{
		    if($rows['customer_name']== ''){
		     $user_result['customer_name'] = $rows['patient'];   
		    }
		    else{
		      $user_result['customer_name'] = $rows['customer_name'];  
		    }
			$user_result['Flag'] = $rows['flg'];
			$user_result['Bill No'] = $rows['bill_no'];
			$user_result['Total'] = $rows['tot'];
		
	
			$all_users[] = $user_result;
		}

		$test = array('SalesIndividualCCList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 
	    
	    case 'getSTotalCCForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
		$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
		$timestampFromDate = strtotime($From_date);
		$timestampToDate = strtotime($To_Range);
		$countNo=0;
		$StartNo=0;
		$EndBno=0;
		$cashtot=0;
		$credittot=0;
		$cardtot=0;
		
		$chekstudentid = $con->query("select count(bill_no) as countNo,min(bill_no) as StartNo,Max(bill_no) as EndBno from sales1  where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
		and ClientID='".$ClientID."'
	")->fetch_assoc();
		$countNo=$chekstudentid['countNo'];
		$StartNo=$chekstudentid['StartNo'];
		$EndBno=$chekstudentid['EndBno'];
		
		
		$check_cashtot=$con->query("select 'cash' flg,SUM(paid_amount) as tot from sales1 where 1>0 
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
		 and ClientID='".$ClientID."' and  COALESCE(type,'')='D' and CCard=''
	")->fetch_assoc();
	$cashtot=$check_cashtot['tot'];
	if($cashtot == null){
	    
	    $cashtot=0;
	}
	
	$check_credittot=$con->query("select 'credit' flg, SUM(grand_total) as tot from sales1 where 1>0 
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
		and ClientID='".$ClientID."' and  COALESCE(type,'')='c' 
	")->fetch_assoc();
	$credittot=$check_credittot['tot'];
	if($credittot == null)
{
    $credittot=0;
}	
		$check_cardtot=$con->query("select 'card' flg,SUM(CCardAmount) as tot from sales1 where 1>0 
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
		and bill_date <='".date("Y-m-d", $timestampToDate)."'
		and ClientID='".$ClientID."' and  COALESCE(type,'')='D' and CCard<>''
	")->fetch_assoc();
	$cardtot=$check_cardtot['tot'];
	if($cardtot == null){
	    	$cardtot=0;
	}
		
	
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>$cashtot.','.$credittot.','.$cardtot,"ResponseMsg"=>$countNo.','.$EndBno.','.$StartNo);	
		
		
		
		
		}
				echo json_encode($returnArr);
		
		break; 

	    
	    
	    case 'getPTotalCCForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$user_result=null;
			$all_users=array();
			$Status=0;
		if($data['ClientID'] == '' or $data['From_date'] == '' or $data['To_Range'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);
			
			
	
			$user_sql = $con->query("select 'cash' as flg, SUM(grand_total) as tot from purchase1 where 1>0 
			and purchase_date >='".date("Y-m-d", $timestampFromDate)."'
			and purchase_date <='".date("Y-m-d", $timestampToDate)."' 
			and ClientID='".$ClientID."' and type ='d' 
			GROUP by ClientID 
			UNION select 'credit' as flg, SUM(grand_total) as tot from purchase1 where 1>0 
		    and purchase_date >='".date("Y-m-d", $timestampFromDate)."'
			and purchase_date <='".date("Y-m-d", $timestampToDate)."' 
			and ClientID='".$ClientID."' and type <>'d' GROUP by ClientID");
		
		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Flag'] = $rows['flg'];
			$user_result['Tot'] = $rows['tot'];
			
	
			$all_users[] = $user_result;
		}
	

		$test = array('PurchaseCCList'=>$all_users);
			if($user_result != null){
		    
		    	$chekstudentid = $con->query("select SUM(grand_total) as tot from purchase1  where 1>0
            and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
            and purchase_date  <='".date("Y-m-d", $timestampToDate)."' 
            and ClientID='".$ClientID."'
      GROUP by ClientID")->fetch_assoc();
			$Status=$chekstudentid['tot'];
		    
		}
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$Status,"ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
		
	    
	    		case 'getPurchaseReportbyRangeBySupplier':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['date'] == ''  or $data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$date = strip_tags(mysqli_real_escape_string($con,$data['date']));

			$user_sql = $con->query("select clientid,purchase_date,supplier_name,SUM(grand_total) as tot,invoice_no from purchase1  where 1>0
            and purchase_date  >='".$date."'
            and purchase_date  <='".$date."'
            and ClientID='".$ClientID."'
      GROUP by ClientID,purchase_date,supplier_name");
		
		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Supplier Name'] = $rows['supplier_name'];
			$user_result['Grand Total'] = $rows['tot'];
				$user_result['Invoice'] = $rows['invoice_no'];
	
			$all_users[] = $user_result;
		}

		$test = array('PurchaseReportbyRangebySupplier'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Supplier List","ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
	    
		case 'registerClient':
				
			$data = json_decode(file_get_contents('php://input'), true);
		 
			
if($data['ClientID'] == ''  or $data['UserID'] == '' or $data['Password'] == '' or  $data['Name'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Name = strip_tags(mysqli_real_escape_string($con,$data['Name']));
$UserID = strip_tags(mysqli_real_escape_string($con,$data['UserID']));
$Password = strip_tags(mysqli_real_escape_string($con,$data['Password']));
$DefaultPwd=md5('".$Password."');

$checkin_usertbl = $con->query("select * from user where (UserName='".$UserID."') or userid='".$ClientID."' and IsShop='1'");

$checkin_clientbl = $con->query("select * from clients where (Email='".$UserID."') or ClientID='".$ClientID."'");

if($checkin_usertbl->num_rows != 0)
{
    
    	$con->query("update user set UserName= '".$UserID."' ,PassWord='".$DefaultPwd."' where userid= '".$ClientID."' ");
	    
	    
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>" account details updated Successfully");
	
// $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Client account already exist please contact administrator");

}

else{

	if(0>1)
	{
	    
	$con->query("update user set UserName= '".$UserID."' ,PassWord='".$DefaultPwd."' where userid= '".$ClientID."' ");
	    
	    
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>" account details updated Successfully");
	}

	else{


		if(1>0){


$ADD_TO_USER=$con->query("insert into user(`Name`,`UserName`,`PassWord`,`Mobile`,
`Active`,`IsUser`,`IsShop`,`Admin`,`userid`)values
('".$Name."','".$UserID."','".$DefaultPwd."','999999999','1',
'0','1','0','".$ClientID."')");

if($ADD_TO_USER){



if(1>0){


	$ADD_TO_SHOPASSIGN=$con->query("insert into tbl_assigned_shops(`ClientID`,`Managed_ClientID`)values
	('".$ClientID."','".$ClientID."')");

	if($ADD_TO_SHOPASSIGN){

			
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"New Client has been added Successfully!");

	}
	else{

		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");

	}


}
else{

	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");
}



}
else{

	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");


}


		}
		else{


			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");

		}


	}



}



}

echo json_encode($returnArr);	

 

	break;
	    
	    
	    
	    	case 'getTotalStockForClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
		
		if($data['ClientID'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		
		$chekstudentid = $con->query("SELECT COUNT(*) as stockvalue from stock WHERE ClientID='".$ClientID."' and (Purchase_quantity-Sales_quantity > 0)  ")->fetch_assoc();
			$Status=$chekstudentid['stockvalue'];
		
		$chekstudentidproduct = $con->query("SELECT COUNT(*) as pvalue from Product WHERE ClientID='".$ClientID."' ")->fetch_assoc();
			$Statusproduct=$chekstudentidproduct['pvalue'];
	
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$Status.','.$Statusproduct);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 
	    
	    
		case 'getLastUpdateByClient':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_users=null;
	
		
		if($data['ClientID'] == '' or $data['date'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		    
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
	$date=strip_tags(mysqli_real_escape_string($con,$data['date']));
	$fromnew=""."00:00:00";
		$Status="0";
		$chekstudentid = $con->query("select * from clients where (ClientID='".$ClientID."')")->fetch_assoc();
		$chekstudentidlog = $con->query("SELECT * FROM onlinelog WHERE UserName='".$ClientID."' ORDER by Auto desc LIMIT 1")->fetch_assoc();
		
		$Pharmappid=$chekstudentid['PharmappsID'];
		$Status=$chekstudentidlog['Dt'];
    $prod = $con->query("select * from user where isUser='1' and userid='".$ClientID."' and Reg_stamp>='".$date.".".$fromnew."'");
	while($rowss = $prod->fetch_assoc())
	{
	$user_result['id'] = $rowss['id'];
    $user_result['Name'] = $rowss['Name'];
    $user_result['Mobile'] = $rowss['Mobile'];
    $all_users[] = $user_result;
	}
		
	
	


	$test = array('UserNotificationList'=>$all_users,"Remain_notification"=>$Status,"PharmappStatus"=>$Pharmappid);
	
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 
	    
	    
		case 'getAllQueryList':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			 $all_users= (array) null;
		if($data['query'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
			$query = $data['query'];

		
		$user_sql = $con->query($query);
		
		
		while($row = mysql_fetch_row($user_sql))
		{
		    
        $user_result[$row] = $rows[0];
		$all_users[] = $user_result;
			 
		
		}
		
		
		$test = array('SupplierbyClient'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Supplier List Retrieval","ResultData"=>$test);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 
	    
	    
	    		case 'getStockDetailsValuebyid':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
	
			$user_sql = $con->query("select SUM(Unit_Rate*(Purchase_quantity-Sales_quantity)) as purchasevalue,SUM(MRP*(Purchase_quantity-Sales_quantity)) as mrpvalue,SUM(Sales_Rate*(Purchase_quantity-Sales_quantity)) as salevalue ,COUNT(*) as stockvalue ,SUM(Unit_Rate*(Purchase_quantity-Sales_quantity)) as stockvaluecur
            from stock WHERE ClientID='".$ClientID."'");
		
		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['Purchase Value'] = $rows['purchasevalue'];
			$user_result['Mrp Value'] = $rows['mrpvalue'];
			$user_result['Sale Value'] = $rows['salevalue'];
			$user_result['Stock Value In'] = $rows['stockvaluecur'];
			$user_result['Stock Value'] = $rows['stockvalue'];
	
			$all_users[] = $user_result;
		}

		$test = array('StockValues'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Value Access","ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 


		case 'getBillsForComparison':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_users=null;
		
		if($data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$user_sql = $con->query("select 'SALES ITEM (FINAL YEAR)' as flag,bill_no from sales1 where  bill_no not in ( select distinct bill_no from sales_item1 where ClientID ='".$ClientID."')     
			and ClientID ='".$ClientID."'
			UNION
			select 'SALES (FINAL YEAR)' as flag,bill_no from sales_item1 where  bill_no not in (
				select distinct bill_no from sales1 where ClientID ='".$ClientID."')     
			and ClientID ='".$ClientID."'
			UNION
			select 'SALES ITEM (PREV.YEAR)' as flag,bill_no from sales where  bill_no not in ( select distinct bill_no from sales_item where ClientID ='".$ClientID."')     
			and ClientID ='".$ClientID."'
			UNION
			select 'SALES (PREV.YEAR)' as flag,bill_no from sales_item where  bill_no not in (
				select distinct bill_no from sales where ClientID ='".$ClientID."')     
			and ClientID ='".$ClientID."'
			ORDER BY 2");
		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Flag Value'] = $rows['flag'];
			$user_result['Bill No'] = $rows['bill_no'];
		
			$all_users[] = $user_result;
		}

		$test = array('SaleBillComparison'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
	    
	    
	    
	    
	     case 'addCustomerOrderListSingle':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['query'] == '' or $data['image'] == '' or $data['image_name'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$query = $data['query'];
	$image_name=strip_tags(mysqli_real_escape_string($con,$data['image_name']));
					$image = $data['image'];
					
					if($image_name != 1){
					  	$decodedImage = base64_decode($image);
					$file_nam = file_put_contents("uploads/".$image_name.".jpg", $decodedImage);  
					}
					

$con->multi_query($query);

if($con){
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Status Updated successfully!");
}
else{
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Failed to update");

}

		  

}
echo json_encode($returnArr);
		
break; 
	    
	    
	   	    
	    case 'updateData':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['query'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$query = $data['query'];

try{
  $con->multi_query($query);  
  
if($con){
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Data Inserted successfully!");
}
else{
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Failed to update");

}



// new code 

// $quires = explode(';',$query);

//   $returnArr = array("ResponseMsg"=>$quires);

// for($i = 0; $i <= count($quires); $i++)
// {
    
//     if($quires[$i] != "")
//     {
//         if($con->query(trim(preg_replace('/\s+/',' ', $quires[$i]))))
//     {
//         $returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Status Updated successfully!");
//     }
//     else
//     {
//         $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Failed to update");

//     }
    
//     }
    
    
    
// }

 
// new code close

}



catch(Exception $e){

    $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>$e->getMessage());
    
}


}
echo json_encode($returnArr);
		
break; 




		case 'isCustomerOStatusupdate':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['Order_Id'] == '' or $data['ClientID'] == ''  or $data['status'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Order_Id = strip_tags(mysqli_real_escape_string($con,$data['Order_Id']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));


$con->query("update customer_orders set Status='".$status."' where (ClientID='".$ClientID."') and Order_Id='".$Order_Id."'");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Status Updated successfully!");
		  

}
echo json_encode($returnArr);
		
break; 


		
			case 'getMultisuplierExistbyProduct':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_users=null;
		
		if($data['item_description'] == '' or $data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$item_description = strip_tags(mysqli_real_escape_string($con,$data['item_description']));
		

			$user_sql = $con->query("Select p1.item_description as itm2,p1.supplier_name as supp2,max(PRate1) as PRate1,max(idd2) as idd2,max(sortid) as sortid from (


Select pi.clientid,item_description,company_name,supplier_name,purchase_date as dt,unit as PRate1,COALESCE((((year(purchase_date)*3650000) + (month(purchase_date)*120000) + (day(purchase_date))+p.purchase_id) *100000),0) as idd2,0 as sortid from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$ClientID."' and p.ClientID ='".$ClientID."'    and item_description ='".$item_description."'

Union    
   
 Select pi.clientid,item_description,company_name,supplier_name,purchase_date as dt,unit as PRate1,COALESCE((((year(purchase_date)*3650) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd2,0 as sortid  from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$ClientID."' and p.ClientID ='".$ClientID."'    and item_description ='".$item_description."'
Union
select clientid,item_description,company_name,supplier_name,invoice_date as dt,purchase_rate as PRate1,COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd2,0 as sortid from opening_stock1 where 1>0
and clientid='".$ClientID."' and COALESCE(supplier_name,'')<>'' and item_description ='".$item_description."'
Union
select t.clientid,item_description,company_name,branch as supplier_name,transfer_date as dt,purchase_rate as PRate1,COALESCE((((year(invoice_date)) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd2,0 as sortid from transfer1 t
 left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."' and ti.Clientid = '".$ClientID."'  and item_description ='".$item_description."'
Union
select t.clientid,item_description,company_name,branch as supplier_name,transfer_date as dt,purchase_rate as PRate1,
    COALESCE((((year(invoice_date)) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd2,0 as sortid from transfer t
left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$ClientID."' And ti.clientid='".$ClientID."'  and item_description ='".$item_description."'

 UNION

 select p.clientid,Product_name as item_description,Short_id as company_name,supplier_name,'' as dt,0 as PRate1,0 as idd2,sort_id as sortid from Product p 
    left join supplier s on p.ClientID = s.clientid where  p.clientid='".$ClientID."' And s.clientid='".$ClientID."'
    and Product_name ='".$item_description."'
    
    
) p1 where p1.item_description ='".$item_description."'
and p1.supplier_name in ( select distinct supplier_name from supplier where  clientid ='".$ClientID."')
group by  p1.item_description,p1.supplier_name
ORDER BY COALESCE(sortid,10000),idd2 desc,2 ");
		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Supplier_Name'] = $rows['supp2'];
			$user_result['Rate'] = $rows['PRate1'];
		
			$all_users[] = $user_result;
		}

		$test = array('Multisuplier'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"List Retrieval","ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 




		





		case 'CheckPorder_Assigned':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
		
		if($data['ProductName'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$supplierName=strip_tags(mysqli_real_escape_string($con,$data['supplierName']));
		$ProductName=$data['ProductName'];
		$status=strip_tags(mysqli_real_escape_string($con,$data['status']));
		$OrderDate=strip_tags(mysqli_real_escape_string($con,$data['OrderDate']));
		$timestampFromDate = strtotime($OrderDate);
		$chekuserid = $con->query("select * from received_orders1 where (ProductName = '".$ProductName."') and Status='N'")->fetch_assoc();
		$ch_uid=$chekuserid['OrderDate'];
		if($chekuserid['OrderDate']!= null){

			$ch_uid=$chekuserid['OrderDate'];
			$sp_nm=$chekuserid['Supplier'];
			$today = time();
			$interval = strtotime($ch_uid) - $today;
			$days = floor($interval / 86400); // 1 day
			if($days < 7) {
			
				$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Order Already made from : ".$sp_nm);
			}
			else{
				$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"No history found");
				
			}
		}
		else{

	
			$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"No history founds");
		
		}

	
		
			
		
		
		
		
		}
		echo json_encode($returnArr);
		
		break; 




		case 'getPurchaseReportbyRange':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
			$class_id=0;
		if($data['From_date'] == '' or $data['To_Range'] == '' or $data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);
			
			$chekstudentid = $con->query("select SUM(grand_total) as ntot from purchase1  where 1>0
			and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
			and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			")->fetch_assoc();
			$class_id=$chekstudentid['ntot'];

			$user_sql = $con->query("select purchase_date,supplier_name,SUM(grand_total) as tot from purchase1  where 1>0
			and purchase_date  >='".date("Y-m-d", $timestampFromDate)."'
			and purchase_date  <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			     GROUP BY  purchase_date
            ORDER BY purchase_date");
		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Purchase Date'] = $rows['purchase_date'];
			$user_result['Supplier Name'] = $rows['supplier_name'];
			$user_result['Grand Total'] = $rows['tot'];
	
			$all_users[] = $user_result;
		}

		$test = array('PurchaseReportbyRange'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$class_id,"ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
		



		case 'getSalesReportbyRange':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		
		if($data['From_date'] == '' or $data['To_Range'] == '' or  $data['ClientID'] == '' or $data['Avgamount'] == '' or $data['cond'] == ''  )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		else{
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
				$cond = strip_tags(mysqli_real_escape_string($con,$data['cond']));
			$Avgamount = strip_tags(mysqli_real_escape_string($con,$data['Avgamount']));
			$From_date = strip_tags(mysqli_real_escape_string($con,$data['From_date']));
			$To_Range = strip_tags(mysqli_real_escape_string($con,$data['To_Range']));
	
			$timestampFromDate = strtotime($From_date);
			$timestampToDate = strtotime($To_Range);
			
			
				$chekstudentid = $con->query("select SUM(grand_total) as ntot from sales1 where 1>0
			and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
		")->fetch_assoc();
			$class_id=$chekstudentid['ntot'];
			
	
			
	
		    if($cond=='1'){
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by bill_date asc");   
		    }
		    
		        else if($cond=='2'){
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by bill_date desc");   
		    }
		            else if($cond=='3'){
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by tot asc");   
		    }
		            else if($cond=='4') {
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by tot desc");   
		    }
		        else if($cond=='5') {
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag,(maxbill-minbill) as nbill from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by nbill asc");   
		    }
		    
		       else  {
		        
		        		$user_sql = $con->query("	select billno,minbill,maxbill,bill_date,tot,totnew,(case when (tot>'".$Avgamount."') then ('EXCEED') else ('BELOW') end) as flag,(maxbill-minbill) as nbill from (

select count(bill_no) as billno,min(bill_no) as minbill,max(bill_no) as maxbill,bill_date,SUM(grand_total) as tot,SUM(paid_amount) as totnew from sales1 where 1>0
		and bill_date >='".date("Y-m-d", $timestampFromDate)."'
			and bill_date <='".date("Y-m-d", $timestampToDate)."'
			and ClientID='".$ClientID."'
			GROUP BY bill_date
			)salesNEW order by nbill desc");   
		    }
		 
		


		
		while($rows = $user_sql->fetch_assoc())
		{

		
			$user_result['Bill Date'] = $rows['bill_date'];
			$user_result['Total Bill Amount'] = $rows['tot'];
			$user_result['Total Paid Amount'] = $rows['totnew'];
			$user_result['BillNo'] = $rows['billno'];
			$user_result['Minbill'] = $rows['minbill'];
			$user_result['Maxbill'] = $rows['maxbill'];
						$user_result['Flag'] = $rows['flag'];
	
			$all_users[] = $user_result;
		}

		$test = array('SalesReportbyRange'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$class_id,"ResultData"=>$test);
		
	}
	
		echo json_encode($returnArr);
		
		break; 
		
		


		case 'addClient':
				
			$data = json_decode(file_get_contents('php://input'), true);
		 
			
if($data['ClientID'] == '' or $data['ClientName'] == '' or $data['UserID'] == '' or $data['Password'] == ''  or $data['Description'] == '' or $data['Address1'] == '' 
 or $data['Address2'] == '' or $data['Address3'] == '' or $data['Phone'] == '' or $data['Type'] == ''
 or $data['Cflag'] == '' or $data['TIN'] == '' or $data['DL'] == '' or $data['Sales_Category'] == ''
 or $data['DL2'] == ''  or $data['BranchID'] == ''  or  $data['Constituency'] == '' or  $data['Opening_Date'] == ''
 or   $data['Inactive'] == '' or   $data['CreditDays'] == '' or   $data['AllowOnlineOrders'] == '' or   $data['Email'] == '' 
 or   $data['BillingID'] == '' or   $data['IGSTCustomer'] == '' or   $data['DefaultBank'] == '' or   $data['Note'] == '' 
 or   $data['PinCode'] == '' or   $data['CreditLimit'] == '' or   $data['IsBranch'] == '' or   $data['IsCustomer'] == ''
 or   $data['Area'] == '' or   $data['Location'] == '' or   $data['WhatsApp1'] == '' or   $data['WhatsApp2'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$UserID = strip_tags(mysqli_real_escape_string($con,$data['UserID']));
$ClientName = strip_tags(mysqli_real_escape_string($con,$data['ClientName']));
$Description = strip_tags(mysqli_real_escape_string($con,$data['Description']));
$Address1 = strip_tags(mysqli_real_escape_string($con,$data['Address1']));
$Address2 = strip_tags(mysqli_real_escape_string($con,$data['Address2']));
$Address3 = strip_tags(mysqli_real_escape_string($con,$data['Address3']));
$Phone = strip_tags(mysqli_real_escape_string($con,$data['Phone']));
$Type = strip_tags(mysqli_real_escape_string($con,$data['Type']));
$Cflag = strip_tags(mysqli_real_escape_string($con,$data['Cflag']));
$TIN = strip_tags(mysqli_real_escape_string($con,$data['TIN']));
$DL = strip_tags(mysqli_real_escape_string($con,$data['DL']));
$Sales_Category = strip_tags(mysqli_real_escape_string($con,$data['Sales_Category']));
$DL2 = strip_tags(mysqli_real_escape_string($con,$data['DL2']));
$BranchID = strip_tags(mysqli_real_escape_string($con,$data['BranchID']));
$Constituency = strip_tags(mysqli_real_escape_string($con,$data['Constituency']));
$Opening_Date = strip_tags(mysqli_real_escape_string($con,$data['Opening_Date']));
$Inactive = strip_tags(mysqli_real_escape_string($con,$data['Inactive']));
$CreditDays = strip_tags(mysqli_real_escape_string($con,$data['CreditDays']));
$AllowOnlineOrders = strip_tags(mysqli_real_escape_string($con,$data['AllowOnlineOrders']));
$Email = strip_tags(mysqli_real_escape_string($con,$data['Email']));
$BillingID = strip_tags(mysqli_real_escape_string($con,$data['BillingID']));
$IGSTCustomer = strip_tags(mysqli_real_escape_string($con,$data['IGSTCustomer']));
$DefaultBank = strip_tags(mysqli_real_escape_string($con,$data['DefaultBank']));
$Note = strip_tags(mysqli_real_escape_string($con,$data['Note']));
$PinCode = strip_tags(mysqli_real_escape_string($con,$data['PinCode']));
$CreditLimit = strip_tags(mysqli_real_escape_string($con,$data['CreditLimit']));
$IsBranch = strip_tags(mysqli_real_escape_string($con,$data['IsBranch']));
$IsCustomer = strip_tags(mysqli_real_escape_string($con,$data['IsCustomer']));
$Password = strip_tags(mysqli_real_escape_string($con,$data['Password']));
$Area = strip_tags(mysqli_real_escape_string($con,$data['Area']));
$Location = strip_tags(mysqli_real_escape_string($con,$data['Location']));
$WhatsApp1 = strip_tags(mysqli_real_escape_string($con,$data['WhatsApp1']));
$WhatsApp2 = strip_tags(mysqli_real_escape_string($con,$data['WhatsApp2']));
$DefaultPwd=md5('".$Password."');

$checkin_usertbl = $con->query("select * from user where (UserName='".$UserID."') or userid='".$ClientID."' and IsShop='1'");
$checkin_clientbl = $con->query("select * from clients where (Email='".$Email."') or ClientID='".$ClientID."'");

if($checkin_usertbl->num_rows != 0)
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Client account already exist please contact administrator");
}

else{

	if($checkin_clientbl->num_rows != 0)
	{
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Client account already exist please contact administrator");
	}

	else{


		$ADD_TO_CLIENT=$con->query("insert into clients(`ClientID`,`ClientName`,`Description`,`Address1`,
		`Address2`,`Address3`,`Phone`,`Type`,`Cflag`,`TIN`,`DL`,`Sales_Category`,`DL2`,`BranchID`,`Constituency`,`Opening_Date`,`Inactive`,`CreditDays`,`AllowOnlineOrders`,
		`Email`,`BillingID`,`IGSTCustomer`,`DefaultBank`,`Note`,`PinCode`,`CreditLimit`,`IsBranch`,`IsCustomer`,`Area`,`Location`,`WhatsApp1`
		,`WhatsApp2`)values
		('".$ClientID."','".$ClientName."','".$Description."','".$Address1."','".$Address2."',
		'".$Address3."','".$Phone."','".$Type."','".$Cflag."','".$TIN."','".$DL."','".$Sales_Category."','".$DL2."','".$BranchID."'
		,'".$Constituency."','".$Opening_Date."','".$Inactive."','".$CreditDays."','".$AllowOnlineOrders."','".$Email."','".$BillingID."'
		,'".$IGSTCustomer."','".$DefaultBank."','".$Note."','".$PinCode."','".$CreditLimit."','".$IsBranch."','".$IsCustomer."'
		,'".$Area."','".$Location."','".$WhatsApp1."','".$WhatsApp2."')");


		if($ADD_TO_CLIENT){


$ADD_TO_USER=$con->query("insert into user(`Name`,`UserName`,`PassWord`,`Mobile`,
`Active`,`IsUser`,`IsShop`,`Admin`,`userid`)values
('".$ClientName."','".$UserID."','".$DefaultPwd."','".$Phone."','1',
'0','1','0','".$ClientID."')");

if($ADD_TO_USER){

	$ADD_TO_PERMISSION=$con->query("insert into tbl_permissions(`ClientID`)values
('".$ClientID."')");

if($ADD_TO_PERMISSION){


	$ADD_TO_SHOPASSIGN=$con->query("insert into tbl_assigned_shops(`ClientID`,`Managed_ClientID`)values
	('".$ClientID."','".$ClientID."')");

	if($ADD_TO_SHOPASSIGN){

			
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"New Client has been added Successfully!");

	}
	else{

		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");

	}


}
else{

	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");
}



}
else{

	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");


}


		}
		else{


			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Server Encountered a problem please try after sometime");

		}


	}



}



}

echo json_encode($returnArr);	

 

	break;


		case 'getPurchaseOrderListbyOdo':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			$all_users=null;
		if($data['orderNo'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$orderNo=strip_tags(mysqli_real_escape_string($con,$data['orderNo']));
		
		$user_sql = $con->query("select * from received_orders1 where OrderNo=".$orderNo." group by ProductName order by Auto desc");
		
		while($rows = $user_sql->fetch_assoc())
		{
		
		$user_result['ClientID'] = $rows['ClientID'];
		$user_result['OrderNo'] = $rows['OrderNo'];
		$user_result['Supplier'] = $rows['Supplier'];
		$user_result['ProductName'] = $rows['ProductName'];
		$user_result['Company'] = $rows['Company'];
		$user_result['Pack'] = $rows['Pack'];
		$user_result['OrderID'] = $rows['OrderID'];
		$user_result['Quantity'] = $rows['Quantity'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['Status'] = $rows['Status'];
		$user_result['TotalQuantity'] = $rows['TotalQuantity'];
		$user_result['unitRate'] = $rows['unitRate'];
		$user_result['Rate'] = $rows['Rate'];
		$user_result['Stock'] = $rows['Stock'];
		$user_result['SalesQuantity'] = $rows['SalesQuantity'];
		$user_result['OrderDate'] = $rows['OrderDate'];
		$all_users[] = $user_result;
			
		
		
		
		}
		
		
		$test = array('OrderbyPurchaseList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Orderby Purchase List Retrieval","ResultData"=>$test);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 



		case 'getOStock':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
		
		if($data['orderNo'] == '' or $data['ClientID'] == '' )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$orderNo=strip_tags(mysqli_real_escape_string($con,$data['orderNo']));
			$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			
			if($ClientID !='0'){
			   	$chekstudentid = $con->query("select * from customer_orders where ClientID='".$ClientID."' and (Order_Id='".$orderNo."') LIMIT 1")->fetch_assoc();
			$Status=$chekstudentid['Status'];
		 
			}
			else{
			       	$chekstudentid = $con->query("select * from customer_orders where (Order_Id='".$orderNo."') and Status !='R' LIMIT 1")->fetch_assoc();
			$Status=$chekstudentid['Status'];
			}
		
	
	
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$Status);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 



		case 'del_itemFromPorderreq';

	    
	$data = json_decode(file_get_contents('php://input'), true);
	if($data['id'] == '' or $data['ProductName'] == ''  )
	{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	}

	else{

		$id = strip_tags(mysqli_real_escape_string($con,$data['id']));
		$ProductName = strip_tags(mysqli_real_escape_string($con,$data['ProductName']));

		$con->query("delete from received_orders1  where OrderNo='".$id."'  and ProductName='".$ProductName."' ");

		
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Item Deleted successfully ");


		echo json_encode($returnArr);	

	}
			



	break;


		case 'del_assignreq';

	    
	$data = json_decode(file_get_contents('php://input'), true);
	if($data['id'] == ''  )
	{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	}

	else{

		$id = strip_tags(mysqli_real_escape_string($con,$data['id']));

		$con->query("delete from tbl_assigned_shops  where id=".$id."");

		
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Assignment Deleted successfully ");


		echo json_encode($returnArr);	

	}
			



	break;


	case 'getAllAssignedShopListbyemail':
	
	
		$data = json_decode(file_get_contents('php://input'), true);
		 $all_users= (array) null;
	if($data['email'] == '')
	{
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	}
	
	else {
	$email=strip_tags(mysqli_real_escape_string($con,$data['email']));
	

	
	
		$user_sql = $con->query("select LastUpdateDt,clients.*,user.*,tbl_assigned_shops.id as newid, tbl_assigned_shops.Managed_ClientID from tbl_assigned_shops LEFT JOIN clients ON tbl_assigned_shops.Managed_ClientID=clients.ClientID LEFT JOIN user ON tbl_assigned_shops.ClientID=user.userid left join ( select username,max(dt) as LastUpdateDt from onlinelog group by username )dd on clients.ClientID = dd.username and tbl_assigned_shops.Managed_ClientID =dd.username where user.UserName=('".$email."') and user.IsUser!=1 order by sort_id asc;");

	
	
	while($rows = $user_sql->fetch_assoc())
	{
	$user_result['id'] = $rows['newid'];
	$user_result['ClientName'] = $rows['ClientName'].','.$rows['Area'].' , '.'Location';
	$user_result['Managed_ClientID'] = $rows['Managed_ClientID'];
	$user_result['TIN'] = $rows['ClientName'];
	$user_result['Phone'] = $rows['Phone'];
	$user_result['DL2'] = $rows['DL2'];
	$user_result['PharmappsID'] = $rows['PharmappsID'];
		$user_result['LastUpdateDt'] = $rows['LastUpdateDt'];
	$all_users[] = $user_result;
		
	
	
	
	}
	
	
	$test = array('AllAssignedShopList'=>$all_users);
	
	
	
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"AllAssignedShopList Retrieval","ResultData"=>$test);
	
	
	echo json_encode($returnArr);		
	
	
	
	
	}
	
	break; 






		case 'getAllAssignedShopList':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
			 $all_users= (array) null;
		if($data['ClientID'] == '')
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		}
		
		else {
		$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		
		$user_sql = $con->query("select clients.*,tbl_assigned_shops.id as newid,tbl_assigned_shops.Managed_ClientID from tbl_assigned_shops
		JOIN clients ON tbl_assigned_shops.Managed_ClientID=clients.ClientID 
		where tbl_assigned_shops.ClientID=".$ClientID."");
		
		
		while($rows = $user_sql->fetch_assoc())
		{
			$user_result['id'] = $rows['newid'];
		$user_result['ClientName'] = $rows['ClientName'];
		$user_result['Managed_ClientID'] = $rows['Managed_ClientID'];
		$user_result['TIN'] = $rows['TIN'];
		$user_result['Phone'] = $rows['Phone'];
		$user_result['DL2'] = $rows['DL2'];
		$all_users[] = $user_result;
			
		
		
		
		}
		
		
		$test = array('AllAssignedShopList'=>$all_users);
		
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"AllAssignedShopList Retrieval","ResultData"=>$test);
		
		
		echo json_encode($returnArr);		
		
		
		
		
		}
		
		break; 




		case 'isPermissionisPharmappView':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['status'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));


$con->query("update tbl_permissions set isPharmappView='".$status."' where (ClientID='".$ClientID."') ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 


			break;



		case 'isPermissionisMultisupplierView':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['status'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));


$con->query("update tbl_permissions set isMultisupplierView='".$status."' where (ClientID='".$ClientID."') ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 


			break;



		case 'isPermissionisStockReportView':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['ClientID'] == '' or $data['status'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));


$con->query("update tbl_permissions set isStockReportView='".$status."' where (ClientID='".$ClientID."') ");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
		  

}


echo json_encode($returnArr);	

	 


			break;


			case 'isPermissionisPurchaseOrderView':

				$data = json_decode(file_get_contents('php://input'), true);
					
					
					
	if($data['ClientID'] == '' or $data['status'] == ''  )
	{
	$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	} 
	
	else {
	
	$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
	$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
	
	
	$con->query("update tbl_permissions set isPurchaseOrderView='".$status."' where (ClientID='".$ClientID."') ");
	
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
			  
	
	}
	
	
	echo json_encode($returnArr);	
	
		 
	
	
				break;



				case 'isPermissionisSaleReportView':

					$data = json_decode(file_get_contents('php://input'), true);
						
						
						
		if($data['ClientID'] == '' or $data['status'] == ''  )
		{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
		} 
		
		else {
		
		$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
		$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
		
		
		$con->query("update tbl_permissions set isSaleReportView='".$status."' where (ClientID='".$ClientID."') ");
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
				  
		
		}
		
		
		echo json_encode($returnArr);	
		
			 
		
		
					break;


					case 'isPermissionisPurchaseReportView':

						$data = json_decode(file_get_contents('php://input'), true);
							
							
							
			if($data['ClientID'] == '' or $data['status'] == ''  )
			{
			$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
			} 
			
			else {
			
			$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
			$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
			
			
			$con->query("update tbl_permissions set isPurchaseReportView='".$status."' where (ClientID='".$ClientID."') ");
			
			$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
					  
			
			}
			
			
			echo json_encode($returnArr);	
			
				 
			
			
						break;


						case 'isPermissionisStockAlertView':

							$data = json_decode(file_get_contents('php://input'), true);
								
								
								
				if($data['ClientID'] == '' or $data['status'] == ''  )
				{
				$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
				} 
				
				else {
				
				$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
				$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
				
				
				$con->query("update tbl_permissions set isStockAlertView='".$status."' where (ClientID='".$ClientID."') ");
				
				$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
						  
				
				}
				
				
				echo json_encode($returnArr);	
				
					 
				
				
							break;



							case 'isPermissionisOrderHistoryView':

								$data = json_decode(file_get_contents('php://input'), true);
									
									
									
					if($data['ClientID'] == '' or $data['status'] == ''  )
					{
					$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
					} 
					
					else {
					
					$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
					$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
					
					
					$con->query("update tbl_permissions set isOrderHistoryView='".$status."' where (ClientID='".$ClientID."') ");
					
					$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permission Updated successfully!");
							  
					
					}
					
					
					echo json_encode($returnArr);	
					
						 
					
					
								break;
	




				case 'getShopbyId':
	
	
								$data = json_decode(file_get_contents('php://input'), true);
	if($data['shop_id'] == '')
	{
		$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	}
					
				else {
					
	
	
	$shop_id = strip_tags(mysqli_real_escape_string($con,$data['shop_id']));
	
		$settin = $con->query("select * from clients where ClientID='".$shop_id."' ")->fetch_assoc();
		
		
		
	
		$test = array('Client_details'=>$settin);
	
		
		
		$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shop Details","ResultData"=>$test);
						
					
				echo json_encode($returnArr);		
				
						
	
	
					}
				
						
						
				break; 


				case 'verifyMobile':

			$data = json_decode(file_get_contents('php://input'), true);
				
				
				
if($data['mobile'] == '' or $data['random_otp'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 

else {

$mobile = strip_tags(mysqli_real_escape_string($con,$data['mobile']));
$random_otp = strip_tags(mysqli_real_escape_string($con,$data['random_otp']));


/*$url = "https://www.fast2sms.com/dev/bulkV2?authorization=AfEk7IRF84jWiOoaMDvxN0lgrP5SQsuZcnbV3ypTmeJdqYX6hKzmjaUV9RCuBpJfi0OAqGZNwgtePTYc&route=dlt&sender_id=SYSIRO&message=131154&variables_values=$random_otp&flash=0&numbers=".$mobile;*/


$url = " https://www.fast2sms.com/dev/bulkV2?authorization=AfEk7IRF84jWiOoaMDvxN0lgrP5SQsuZcnbV3ypTmeJdqYX6hKzmjaUV9RCuBpJfi0OAqGZNwgtePTYc&route=otp&variables_values=".$random_otp."&flash=0&numbers=".$mobile."";

/*$url = "https://smsapi.24x7sms.com/api_2.0/SendSMS.aspx?APIKEY=QqFVW3aYciH&MobileNo=".$mobile."&SenderID=MEDSFT&Message=Your+OTP+for+Login+is+".$random_otp.".+Please+do+not+share+this+message+with+anyone.+This+OTP+is+valid+for+2+minutes+-+MEDISOFT&ServiceName=TEMPLATE_BASED&DLTTemplateID=1007321869209554673";*/
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);


$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$resp);
		  

}


echo json_encode($returnArr);	

	 


			break;



case 'register':

$data = json_decode(file_get_contents('php://input'), true);


if( $data['name'] == '' or $data['role'] == '' or $data['mobile'] == '' 

or $data['email'] == '' or $data['password'] == '' or $data['shop_id'] == '' ) 
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {

$name = strip_tags(mysqli_real_escape_string($con,$data['name']));
$email = strip_tags(mysqli_real_escape_string($con,$data['email']));
$password= strip_tags(mysqli_real_escape_string($con,$data['password']));
$mobile =strip_tags(mysqli_real_escape_string($con,$data['mobile']));
$role =strip_tags(mysqli_real_escape_string($con,$data['role']));
$shop_id =strip_tags(mysqli_real_escape_string($con,$data['shop_id']));

$hashpwd=md5($password);

	$checkmob = $con->query("select * from user where Mobile='".$mobile."'");

	if($checkmob->num_rows != 0)
	{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Account Already exist please login to proceed");
	}
	else{

		$con->query("insert into user(`Name`,`UserName`,`PassWord`,`mobile`,`IsUser`,`userid`,`Active`,`IsShop`,`Admin`,`app_login_count`,`max_connections`)values

	('".$name."','".$email."','".$hashpwd."','".$mobile."','".$role."','".$shop_id."','1','0','0','1','1')");
	
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Successfully Registered!");

	}



}


echo json_encode($returnArr);
break;








case 'login':


				$data = json_decode(file_get_contents('php://input'), true);
				if($data['username'] == '' or $data['password'] == '')
				{
					$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");

				}

				else {
					$username = strip_tags(mysqli_real_escape_string($con,$data['username']));
					$password = strip_tags(mysqli_real_escape_string($con,$data['password']));
					$hashpwd=md5($password);
					
			   

					$chek = $con->query("select user.* from user 
					JOIN tbl_settings on user.id=tbl_settings.user_id
					where (Mobile='".$username."' or UserName='".$username."') and PassWord='".$hashpwd."' and Package_ID !='0'");

if($chek->num_rows != 0)
{
 
     	$chekstudentid = $con->query("select user.* from user 
					JOIN tbl_settings on user.id=tbl_settings.user_id
					where (Mobile='".$username."' or UserName='".$username."') and PassWord='".$hashpwd."' and Package_ID !='0'and user.Active=1 ")->fetch_assoc();
      
if (is_null($chekstudentid)){
    
     $app_login_count=0;
}
else{
     $app_login_count=$chekstudentid['id'];
    $con->query("UPDATE tbl_settings SET enable_forcelogout='0' WHERE user_id='".$app_login_count."'");
}
    
$c = $con->query("select user.Name,user.id,user.Mobile,user.IsUser,user.IsShop,user.UserName,user.Active,user.Admin,user.Package_ID,user.app_login_count,user.is_demo,
user.userid,clients.ClientName,clients.Phone,clients.Address1,clients.Address2,clients.Address3,clients.Email,clients.PharmappsID,clients.Type2  from user JOIN clients ON user.userid=clients.ClientID where (Mobile='".$username."' or UserName='".$username."')  and PassWord='".$hashpwd."' ");
$c = $c->fetch_assoc();
$test = array('User_details'=>$c );
$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Login successfull","ResultData"=>$test);
}
else
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Invalid Email/Mobile No or Password or Package Error or Software settings not updated!!!");
}




				}
				

				echo json_encode($returnArr);	





				break;




				case 'getProductDetailsbyName':


					$data = json_decode(file_get_contents('php://input'), true);
					if($data['ClientID'] == '' or $data['Product_Name'] == '')
					{
						$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
	
					}
	
					else {
						$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
						$Product_Name =$data['Product_Name'];
		
	$c = $con->query("SELECT MAX(MRP) as maxmrp ,SUM(Purchase_quantity -Sales_quantity) as stk ,uPack,manufacturer,Sales_Rate FROM `stock` WHERE ClientID='".$ClientID."' and Product_Name='".$Product_Name."' ");
	$c = $c->fetch_assoc();
	$test = array('Stock_Details'=>$c );
	
	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	}
	
	
	
	
	
				
					echo json_encode($returnArr);	
	
	
	
	
	
					break;



                    case 'getPermissionViewbyClient':


                        $data = json_decode(file_get_contents('php://input'), true);
                        if($data['ClientID'] == '')
                        {
                            $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
        
                        }
        
                        else {
                            $ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
                           
            
        $c = $con->query("SELECT * FROM `tbl_permissions` WHERE ClientID='".$ClientID."'");
        $c = $c->fetch_assoc();
        $test = array('Client_Permissions'=>$c );
        
        $returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Permissions","ResultData"=>$test);
        }
        
        
                        echo json_encode($returnArr);	
        
        
        
        
        
                        break;
        
	
			
			
			
				case 'getPurchaseOrderList':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	
	$all_users=null;
	$countvalue=0;

if($data['Client_ID'] == '' or $data['Supplier_Name'] == '' or $data['B_From_Date'] == '' or $data['B_To_Date'] == '' or $data['sort'] == ''   )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong || Params mismatch");
}

else {

$Client_ID=strip_tags(mysqli_real_escape_string($con,$data['Client_ID']));
$Supplier_Name=strip_tags(mysqli_real_escape_string($con,$data['Supplier_Name']));
$sort=strip_tags(mysqli_real_escape_string($con,$data['sort']));
$B_From_Date=strip_tags(mysqli_real_escape_string($con,$data['B_From_Date']));
$B_To_Date=strip_tags(mysqli_real_escape_string($con,$data['B_To_Date']));
$timestampFromDate = strtotime($B_From_Date);
$timestampToDate = strtotime($B_To_Date);

if($Supplier_Name =='0')
{
    if($sort=='Stock'){
      $user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,COALESCE(stk,'0') as stk,(case when COALESCE(StwFlag,0)>0 then (StwNewSupp) else supplier_name end) as supplier_name,
0 as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff,qnos,WhStock
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,MRP from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0
and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(

Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36".$Client_ID."000) + (month(purchase_date)*120000) + (day(purchase_date))+p.purchase_id) *100000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'    
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+".$Client_ID."000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.Clientid = '".$Client_ID."'  
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'  

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36".$Client_ID."000) + (month(purchase_date)*120000) + (day(purchase_date))+p.purchase_id) *100000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'   group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.ClientID ='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'    group by ti.clientid,item_description,company_name,branch



) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'    
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0





) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier ,OrderNo,1 as RecOrdff,Quantity as qnos from received_orders1 
    where clientid = '".$Client_ID."' and st_reason IS NULL and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company   
    
    left join ( select distinct product_name as stwPName,manufacturer as stwMan,'ASWAS PHARMA' as StwNewSupp,1 as StwFlag,(purchase_quantity-sales_quantity) as WhStock from stock_wholesale)sw on
    sqtywithstk.item_description = sw.stwpname and sqtywithstk.company_name = sw.stwMan
     where (supplier_name is not null) or (unitrate is not null)
   
       group by  item_description
 order by COALESCE(RecOrdff,0),COALESCE(stk,0),1");
    }
    
    else if($sort=='Required Quantity'){
        
        	$checktotquantity = $con->query("select count(*) as cnt from (
select * from (
select item_description,company_name,salesquantity,quantity,pack,unitrate,COALESCE(stk,0) as stk,supplier_name,
 (case when (COALESCE((reqqty+COALESCE(coqty,0)),0)>0) then (reqqty+COALESCE(coqty,0)) else (0+COALESCE(coqty,0)) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,
COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,COALESCE(coqty,0) as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(COALESCE(stk,0)))/max(COALESCE(pack,0))) as reqqty,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack
from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,mrp from (

    
Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

    
   
select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."' 
and si.clientid='".$Client_ID."' 


Union    
    
select 0 as bill_no,'1900-01-01' as bill_date,co.clientid,Product_Name as  item_description,co.company_name,Quantity_nos as quantity,pck.pack as pack from customer_orders   co left join ( 
    
    select item_description,company_name,pack,ClientID from purchase_item1 where clientid='".$Client_ID."' 
    Union
    
    select item_description,company_name,pack,ClientID from purchase_item where clientid='".$Client_ID."'
    UNION
    
    select item_description,company_name,pack,ClientID from opening_stock1 where clientid='".$Client_ID."'
    )pck on co.Product_Name = pck.item_description and co.company_name = pck.company_name 
    and co.ClientID = pck.clientid
    where 1>0
and status<>'B' and co.clientid ='".$Client_ID."' and pck.clientid ='".$Client_ID."'   
and (order_date>= '".date("Y-m-d", $timestampFromDate)."')
and (order_date<= '".date("Y-m-d", $timestampToDate)."')
    
) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."' 
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(


Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'   
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.Clientid = '".$Client_ID."' 
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."' 

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'  group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.ClientID ='".$Client_ID."'  group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch



) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'   
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0
) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."'  ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R' 
)onea group by item_description,company_name    
 
)sqtywithstk left join (
     
   select ProductName,company,max(Orderdate) as RecOrdDt,max(totalquantity) as RecOrdQty,max(supplier) as RecOrdSupplier,OrderNo,1 as RecOrdff from received_orders1 
   where clientid = '".$Client_ID."'   and supplier<>'' group by  ProductName,company
 
)RecOrd on sqtywithstk.item_description = RecOrd.productname 
   and sqtywithstk.company_name= RecOrd.company  
   
   
   left join (
       
       select product_name as cpproduct,company_name as cpcomp,clientid as coclientid,sum(quantity_nos) as coqty from customer_orders 
       where status<>'B' and clientid ='".$Client_ID."'  group by Product_Name,Company_Name,ClientID )co on sqtywithstk.item_description = co.cpproduct and sqtywithstk.company_name = co.cpcomp)aa where reqqty > 0   

     
          group by  item_description
       
order by COALESCE(RecOrdff,0),9 desc,14 desc,1 desc)cnt")->fetch_assoc();
	    	$countvalue=$checktotquantity['cnt'];
        
        $user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate,COALESCE(stk,0) as stk,supplier_name,
 (case when (COALESCE(reqqty,0)>0) then (reqqty) else (0+COALESCE(coqty,0)) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,
COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,COALESCE(coqty,0) as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff,COALESCE(custordff,0) as Custordff,qnos
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(COALESCE(stk,0)))/max(COALESCE(pack,0))) as reqqty,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack
from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,mrp from (

    
Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

    
   
select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."' 
and si.clientid='".$Client_ID."' 


Union    
    
select 0 as bill_no,'1900-01-01' as bill_date,co.clientid,Product_Name as  item_description,co.company_name,Quantity_nos as quantity,pck.pack as pack from customer_orders   co left join ( 
    
    select item_description,company_name,pack,ClientID from purchase_item1 where clientid='".$Client_ID."' 
    Union
    
    select item_description,company_name,pack,ClientID from purchase_item where clientid='".$Client_ID."'
    UNION
    
    select item_description,company_name,pack,ClientID from opening_stock1 where clientid='".$Client_ID."'
    )pck on co.Product_Name = pck.item_description and co.company_name = pck.company_name 
    and co.ClientID = pck.clientid
    where 1>0
and status<>'B' and co.clientid ='".$Client_ID."' and pck.clientid ='".$Client_ID."'   
and (order_date>= '".date("Y-m-d", $timestampFromDate)."')
and (order_date<= '".date("Y-m-d", $timestampToDate)."')
    
) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."' 
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(


Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'   
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.Clientid = '".$Client_ID."' 
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."' 

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'  group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.ClientID ='".$Client_ID."'  group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch
    
) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'   
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0
) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."'  ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R' 
)onea group by item_description,company_name    
 
)sqtywithstk left join (
   select ProductName,company,max(Orderdate) as RecOrdDt,max(totalquantity) as RecOrdQty,max(supplier) as RecOrdSupplier,OrderNo,1 as RecOrdff,Quantity as qnos from received_orders1 
   where clientid = '".$Client_ID."' and st_reason IS NULL   and supplier<>'' group by  ProductName,company
 
)RecOrd on sqtywithstk.item_description = RecOrd.productname 
   and sqtywithstk.company_name= RecOrd.company  
   left join (
       select product_name as cpproduct,company_name as cpcomp,clientid as coclientid,sum(quantity_nos) as coqty,2 as custordff  from customer_orders 
       where status<>'B' and clientid ='".$Client_ID."'  group by Product_Name,Company_Name,ClientID )co on sqtywithstk.item_description = co.cpproduct and sqtywithstk.company_name = co.cpcomp    
           group by  item_description   
order by COALESCE(custordff,0) desc,COALESCE(RecOrdff,0) desc ,9 desc,14 desc,1 desc");
    }

    else if($sort=='Product name'){

$user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,stk,supplier_name,
0 as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff,qnos
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,MRP from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(

Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'    
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.Clientid = '".$Client_ID."'  
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'  

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'   group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.ClientID ='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'    group by ti.clientid,item_description,company_name,branch



) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'    
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0





) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier ,OrderNo,1 as RecOrdff,Quantity as qnos from received_orders1 
    where clientid = '".$Client_ID."' and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company   
       group by  item_description
 order by COALESCE(RecOrdff,0),1 asc,7");


}

    else if($sort=='Supplier name'){

$user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,stk,supplier_name,
(case when (stk=0) then (reqqty) else (0) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty,qnos
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(stk))/max(pack)) as reqqty


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(



Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate from (


Select p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union

Select p.purchase_id*100000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select opening_stock_id*-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate from opening_stock1 where 1>0
and clientid='".$Client_ID."'
Union
select ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.Clientid = '".$Client_ID."'
Union
select ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."'

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id+AutoID) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
Select COALESCE(max(((year(purchase_date)*3650) + (month(purchase_date)*120) + (day(purchase_date))+p.purchase_id) *100),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.ClientID ='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."' 



) p4  group by clientid,item_description,company_name,supplier_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
Where 1 > 0 and p1.clientid='".$Client_ID."'
group by p1.clientid,p1.item_description,p1.company_name,supplier_name

) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier,OrderNo,Quantity as qnos  from received_orders1 
    where clientid = 50 and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company     
 order by supplier_name ");


}

    else if($sort=='Sales quantity'){

$user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,stk,supplier_name,
(case when (stk=0) then (reqqty) else (0) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(stk))/max(pack)) as reqqty


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(



Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate from (


Select p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union

Select p.purchase_id*100000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select opening_stock_id*-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate from opening_stock1 where 1>0
and clientid='".$Client_ID."'
Union
select ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.Clientid = '".$Client_ID."'
Union
select ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."'

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id+AutoID) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
Select COALESCE(max(((year(purchase_date)*3650) + (month(purchase_date)*120) + (day(purchase_date))+p.purchase_id) *100),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.ClientID ='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."' 



) p4  group by clientid,item_description,company_name,supplier_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
Where 1 > 0 and p1.clientid='".$Client_ID."'
group by p1.clientid,p1.item_description,p1.company_name,supplier_name

) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier,OrderNo  from received_orders1 
    where clientid = 50 and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company     
 order by salesquantity desc");


}

}
else{
    
   if($sort=='Stock'){
        $user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,stk,supplier_name,
0 as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff,qnos
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,MRP from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(

Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'    
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.Clientid = '".$Client_ID."'  
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'  

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'   group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.ClientID ='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'    group by ti.clientid,item_description,company_name,branch



) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'    
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0





) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier ,OrderNo,1 as RecOrdff,Quantity as qnos from received_orders1 
    where clientid = '".$Client_ID."' and st_reason IS NULL and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company where supplier_name ='".$Supplier_Name."'     
       group by  item_description
 order by COALESCE(RecOrdff,0),7,1 asc");
    }
    
  else if($sort=='Required Quantity'){
        
        $checktotquantity = $con->query("select count(*) as cnt from (
select * from (
select item_description,company_name,salesquantity,quantity,pack,unitrate,COALESCE(stk,0) as stk,supplier_name,
 (case when (COALESCE((reqqty+COALESCE(coqty,0)),0)>0) then (reqqty+COALESCE(coqty,0)) else (0+COALESCE(coqty,0)) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,
COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,COALESCE(coqty,0) as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(COALESCE(stk,0)))/max(COALESCE(pack,0))) as reqqty,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack
from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,mrp from (

    
Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

    
   
select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."' 
and si.clientid='".$Client_ID."' 


Union    
    
select 0 as bill_no,'1900-01-01' as bill_date,co.clientid,Product_Name as  item_description,co.company_name,Quantity_nos as quantity,pck.pack as pack from customer_orders   co left join ( 
    
    select item_description,company_name,pack,ClientID from purchase_item1 where clientid='".$Client_ID."' 
    Union
    
    select item_description,company_name,pack,ClientID from purchase_item where clientid='".$Client_ID."'
    UNION
    
    select item_description,company_name,pack,ClientID from opening_stock1 where clientid='".$Client_ID."'
    )pck on co.Product_Name = pck.item_description and co.company_name = pck.company_name 
    and co.ClientID = pck.clientid
    where 1>0
and status<>'B' and co.clientid ='".$Client_ID."' and pck.clientid ='".$Client_ID."'   
and (order_date>= '".date("Y-m-d", $timestampFromDate)."')
and (order_date<= '".date("Y-m-d", $timestampToDate)."')
    
) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."' 
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(


Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'   
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.Clientid = '".$Client_ID."' 
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."' 

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'  group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.ClientID ='".$Client_ID."'  group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch



) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'   
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0
) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."'  ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R' 
)onea group by item_description,company_name    
 
)sqtywithstk left join (
     
   select ProductName,company,max(Orderdate) as RecOrdDt,max(totalquantity) as RecOrdQty,max(supplier) as RecOrdSupplier,OrderNo,1 as RecOrdff from received_orders1 
   where clientid = '".$Client_ID."'   and supplier<>'' group by  ProductName,company
 
)RecOrd on sqtywithstk.item_description = RecOrd.productname 
   and sqtywithstk.company_name= RecOrd.company  
   
   
   left join (
       
       select product_name as cpproduct,company_name as cpcomp,clientid as coclientid,sum(quantity_nos) as coqty from customer_orders 
       where status<>'B' and clientid ='".$Client_ID."'  group by Product_Name,Company_Name,ClientID )co on sqtywithstk.item_description = co.cpproduct and sqtywithstk.company_name = co.cpcomp)aa where reqqty > 0   

     
          group by  item_description
       
order by COALESCE(RecOrdff,0),9 desc,14 desc,1 desc)cnt")->fetch_assoc();
        $countvalue=$checktotquantity['cnt'];
    
    $user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate,COALESCE(stk,0) as stk,supplier_name,
 (case when (COALESCE(reqqty,0)>0) then (reqqty) else (0+COALESCE(coqty,0)) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,
COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,COALESCE(coqty,0) as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff,COALESCE(custordff,0) as Custordff,qnos
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(COALESCE(stk,0)))/max(COALESCE(pack,0))) as reqqty,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack
from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,mrp from (

    
Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

    
   
select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."' 
and si.clientid='".$Client_ID."' 


Union    
    
select 0 as bill_no,'1900-01-01' as bill_date,co.clientid,Product_Name as  item_description,co.company_name,Quantity_nos as quantity,pck.pack as pack from customer_orders   co left join ( 
    
    select item_description,company_name,pack,ClientID from purchase_item1 where clientid='".$Client_ID."' 
    Union
    
    select item_description,company_name,pack,ClientID from purchase_item where clientid='".$Client_ID."'
    UNION
    
    select item_description,company_name,pack,ClientID from opening_stock1 where clientid='".$Client_ID."'
    )pck on co.Product_Name = pck.item_description and co.company_name = pck.company_name 
    and co.ClientID = pck.clientid
    where 1>0
and status<>'B' and co.clientid ='".$Client_ID."' and pck.clientid ='".$Client_ID."'   
and (order_date>= '".date("Y-m-d", $timestampFromDate)."')
and (order_date<= '".date("Y-m-d", $timestampToDate)."')
    
) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."' 
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(


Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'   
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.Clientid = '".$Client_ID."' 
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."' 

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'  and p.ClientID ='".$Client_ID."'  group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'  and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  and ti.ClientID ='".$Client_ID."'  group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'  And ti.clientid='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch
    
) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'   
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0
) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."'  ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R' 
)onea group by item_description,company_name    
 
)sqtywithstk left join (
   select ProductName,company,max(Orderdate) as RecOrdDt,max(totalquantity) as RecOrdQty,max(supplier) as RecOrdSupplier,OrderNo,1 as RecOrdff,Quantity as qnos from received_orders1 
   where clientid = '".$Client_ID."'   and supplier<>'' group by  ProductName,company
 
)RecOrd on sqtywithstk.item_description = RecOrd.productname 
   and sqtywithstk.company_name= RecOrd.company  
   left join (
       select product_name as cpproduct,company_name as cpcomp,clientid as coclientid,sum(quantity_nos) as coqty,2 as custordff  from customer_orders 
       where status<>'B' and clientid ='".$Client_ID."'  group by Product_Name,Company_Name,ClientID )co on sqtywithstk.item_description = co.cpproduct and sqtywithstk.company_name = co.cpcomp 
 where  supplier_name ='".$Supplier_Name."'   
           group by  item_description   
order by COALESCE(custordff,0) desc,COALESCE(RecOrdff,0) desc ,9 desc,14 desc,1 desc");
}


   else if($sort=='Product name'){

$user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,stk,supplier_name,
0 as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty,PRate_Pack,mrpPack,COALESCE(RecOrdff,0) as RecOrdff,qnos
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,max(PRate_Pack) as PRate_Pack,max(MRP) as MRPPack


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name,PRate_Pack,MRP from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(

Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate,max(idd) as idd,max(id) as id,max(PRate_Pack) as PRate_Pack,max(MRP) as MRP from (


Select COALESCE((((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as idd,p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate,PRate_Pack,MRP from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'    
    
 
Union
select COALESCE((((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as idd,opening_stock_id-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate,PRate_Pack,MRP from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>''
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.Clientid = '".$Client_ID."'  
Union
select COALESCE((((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as idd,ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate,PRate_Pack,MRP from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'  

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'   and p.ClientID ='".$Client_ID."'   group by pi.clientid,item_description,company_name,supplier_name
 
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."'   and COALESCE(supplier_name,'')<>'' group by clientid,item_description,company_name,supplier_name
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   and ti.ClientID ='".$Client_ID."'   group by ti.clientid,item_description,company_name,branch
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."'   And ti.clientid='".$Client_ID."'    group by ti.clientid,item_description,company_name,branch



) p4  group by clientid,item_description,company_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
    and COALESCE(p1.idd,0) = COALESCE(p5.id,0) 
Where 1 > 0 and p1.clientid='".$Client_ID."'    
group by p1.clientid,p1.item_description,p1.company_name,p1.supplier_name
having max(id) >0





) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier ,OrderNo,1 as RecOrdff,Quantity as qnos from received_orders1 
    where clientid = '".$Client_ID."' and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company where supplier_name ='".$Supplier_Name."' 
       group by  item_description
 order by COALESCE(RecOrdff,0),1 asc,7");


}



  else if($sort=='Supplier name'){

$user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,stk,supplier_name,
(case when (stk=0) then (reqqty) else (0) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty,qnos
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(stk))/max(pack)) as reqqty


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(



Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate from (


Select p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union

Select p.purchase_id*100000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select opening_stock_id*-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate from opening_stock1 where 1>0
and clientid='".$Client_ID."'
Union
select ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.Clientid = '".$Client_ID."'
Union
select ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."'

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id+AutoID) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
Select COALESCE(max(((year(purchase_date)*3650) + (month(purchase_date)*120) + (day(purchase_date))+p.purchase_id) *100),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.ClientID ='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."' 



) p4 where  supplier_name='".$Supplier_Name."'  group by clientid,item_description,company_name,supplier_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
Where 1 > 0 and p1.clientid='".$Client_ID."' and supplier_name='".$Supplier_Name."'
group by p1.clientid,p1.item_description,p1.company_name,supplier_name

) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
and  supplier_name='".$Supplier_Name."'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier,OrderNo,Quantity as qnos  from received_orders1 
    where clientid = 50 and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company     
 order by supplier_name ");


}
 
    else if($sort=='Sales quantity'){

$user_sql = $con->query("select item_description,company_name,salesquantity,quantity,pack,unitrate
,stk,supplier_name,
(case when (stk=0) then (reqqty) else (0) end) as reqqty,COALESCE(RecOrdQty,'') as RecOrdQty,COALESCE(RecOrdDt,'1900-01-01') as RecOrdDt,COALESCE(RecOrdSupplier,'') as RecOrdSupplier,OrderNo,0 as coqty
from (


select item_description,company_name,max(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,max(stk) as stk,supplier_name,CEILING((max(quantity)-max(stk))/max(pack)) as reqqty


from (

Select s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales1 s left join sales_item1 si On s.bill_no=si.bill_no And s.clientid=si.clientid    
    where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."')
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')
and s.clientid='".$Client_ID."'
and si.clientid='".$Client_ID."'

) ss
group by item_description,company_name,clientid

) s
 left Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0
and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
left Join(



Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate from (


Select p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union

Select p.purchase_id*100000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select opening_stock_id*-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate from opening_stock1 where 1>0
and clientid='".$Client_ID."'
Union
select ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.Clientid = '".$Client_ID."'
Union
select ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."'

) p1 left Join ( select max(id) as id,clientid,item_description,company_name from (


Select COALESCE(max(((year(purchase_date)*36500) + (month(purchase_date)*1200) + (day(purchase_date))+p.purchase_id+AutoID) *1000),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase1 p left join purchase_item1 pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
Select COALESCE(max(((year(purchase_date)*3650) + (month(purchase_date)*120) + (day(purchase_date))+p.purchase_id) *100),0) as id,pi.clientid,item_description,company_name,supplier_name from purchase p left join purchase_item pi
On p.clientid=pi.clientid And p.purchase_id=pi.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."' and p.ClientID ='".$Client_ID."'
Union
select COALESCE(max(((year(invoice_date)*365) + (month(invoice_date)*12) + (day(invoice_date)))),0) as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
and clientid='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer1 t left join transfer_item1 ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' and ti.ClientID ='".$Client_ID."' 
Union
select COALESCE(max(((year(invoice_date)) + (month(invoice_date)) + (day(invoice_date)))),0) as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer t left join transfer_item ti on t.clientid=ti.clientid and t.transfer_no=ti.transfer_no
where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."' 



) p4 where  supplier_name='".$Supplier_Name."'  group by clientid,item_description,company_name,supplier_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name
Where 1 > 0 and p1.clientid='".$Client_ID."' and  supplier_name='".$Supplier_Name."'
group by p1.clientid,p1.item_description,p1.company_name,supplier_name

) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
left join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And Clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid And s.clientid=m.Clientid
where c.type='R'
and  supplier_name='".$Supplier_Name."'
)onea group by item_description,company_name
 )sqtywithstk left join (
     
   select ProductName,company,Orderdate as RecOrdDt,sum(totalquantity) as RecOrdQty,supplier as RecOrdSupplier,OrderNo  from received_orders1 
    where clientid = 50 and supplier<>'' group by  ProductName,company,Orderdate,supplier)RecOrd on sqtywithstk.item_description = RecOrd.productname 
    and sqtywithstk.company_name= RecOrd.company     
 order by salesquantity desc");


}
    
    
    
}

while($rows = $user_sql->fetch_assoc())
{
$user_result['Item Description'] = $rows['item_description'];
$user_result['WhStock'] = $rows['WhStock'];
$user_result['Company Name'] = $rows['company_name'];
$user_result['Sales Quantity'] = $rows['salesquantity'];
$user_result['Quantity'] = $rows['quantity'];
$user_result['Pack'] = $rows['pack'];
$user_result['Unit Rate'] = $rows['unitrate'];
$user_result['Stock'] = $rows['stk'];
$user_result['Supplier Name'] = $rows['supplier_name'];
$user_result['reqqty'] = $rows['reqqty'];
$user_result['RecOrdQty'] = $rows['RecOrdQty'];
$user_result['RecOrdDt'] = $rows['RecOrdDt'];
$user_result['RecOrdSupplier'] = $rows['RecOrdSupplier'];
$user_result['PrevOrderNo'] = $rows['OrderNo'];
$user_result['Coquantity'] = $rows['coqty'];
$user_result['PRatePack'] = $rows['PRate_Pack'];
$user_result['Mrp_Pack'] = $rows['mrpPack'];
$user_result['qnos'] = $rows['qnos'];
$all_users[] = $user_result;
}



$test = array('Purchase Order'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>$countvalue,"ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 


		




case 'getPurchaseOrderListTest':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
if($data['Client_ID'] == '' or $data['B_From_Date'] == '' or $data['B_To_Date'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong || Params mismatch");
}

else {

$Client_ID=strip_tags(mysqli_real_escape_string($con,$data['Client_ID']));
$B_From_Date=strip_tags(mysqli_real_escape_string($con,$data['B_From_Date']));
$B_To_Date=strip_tags(mysqli_real_escape_string($con,$data['B_To_Date']));
$timestampFromDate = strtotime($B_From_Date);
$timestampToDate = strtotime($B_To_Date);
$user_sql = $con->query("  select item_description,company_name,sum(quantity) as salesquantity,0 as quantity,max(pack) as pack,max(unitrate) as unitrate
,sum(stk) as stk,supplier_name from (

Select  s.clientid,s.item_description,s.company_name,quantity,pack,prate/pack As unitrate,stk,supplier_name  from (

Select clientid,item_description,company_name,sum(quantity) As quantity,max(pack) As pack  from (

select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales_item1 si join sales1 s On si.bill_no=s.bill_no And si.clientid=s.clientid    
union
select si.bill_no,bill_date,si.clientid,item_description,company_name,quantity,pack from sales_item si join sales s On si.bill_no=s.bill_no And si.clientid=s.clientid    

) ss where 1>0

and (bill_date>= '".date("Y-m-d", $timestampFromDate)."') 
and (bill_date<= '".date("Y-m-d", $timestampToDate)."')


and clientid='".$Client_ID."'
group by item_description,company_name,clientid

)  s
  Join (


select clientid,product_name,manufacturer,sum((purchase_quantity-sales_quantity)) as stk from stock where 1>0

and clientid='".$Client_ID."'
group by clientid,product_name,manufacturer

) st
on s.clientid=st.clientid and s.item_description=st.product_name and s.company_name=st.manufacturer
Join(



Select p1.clientid,p1.item_description,p1.company_name,p1.supplier_name,max(prate) As prate  from (


Select p.purchase_id*10000000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase_item1 pi join  purchase1 p
	 On pi.clientid=p.clientid And pi.purchase_id=p.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'
Union

Select p.purchase_id*100000 As f,pi.clientid,item_description,company_name,supplier_name,unit*pack As prate from purchase_item pi join  purchase p
	 On pi.clientid=p.clientid And pi.purchase_id=p.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'
Union
select opening_stock_id*-1 as f,clientid,item_description,company_name,supplier_name,purchase_rate*pack as prate from opening_stock1 where 1>0
	and clientid='".$Client_ID."'
Union
select ti.transfer_no+50000 as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer_item1 ti join transfer1 t on ti.clientid=t.clientid and ti.transfer_no=t.transfer_no
	 where t.type='i' and ti.type='i'
	 And t.clientid='".$Client_ID."'
Union
select ti.transfer_no as f,ti.clientid,item_description,company_name,branch as supplier_name,purchase_rate as prate from transfer_item ti join transfer t on ti.clientid=t.clientid and ti.transfer_no=t.transfer_no
	 where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."'

) p1 Join ( select max(id) as id,clientid,item_description,company_name  from (


Select p.purchase_id*100000000  as id,pi.clientid,item_description,company_name,supplier_name from purchase_item1 pi join  purchase1 p
	 On pi.clientid=p.clientid And pi.purchase_id=p.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'
Union
Select p.purchase_id*1000000  as id,pi.clientid,item_description,company_name,supplier_name from purchase_item pi join  purchase p
	 On pi.clientid=p.clientid And pi.purchase_id=p.purchase_id where 1>0
and pi.ClientID ='".$Client_ID."'
Union
select opening_stock_id*-1 as id,clientid,item_description,company_name,supplier_name from opening_stock1 where 1>0
	and clientid='".$Client_ID."'
Union
select ti.transfer_no+50000 as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer_item1 ti join transfer1 t on ti.clientid=t.clientid and ti.transfer_no=t.transfer_no
	 where t.type='i' and ti.type='i'
	 And t.clientid='".$Client_ID."'
Union
select ti.transfer_no as id,ti.clientid,item_description,company_name,branch as supplier_name from transfer_item ti join transfer t on ti.clientid=t.clientid and ti.transfer_no=t.transfer_no
	 where t.type='i' and ti.type='i'
And t.clientid='".$Client_ID."' And ti.clientid='".$Client_ID."'



) p4  group by clientid,item_description,company_name,supplier_name
) p5 on p1.clientid=p5.clientid and p1.item_description=p5.item_description and p1.company_name=p5.company_name and p1.f=p5.id
Where 1 > 0 and p1.clientid='".$Client_ID."' 
group by p1.clientid,p1.item_description,p1.company_name,supplier_name

) p3 on s.clientid=p3.clientid and s.item_description=p3.item_description and s.company_name=p3.company_name  
join clients c on s.clientid=c.clientid  
left join (
select * from minmax where 1>0
And clientid ='".$Client_ID."' ) m On s.item_description=m.productname And s.company_name=m.shortid  And s.clientid=m.Clientid
where c.type='R'
and quantity<m.minlevel


)onea  group by item_description,company_name,supplier_name order by  item_description");


while($rows = $user_sql->fetch_assoc())
{
$user_result['Item Description'] = $rows['item_description'];
$user_result['Company Name'] = $rows['company_name'];
$user_result['Sales Quantity'] = $rows['salesquantity'];
$user_result['Quantity'] = $rows['quantity'];
$user_result['Pack'] = $rows['pack'];
$user_result['Unit Rate'] = $rows['unitrate'];
$user_result['Stock'] = $rows['stk'];
$user_result['Supplier Name'] = $rows['supplier_name'];
$all_users[] = $user_result;
}



$test = array('Purchase Order'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Purchase Order Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 

case 'getAllSupplierbyClientActive':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	 $all_users= (array) null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

$user_sql = $con->query("select * from supplier where ClientID=".$ClientID." and active='1' order by sort_id asc");


while($rows = $user_sql->fetch_assoc())
{

	$user_result['Supplier_Name'] = $rows['Supplier_Name'];
$user_result['AutoID'] = $rows['AutoID'];
$user_result['Active'] = $rows['active'];
$user_result['sort_id'] = $rows['sort_id'];
$all_users[] = $user_result;
	



}


$test = array('SupplierbyClient'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Supplier List Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break;





case 'getAllSupplierbyClient':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	 $all_users= (array) null;
if($data['ClientID'] == '' or $data['admin'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$admin=strip_tags(mysqli_real_escape_string($con,$data['admin']));

if($admin =='1'){
   $user_sql = $con->query("select * from (

select *,1 as f from supplier where ClientID='".$ClientID."'  and sort_id is not null
UNION
select *,2 as f from supplier where ClientID='".$ClientID."'  and sort_id is  null
)supp order by active desc,f,sort_id,Supplier_Name" );
 
}
else{
 $user_sql = $con->query("select * from (

select *,1 as f from supplier where ClientID='".$ClientID."'  and sort_id is not null and active='1'
UNION
select *,2 as f from supplier where ClientID='".$ClientID."'  and sort_id is  null and active='1'
)supp order by active desc, f,sort_id");
   
}



while($rows = $user_sql->fetch_assoc())
{

	$user_result['Supplier_Name'] = $rows['Supplier_Name'];
$user_result['AutoID'] = $rows['AutoID'];
$user_result['Active'] = $rows['active'];
$user_result['sort_id'] = $rows['sort_id'];
$all_users[] = $user_result;
	



}


$test = array('SupplierbyClient'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Supplier List Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 



case 'getAllShopbyAdmin':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	 $all_users= (array) null;
if($data['admin'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {

$user_sql = $con->query("select * from clients ORDER BY ClientName ASC");


while($rows = $user_sql->fetch_assoc())
{

	$user_result['ClientId'] = $rows['ClientID'];
$user_result['ClientName'] = $rows['ClientName'];
$user_result['Type'] = $rows['Type'];
$user_result['Location'] = $rows['Location'];
$user_result['Area'] = $rows['Area'];
$user_result['PharmappsID'] = $rows['PharmappsID'];
$user_result['Phone'] = $rows['Phone'];
$user_result['AllowOnlineOrders'] = $rows['AllowOnlineOrders'];
$user_result['pay_upi'] = $rows['pay_upi'];
$all_users[] = $user_result;
	



}


$test = array('AllShopsbyAdmin'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 


case 'getAllShopbyAdminShopsort':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	 $all_users= (array) null;
if( $data['ClientID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$user_sql = $con->query("SELECT 1 as flag,shpsort.sort_id as NewSortID,c.id,c.ClientID,ClientName,Description,Address1,address2,Address3,phone,
type,cflag,tin,dl,Sales_Category,dl2,branchid,Constituency,Opening_Date,Inactive,CreditDays,AllowOnlineOrders,Email,
BillingID,IGSTCustomer,DefaultBank,note,pincode,CreditLimit,IsBranch,IsCustomer,Area,Location,Lat,Lng,WhatsApp1,WhatsApp2,PharmappsID,FSNumber,Type2,pay_qr,pay_qr_status,GSTType,pay_upi,trial_from,trial_to,max_connections,c.sort_id,assign_stamp
FROM `clients` c left join tbl_shop_sorting shpsort on c.ClientID = shpsort.Managed_ClientID
where shpsort.ClientID = '".$ClientID."' 
 
 UNION
 
 SELECT  2 as flag,1000 as NewSortID,id,ClientID,ClientName,Description,Address1,address2,Address3,phone,type,cflag,tin,dl,Sales_Category,dl2,
branchid,Constituency,Opening_Date,Inactive,CreditDays,AllowOnlineOrders,Email,BillingID,IGSTCustomer,DefaultBank,note,pincode,CreditLimit,IsBranch,IsCustomer,Area,Location,Lat,Lng,WhatsApp1,WhatsApp2,PharmappsID,
FSNumber,Type2,pay_qr,pay_qr_status,GSTType,pay_upi,trial_from,trial_to,max_connections,sort_id,0 as assign_stamp
FROM `clients` where ClientID not in (  select distinct Managed_ClientID from tbl_shop_sorting ) 
order by 1,2,ClientName asc;");


while($rows = $user_sql->fetch_assoc())
{

$user_result['ClientId'] = $rows['ClientID'];
$user_result['NewSortID'] = $rows['NewSortID'];
$user_result['ClientName'] = $rows['ClientName'];
$user_result['Type'] = '0';
$user_result['Location'] = $rows['Location'];
$user_result['Area'] = $rows['Area'];
$user_result['PharmappsID'] = $rows['PharmappsID'];
$user_result['Phone'] = '0';
$user_result['AllowOnlineOrders'] = $rows['AllowOnlineOrders'];
$user_result['pay_upi'] = $rows['pay_upi'];
$all_users[] = $user_result;
	



}


$test = array('AllShopsbyAdmin'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 




case 'getAllShopbyAdminnew':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	 $all_users= (array) null;
if($data['admin'] == '' or $data['ClientID'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$user_sql = $con->query("select * from clients where ClientID !='".$ClientID."' ORDER BY ClientName ASC");


while($rows = $user_sql->fetch_assoc())
{

	$user_result['ClientId'] = $rows['ClientID'];
$user_result['ClientName'] = 'Test';
$user_result['Type'] = $rows['Type'];
$user_result['Location'] = $rows['Location'];
$user_result['Area'] = $rows['Area'];
$user_result['PharmappsID'] = $rows['PharmappsID'];
$user_result['Phone'] = $rows['Phone'];
$user_result['AllowOnlineOrders'] = $rows['AllowOnlineOrders'];
$user_result['pay_upi'] = $rows['pay_upi'];
$all_users[] = $user_result;
	



}


$test = array('AllShopsbyAdmin'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 








case 'getAllShopForAssign':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	 $all_users= (array) null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

$user_sql = $con->query("select * from clients  WHERE ClientID !='".$ClientID."'ORDER BY ClientName ASC ");


while($rows = $user_sql->fetch_assoc())
{

	$user_result['ClientId'] = $rows['ClientID'];
$user_result['ClientName'] = $rows['ClientName'];
$user_result['Type'] = $rows['Type'];
$all_users[] = $user_result;
	



}


$test = array('AllShopsbyAdminAssign'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 






case 'getPurchaseOrderByClient':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

$user_sql = $con->query("select OrderNo,Supplier,OrderDate,OrderID,sum(Rate) as NetRate,Pharmapp_Supplier,PAppSuppID,st_reason,del_status,ssortid,count(*) as ncount from (

     
    
SELECT OrderNo,Supplier,OrderDate,OrderID,((pack*quantity)*unitrate) as NetRate,ro.Auto,Pharmapp_Supplier,pss.PAppSuppID,st_reason,del_status,rate FROM `received_orders1`  ro 
    left join ( select Pharmapp_Supplier,SupplierId as PAppSuppID,clientid,Supplier_Name from PharmApp_Sp_Substitutes ) pss on ro.supplier = pss.Supplier_Name  and ro.clientid = pss.clientid 
    where ro.ClientID = '".$ClientID."' and pss.clientid = '".$ClientID."' 
    
    UNION
    
    SELECT OrderNo,Supplier,OrderDate,OrderID,((pack*quantity)*unitrate) as NetRate,Auto,'' as Pharmapp_Supplier,0 as PAppSuppID,st_reason,del_status,rate FROM `received_orders1` 
where clientid = '".$ClientID."' and supplier not in ( select DISTINCT Supplier_Name from PharmApp_Sp_Substitutes) 
    
    
    
    )aa left join ( select supplier_name as sname,active as sactive,clientid as sclientid,sort_id as ssortid from supplier where clientid = '".$ClientID."')Supp on aa.supplier = Supp.sname where  st_reason IS  NULL and del_status !=  2  GROUP BY OrderNo ORDER BY ssortid");


while($rows = $user_sql->fetch_assoc())
{

	$user_result['OrderNo'] = $rows['OrderNo'];
	$user_result['Rate'] = $rows['NetRate'];
	$user_result['Supplier'] = $rows['Supplier'];
	$user_result['OrderDate'] = $rows['OrderDate'];
	$user_result['OrderID'] = $rows['OrderID'];
	$user_result['Pharmapp_Supplier'] = $rows['Pharmapp_Supplier'];
	$user_result['PAppSuppID'] = $rows['PAppSuppID'];
	$user_result['st_reason'] = $rows['st_reason'];
	$user_result['del_status'] = $rows['del_status'];
			$user_result['ncount'] = $rows['ncount'];
    $all_users[] = $user_result;



}


$test = array('OrderByClient'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"OrderList Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 



case 'getPurchaseOrderByClientSend':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

$user_sql = $con->query("select OrderNo,Supplier,OrderDate,OrderID,sum(Rate) as NetRate,Pharmapp_Supplier,PAppSuppID,st_reason,del_status,count(*) as ncount from (

     
    
SELECT OrderNo,Supplier,OrderDate,OrderID,((pack*quantity)*unitrate) as NetRate,ro.Auto,Pharmapp_Supplier,pss.PAppSuppID,st_reason,del_status,rate FROM `received_orders1`  ro 
    left join ( select Pharmapp_Supplier,SupplierId as PAppSuppID,clientid,Supplier_Name from PharmApp_Sp_Substitutes ) pss on ro.supplier = pss.Supplier_Name  and ro.clientid = pss.clientid 
    where ro.ClientID = '".$ClientID."' and pss.clientid = '".$ClientID."' 
    
    UNION
    
    SELECT OrderNo,Supplier,OrderDate,OrderID,((pack*quantity)*unitrate) as NetRate,Auto,'' as Pharmapp_Supplier,0 as PAppSuppID,st_reason,del_status,rate FROM `received_orders1` 
where clientid = '".$ClientID."' and supplier not in ( select DISTINCT Supplier_Name from PharmApp_Sp_Substitutes) 
    
    
  )aa where   del_status =0 and del_status !=  2 and  (st_reason IS NOT NULL OR OrderID IS NOT NULL) GROUP BY OrderNo,Supplier,OrderID,Pharmapp_Supplier,PAppSuppID ORDER BY OrderDate desc ");


while($rows = $user_sql->fetch_assoc())
{

	$user_result['OrderNo'] = $rows['OrderNo'];
	$user_result['Rate'] = $rows['NetRate'];
	$user_result['Supplier'] = $rows['Supplier'];
	$user_result['OrderDate'] = $rows['OrderDate'];
	$user_result['OrderID'] = $rows['OrderID'];
	$user_result['Pharmapp_Supplier'] = $rows['Pharmapp_Supplier'];
	$user_result['PAppSuppID'] = $rows['PAppSuppID'];
	$user_result['st_reason'] = $rows['st_reason'];
	$user_result['del_status'] = $rows['del_status'];
			$user_result['ncount'] = $rows['ncount'];
    $all_users[] = $user_result;
	



}


$test = array('OrderByClient'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"OrderList Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 

case 'getPurchaseOrderByClientDeleted':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

$user_sql = $con->query("select OrderNo,Supplier,OrderDate,OrderID,sum(Rate) as NetRate,Pharmapp_Supplier,PAppSuppID,st_reason,del_status,count(*) as ncount from (

     
    
SELECT OrderNo,Supplier,OrderDate,OrderID,((pack*quantity)*unitrate) as NetRate,ro.Auto,Pharmapp_Supplier,pss.PAppSuppID,st_reason,del_status,rate FROM `received_orders1`  ro 
    left join ( select Pharmapp_Supplier,SupplierId as PAppSuppID,clientid,Supplier_Name from PharmApp_Sp_Substitutes ) pss on ro.supplier = pss.Supplier_Name  and ro.clientid = pss.clientid 
    where ro.ClientID = '".$ClientID."' and pss.clientid = '".$ClientID."' 
    
    UNION
    
    SELECT OrderNo,Supplier,OrderDate,OrderID,((pack*quantity)*unitrate) as NetRate,Auto,'' as Pharmapp_Supplier,0 as PAppSuppID,st_reason,del_status,rate FROM `received_orders1` 
where clientid = '".$ClientID."' and supplier not in ( select DISTINCT Supplier_Name from PharmApp_Sp_Substitutes) 
    
    
    )aa left join ( select supplier_name as sname,active as sactive,clientid as sclientid,sort_id as ssortid from supplier where clientid = '".$ClientID."')Supp on aa.supplier = Supp.sname where   del_status =1  and  del_status != 2 GROUP BY OrderNo,Supplier,OrderID,Pharmapp_Supplier,PAppSuppID ORDER BY OrderDate desc ");


while($rows = $user_sql->fetch_assoc())
{

	$user_result['OrderNo'] = $rows['OrderNo'];
	$user_result['Rate'] = $rows['NetRate'];
	$user_result['Supplier'] = $rows['Supplier'];
	$user_result['OrderDate'] = $rows['OrderDate'];
	$user_result['OrderID'] = $rows['OrderID'];
	$user_result['Pharmapp_Supplier'] = $rows['Pharmapp_Supplier'];
	$user_result['PAppSuppID'] = $rows['PAppSuppID'];
	$user_result['st_reason'] = $rows['st_reason'];
	$user_result['del_status'] = $rows['del_status'];
		$user_result['ncount'] = $rows['ncount'];
    $all_users[] = $user_result;
	



}


$test = array('OrderByClient'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"OrderList Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 





case 'getAllStockByClient':
	
	
$data = json_decode(file_get_contents('php://input'), true);
	$all_amenity=null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}
			
		else {
			

$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

   if($ClientID =='0')
{
$bookings_sql = $con->query("select * from stock where Purchase_quantity-Sales_quantity > 0 LIMIT 1000"); 
}
else{
$bookings_sql = $con->query("select '0' as flag,stock.*  from stock where  Product_Name  not in ( select distinct ProductName  from StockVerification where ClientID ='".$ClientID."')     
			and ClientID ='".$ClientID."' and (Purchase_quantity-Sales_quantity)>0 group by Product_Name
			UNION
			select '1' as flag,stock.* from stock where  Product_Name  in (
				select distinct ProductName from StockVerification where ClientID ='".$ClientID."')     
			and ClientID ='".$ClientID."' and (Purchase_quantity-Sales_quantity)>0 group by Product_Name
			ORDER BY 1 desc"); 
}



while($rows = $bookings_sql->fetch_assoc())
{
$am_result['flag'] = $rows['flag'];
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];
$am_result['Batch'] = $rows['Batch'];
$am_result['Expiry'] = $rows['Expiry'];
$am_result['Purchase_quantity'] = $rows['Purchase_quantity'];
$am_result['Sales_quantity'] = $rows['Sales_quantity'];
$am_result['uPack'] = $rows['uPack'];
$am_result['Unit_Rate'] = $rows['Unit_Rate'];
$am_result['Sales_Rate'] = $rows['Sales_Rate'];
$am_result['Manufacturer'] = $rows['manufacturer'];
$all_amenity[] = $am_result;
}



$test = array('All_Stock'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
				
			
		echo json_encode($returnArr);		
		
				


			}
		
				
				
		break; 	
		
		
		
			case 'getAllStockByClientLikeCustomer':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_amenity=null;
if($data['ClientID'] == '' or $data['Pattn'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {


$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Pattn=strip_tags(mysqli_real_escape_string($con,$data['Pattn']));

if($ClientID =='0')
{
$bookings_sql = $con->query("select * from stock WHERE LOWER(Product_Name) LIKE '".$Pattn."%' GROUP BY Product_Name  ORDER BY Product_Name"); 
}
else{
/*$bookings_sql = $con->query("select * from stock where ClientID='".$ClientID."' and LOWER(Product_Name) LIKE '".$Pattn."%' and Purchase_quantity-Sales_quantity > 0 GROUP BY Product_Name  ORDER BY Product_Name "); */

$bookings_sql = $con->query("select * from stock where ClientID='".$ClientID."' and LOWER(Product_Name) LIKE '".$Pattn."%'  GROUP BY Product_Name  ORDER BY Product_Name  "); 
}



while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];
$am_result['Batch'] = $rows['Batch'];
$am_result['Expiry'] = $rows['Expiry'];
$am_result['Purchase_quantity'] = $rows['Purchase_quantity'];
$am_result['Sales_quantity'] = $rows['Sales_quantity'];
$am_result['uPack'] = $rows['uPack'];
$am_result['Unit_Rate'] = $rows['Unit_Rate'];
$am_result['Sales_Rate'] = $rows['Sales_Rate'];
$am_result['Manufacturer'] = $rows['manufacturer'];

$all_amenity[] = $am_result;
}



$test = array('All_Stock'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	

	

	


}

echo json_encode($returnArr);		
	
break; 	




		case 'getAllStockByClientLike':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
				$all_amenity=null;
if($data['ClientID'] == '' or $data['Pattn'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {


$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Pattn=strip_tags(mysqli_real_escape_string($con,$data['Pattn']));

if($ClientID =='0')
{
$bookings_sql = $con->query("select * from stock WHERE LOWER(Product_Name) LIKE '".$Pattn."%' GROUP BY Product_Name  ORDER BY Product_Name"); 
}
else{
$bookings_sql = $con->query("select * from stock where ClientID='".$ClientID."' and LOWER(Product_Name) LIKE '%".$Pattn."%' and Purchase_quantity-Sales_quantity > 0  ORDER BY Product_Name"); 
}



while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];
$am_result['Batch'] = $rows['Batch'];
$am_result['Expiry'] = $rows['Expiry'];
$am_result['Purchase_quantity'] = $rows['Purchase_quantity'];
$am_result['Sales_quantity'] = $rows['Sales_quantity'];
$am_result['uPack'] = $rows['uPack'];
$am_result['Unit_Rate'] = $rows['Unit_Rate'];
$am_result['Sales_Rate'] = $rows['Sales_Rate'];

$all_amenity[] = $am_result;
}



$test = array('All_Stock'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details","ResultData"=>$test);
	

	

	


}

echo json_encode($returnArr);		
	
break; 	





		case 'getAllStockByClientLikenew':
	
	
			$data = json_decode(file_get_contents('php://input'), true);
if($data['ClientID'] == '' or $data['ProductName'] == '' )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {


$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$ProductName=strip_tags(mysqli_real_escape_string($con,$data['ProductName']));

$bookings_sql = $con->query("select * from stock"); 
 


while($rows = $bookings_sql->fetch_assoc())
{
$am_result['Product_Name'] = $rows['Product_Name'];
$am_result['MRP'] = $rows['MRP'];
$am_result['Stock_id'] = $rows['Stock_id'];

$all_amenity[] = $am_result;
}



$test = array('AllStockSearch'=>$all_amenity);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Stock Details Like","ResultData"=>$test);
	

echo json_encode($returnArr);		

	


}

	
	
break; 	






		case 'addPurchaseOrderList':
				
			$data = json_decode(file_get_contents('php://input'), true);
		 
			
if($data['ClientID'] == '' or $data['rate'] == ''  or $data['total_quantity'] == '' or $data['supplier_name'] == '' 
or $data['quantity'] == '' or $data['item'] == '' or $data['company'] == '' or $data['pack'] == ''
or $data['orderDate'] == '' or $data['orderNo'] == '' or $data['status'] == '' or $data['unitRate'] == ''
or $data['Stock'] == ''  or $data['SalesQuantity'] == ''   )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$rate = strip_tags(mysqli_real_escape_string($con,$data['rate']));
$total_quantity = strip_tags(mysqli_real_escape_string($con,$data['total_quantity']));
$supplier_name = strip_tags(mysqli_real_escape_string($con,$data['supplier_name']));
$quantity = strip_tags(mysqli_real_escape_string($con,$data['quantity']));
$item = strip_tags(mysqli_real_escape_string($con,$data['item']));
$company = strip_tags(mysqli_real_escape_string($con,$data['company']));
$pack = strip_tags(mysqli_real_escape_string($con,$data['pack']));
$orderDate = strip_tags(mysqli_real_escape_string($con,$data['orderDate']));
$orderNo = strip_tags(mysqli_real_escape_string($con,$data['orderNo']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
$unitRate = strip_tags(mysqli_real_escape_string($con,$data['unitRate']));
$Stock = strip_tags(mysqli_real_escape_string($con,$data['Stock']));
$SalesQuantity = strip_tags(mysqli_real_escape_string($con,$data['SalesQuantity']));
$timestamporderDate = strtotime($orderDate );


$con->query("insert into received_orders1(`ClientID`,`OrderNo`,`OrderDate`,`Supplier`,
`ProductName`,`Company`,`Pack`,`Quantity`,`TotalQuantity`,`Status`,`Rate`,`unitRate`,`Stock`,`SalesQuantity`)values
('".$ClientID."','".trim($orderNo)."','".date("Y-m-d", $timestamporderDate)."','".$supplier_name."','".$item."',
'".$company."','".$pack."','".$quantity."','".$total_quantity."','".$status."','".$rate."','".$unitRate."','".$Stock."','".$SalesQuantity."')");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"New Purchase order has been added Successfully!");


}

echo json_encode($returnArr);	

 

	break;



	case 'updatePurchaseOrderList':
				
		$data = json_decode(file_get_contents('php://input'), true);
	 
		
if($data['ClientID'] == '' or $data['rate'] == ''  or $data['total_quantity'] == '' or $data['supplier_name'] == '' 
or $data['quantity'] == '' or $data['item'] == '' or $data['company'] == '' or $data['pack'] == ''
or $data['orderDate'] == '' or $data['orderNo'] == '' or $data['status'] == '' or $data['unitRate'] == ''
or $data['Stock'] == ''  or $data['SalesQuantity'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$rate = strip_tags(mysqli_real_escape_string($con,$data['rate']));
$total_quantity = strip_tags(mysqli_real_escape_string($con,$data['total_quantity']));
$supplier_name = strip_tags(mysqli_real_escape_string($con,$data['supplier_name']));
$quantity = strip_tags(mysqli_real_escape_string($con,$data['quantity']));
$item = strip_tags(mysqli_real_escape_string($con,$data['item']));
$company = strip_tags(mysqli_real_escape_string($con,$data['company']));
$pack = strip_tags(mysqli_real_escape_string($con,$data['pack']));
$orderDate = strip_tags(mysqli_real_escape_string($con,$data['orderDate']));
$orderNo = strip_tags(mysqli_real_escape_string($con,$data['orderNo']));
$status = strip_tags(mysqli_real_escape_string($con,$data['status']));
$unitRate = strip_tags(mysqli_real_escape_string($con,$data['unitRate']));
$Stock = strip_tags(mysqli_real_escape_string($con,$data['Stock']));
$SalesQuantity = strip_tags(mysqli_real_escape_string($con,$data['SalesQuantity']));
$timestamporderDate = strtotime($orderDate );


$con->query("update received_orders1 set ClientID ='".$ClientID."' ,OrderNo='".trim($orderNo)."' ,OrderDate='".$orderDate."' 

,Supplier='".$supplier_name."' ,ProductName='".$item."' ,Company='".$company."' ,Pack='".$pack."' ,Quantity='".$quantity."'

,TotalQuantity='".$total_quantity."' ,Status='".$status."' ,Rate='".$rate."' ,unitRate='".$unitRate."' ,Stock='".$Stock."'

,SalesQuantity='".$SalesQuantity."' where ProductName='".$item."' and OrderNo='".$orderNo."'"); 


$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Purchase order has been updated Successfully!");





}

echo json_encode($returnArr);	



break;




			
	case 'addShopAssignment':
				    
		$data = json_decode(file_get_contents('php://input'), true);
		
		
		
if($data['ClientID'] == '' or $data['MClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$MClientID = strip_tags(mysqli_real_escape_string($con,$data['MClientID']));
$checkexist = $con->query("select * from tbl_assigned_shops where ClientID='".$ClientID."' and Managed_ClientID='".$MClientID."'");
if($checkexist->num_rows != 0)
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Shop already assigned to client");
}
else
{

	$con->query("insert into tbl_assigned_shops(`ClientID`,`Managed_ClientID`)values('".$ClientID."','".$MClientID."')");

	$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Assign Request added Successfully!");
	
	

}


}

echo json_encode($returnArr);	



break;






	case 'addCustomerOrderList':
				
		$data = json_decode(file_get_contents('php://input'), true);
	 
		
if($data['ClientID'] == '' or $data['Name'] == ''  or $data['user_id'] == '' or $data['order_id'] == '' 
or $data['Product_Name'] == '' or $data['Quantity_nos'] == '' or $data['Rate'] == ''  or $data['Status'] == ''
 or $data['Order_Date'] == ''  or $data['Doctor_name'] == ''  or $data['Patients_name'] == '' or $data['notes'] == ''
 )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
} 
else{


$ClientID = strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
$Name = strip_tags(mysqli_real_escape_string($con,$data['Name']));
$user_id = strip_tags(mysqli_real_escape_string($con,$data['user_id']));
$order_id = strip_tags(mysqli_real_escape_string($con,$data['order_id']));
$Product_Name = strip_tags(mysqli_real_escape_string($con,$data['Product_Name']));
$Quantity_nos = strip_tags(mysqli_real_escape_string($con,$data['Quantity_nos']));
$Status = strip_tags(mysqli_real_escape_string($con,$data['Status']));
$Order_Date = strip_tags(mysqli_real_escape_string($con,$data['Order_Date']));
$Rate = strip_tags(mysqli_real_escape_string($con,$data['Rate']));
$Doctor_name = strip_tags(mysqli_real_escape_string($con,$data['Doctor_name']));
$notes = strip_tags(mysqli_real_escape_string($con,$data['notes']));
$Patients_name = strip_tags(mysqli_real_escape_string($con,$data['Patients_name']));
$timestamporderDate = strtotime($Order_Date);


$con->query("insert into customer_orders(`Name`,`user_id`,`ClientID`,`Order_Id`,
`Product_Name`,`Quantity_nos`,`rate`,`Status`,`Order_Date`,`Doctor_name`,`Patients_name`,`notes`)values
('".$Name."','".$user_id."','".$ClientID."','".trim($order_id)."',
'".$Product_Name."','".$Quantity_nos."','".$Rate."','".$Status."','".date("Y-m-d", $timestamporderDate)."','".$Doctor_name."','".$Patients_name."','".$notes."')");

$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"New Oreder order has been added Successfully!");





}

echo json_encode($returnArr);	



break;


case 'getAllSupplierbyClient':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	 $all_users= (array) null;
if($data['ClientID'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

$user_sql = $con->query("select * from supplier where ClientID=".$ClientID."");


while($rows = $user_sql->fetch_assoc())
{

$user_result['Supplier_Name'] = $rows['Supplier_Name'];
$user_result['AutoID'] = $rows['AutoID'];
$all_users[] = $user_result;
	



}


$test = array('SupplierbyClient'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Supplier List Retrieval","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 



case 'getAllCustomerListbyODO':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
	
if($data['Order_Id'] == '' or $data['ClientID'] == ''  )
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
	$Order_Id=strip_tags(mysqli_real_escape_string($con,$data['Order_Id']));
$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));

if($ClientID !='0'){
   	$user_sql = $con->query("select *
		from customer_orders WHERE Order_Id='".$Order_Id."' and ClientID='".$ClientID."' ORDER BY id DESC"); 
}
else{
    	$user_sql = $con->query("select *
		from customer_orders WHERE Order_Id='".$Order_Id."' and Status !='R' ORDER BY id DESC"); 
}

	
	

	
while($rows = $user_sql->fetch_assoc())
{

$user_result['Product_Name'] = $rows['Product_Name'];
$user_result['Quantity_nos'] = $rows['Quantity_nos'];
$user_result['rate'] = $rows['rate'];
$user_result['Status'] = $rows['Status'];
$user_result['C_Status'] = $rows['c_status'];
$user_result['Bill'] = $rows['bill_img'];
$user_result['Name'] = $rows['Name'];
$user_result['user_id'] = $rows['user_id'];
$user_result['Doctor'] = $rows['Doctor_name'];
$user_result['Patient'] = $rows['Patients_name'];;
$user_result['Notes'] = $rows['notes'];
$user_result['Order_Date'] = $rows['Order_Date'];
$user_result['ClientID'] = $rows['ClientID'];
$user_result['c_location'] = $rows['c_location'];
$user_result['BillNo'] = $rows['BillNo'];
$all_users[] = $user_result;
	



}


$test = array('AllCustomerOrderbyOrder'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 

case 'getAllCustomerOrderbyshopssales':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['ClientID'] == '' or $data['sales'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
	$ClientID=strip_tags(mysqli_real_escape_string($con,$data['ClientID']));
	$sales=strip_tags(mysqli_real_escape_string($con,$data['sales']));
	
	if($ClientID ==0){
	   	if($sales !=0){

		$user_sql = $con->query("select Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,customer_orders.user_id,Name,Status,notes,bill_img,c_notes,BillNo,customer_orders.ClientID
		,c_location,clients.Area,clients.Location,sh_to from customer_orders join clients on customer_orders.ClientID=clients.ClientID
        WHERE  COALESCE(user_id)!='' GROUP BY Order_Id,customer_orders.ClientID ORDER BY customer_orders.id DESC;");
	}

	else{

		$user_sql = $con->query("select Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,user_id,Name,Status,notes,bill_img,c_notes,BillNo,customer_orders.ClientID
		,c_location,clients.Area,clients.Location,sh_to  from customer_orders join clients on customer_orders.ClientID=clients.ClientID  WHERE  (user_id='' OR user_id is null) GROUP BY Order_Id,customer_orders.ClientID ORDER BY customer_orders.id DESC");
	}
	 
	}
	else{
	    	if($sales !=0){

		$user_sql = $con->query("select Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,user_id,Name,Status,notes,bill_img,c_notes,BillNo,customer_orders.ClientID
		,c_location,clients.Area,clients.Location,sh_to  from customer_orders join clients on customer_orders.ClientID=clients.ClientID WHERE customer_orders.ClientID='".$ClientID."' and COALESCE(user_id)!='' GROUP BY Order_Id,customer_orders.ClientID ORDER BY customer_orders.id DESC");
	}

	else{

		$user_sql = $con->query("select Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,user_id,Name,Status,notes,bill_img,c_notes,BillNo,customer_orders.ClientID
		,c_location,clients.Area,clients.Location,sh_to  from customer_orders join clients on customer_orders.ClientID=clients.ClientID WHERE customer_orders.ClientID='".$ClientID."' and  (user_id='' OR user_id is null) GROUP BY Order_Id,customer_orders.ClientID ORDER BY customer_orders.id DESC");
	}
	
	}



while($rows = $user_sql->fetch_assoc())
{

$user_result['OrderId'] = $rows['Order_Id'];
$user_result['Order_Date'] = $rows['Order_Date'];
$user_result['qnos'] = $rows['qnos'];
$user_result['amount'] = $rows['amount'];
$user_result['Doctor_name'] = $rows['Doctor_name'];
$user_result['Patients_name'] = $rows['Patients_name'];
$user_result['Name'] = $rows['Name'];
$user_result['user_id'] = $rows['user_id'];
$user_result['Status'] = $rows['Status'];
$user_result['Notes'] = $rows['notes'];
$user_result['Bill'] = $rows['bill_img'];
$user_result['sh_to'] = $rows['sh_to'];
$user_result['CNotes'] = $rows['c_notes'];
$user_result['BillNo'] = $rows['BillNo'];
$user_result['ClientID'] = $rows['ClientID'];
$user_result['c_location'] = $rows['c_location'];
$user_result['Area'] = $rows['Area'];
$user_result['Location'] = $rows['Location'];
$all_users[] = $user_result;
	



}


$test = array('AllCustomerOrderbyAdmin'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 





case 'getAllCustomerOrderbyshop':
	
	
	$data = json_decode(file_get_contents('php://input'), true);
		$all_users=null;
if($data['bill'] == '' or $data['user_id'] == '')
{
$returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
}

else {
	$bill=strip_tags(mysqli_real_escape_string($con,$data['bill']));
	$user_id=strip_tags(mysqli_real_escape_string($con,$data['user_id']));

	if($bill !=0){

		$user_sql = $con->query("select days_taken,reminder_before,Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,user_id,Name,Status,notes,bill_img,c_notes,BillNo,ClientID
		,c_location from customer_orders WHERE user_id='".$user_id."' AND Status !='R' and COALESCE(BillNo)!='' GROUP BY Order_Id ORDER BY id DESC");
	}
	else{

		$user_sql = $con->query("select days_taken,reminder_before, Order_Id,Order_Date,COUNT(Quantity_nos) as qnos,SUM(rate) as amount,Doctor_name,Patients_name,user_id,Name,Status,notes,bill_img,c_notes,BillNo,ClientID
		,c_location from customer_orders WHERE user_id='".$user_id."' AND Status !='R' GROUP BY Order_Id ORDER BY id DESC");;
	}
	

while($rows = $user_sql->fetch_assoc())
{

$user_result['OrderId'] = $rows['Order_Id'];
$user_result['Order_Date'] = $rows['Order_Date'];
$user_result['qnos'] = $rows['qnos'];
$user_result['amount'] = $rows['amount'];
$user_result['Doctor_name'] = $rows['Doctor_name'];
$user_result['Patients_name'] = $rows['Patients_name'];
$user_result['Name'] = $rows['Name'];
$user_result['user_id'] = $rows['user_id'];
$user_result['Status'] = $rows['Status'];
$user_result['Notes'] = $rows['notes'];
$user_result['Bill'] = $rows['bill_img'];
$user_result['CNotes'] = $rows['c_notes'];
$user_result['BillNo'] = $rows['BillNo'];
$user_result['ClientID'] = $rows['ClientID'];
$user_result['days_taken'] = $rows['days_taken'];
$user_result['reminder_before'] = $rows['reminder_before'];
$user_result['c_location'] = $rows['c_location'];
$all_users[] = $user_result;
	



}


$test = array('AllCustomerOrderbyAdmin'=>$all_users);



$returnArr = array("ResponseCode"=>"200","Result"=>"true","ResponseMsg"=>"Shops List","ResultData"=>$test);


echo json_encode($returnArr);		




}

break; 




		default: 
			$response['error'] = true; 
			$response['message'] = 'Invalid Operation Called';
			echo json_encode($response);
	}
	
}else{
	$response['error'] = true; 
	$response['message'] = 'Invalid API Call';
	echo json_encode($response);
}



function isTheseParametersAvailable($params){
	
	foreach($params as $param){
		if(!isset($_POST[$param])){
			return false; 
		}
	}
	return true; 
}