<?php

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

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

//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(extra_amount) as extra_amount ,sum(discount) as discount
FROM (
  SELECT cm.id,cm.ccode,cm.cname,cm.mobile,SUM(sd.tamount) as samount,0 as payamount,sum(sd.extra_amount) as extra_amount,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' and sd.id<$edit_id GROUP BY cm.id
  
  UNION ALL
  
  SELECT cm.id,cm.ccode,cm.cname,cm.mobile,0 as samount,sum(sc.received_amount) as payamount,0 as extra_amount,sum(sc.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 sc.saleid<$edit_id and cm.id='$customerid' GROUP by cm.id
 
) a GROUP BY a.id  ");



$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);



$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['extra_amount']+$row['samount']+$opening_balance)-($row['payamount']+$row['discount']);

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




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

?>