<?php

require_once("../config/configDB.php");

if($_POST['cid']) {
  $customerid     =   $_POST['cid'];
  $pid= $_POST['pid'];
}

//echo $customerid;

$sql = mysqli_query($conn,"SELECT a.id,a.ccode,a.cname,a.mobile,sum(a.samount) as samount,sum(payamount) as payamount,sum(discount) as discount 
FROM (
  SELECT cm.id,cm.ccode,cm.cname,cm.mobile,SUM(sd.tamount) as samount,0 as payamount,0 as discount from customer_master as cm LEFT JOIN saleheader sd ON cm.id=sd.customer_id WHERE cm.isdelete=1 and sd.status='' and cm.id='$customerid' GROUP BY cm.id
  
  UNION ALL
  
  SELECT cm.id,cm.ccode,cm.cname,cm.mobile,0 as samount,sum(sc.received_amount) as payamount,sum(discount) as discount from customer_master as cm LEFT JOIN customer_payment_header as sc ON cm.id=sc.customerID WHERE cm.isdelete=1 and sc.status='' and cm.id='$customerid' GROUP by cm.id
 
) a GROUP BY a.id  ");



$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);

$sql_return=mysqli_query($conn,"select Sum(tamount) as return_amount from sale_return_header where status='' and customer_id='$customerid' ");
$row_return=mysqli_fetch_array($sql_return,MYSQLI_ASSOC);

$return_amount=$row_return['return_amount'];

$sql_opening=mysqli_query($conn,"select opening_balance from customer_master where id='$customerid' ");
$row_opening=mysqli_fetch_array($sql_opening,MYSQLI_ASSOC);

$opening_balance=$row_opening['opening_balance'];



$cname=$row['cname'];
$pamount1        = ($row['samount']+$opening_balance)-($row['payamount']+$row['discount']+$return_amount);

$pamount=number_format($pamount1,2,'.','');




$result = mysqli_query($conn,"SELECT *  FROM product_master WHERE product_type='Return'  ");

while($row_tray=mysqli_fetch_array($result))
{
$prid=$row_tray['id'];
}

$query_purchase=mysqli_query($conn,"select sum(trd.out_tray) as outqty,sum(trd.in_tray) as inqty from saleheader as trd  where trd.status=''   and trd.customer_id='".$customerid."'");


while($row_pqty=mysqli_fetch_array($query_purchase))
{
$outqty=$row_pqty['outqty'];
$inqty=$row_pqty['inqty'];

}


$available_qty=$outqty-$inqty;

$aqty=number_format($available_qty,2,'.','');





 $output = $pamount.'||'.$available_qty.'||';
 
 echo $output;  

?>