<?php 
include "../config.php";
$sales_code = $_POST['invoice'];
$customer = $_POST['customer'];
//echo $customer;
if ($sales_code != '' && $sales_code != 'opening')
{
$output = (object)['code'=>null];
$total_amount_paid = 0;
$sales_balance = mysqli_query($connect,"select salescode,ifnull((totalamount),0)as sales from second_transaction where salescode='$sales_code'&& status!='deleted'");
while($sales_rec = mysqli_fetch_array($sales_balance)) {
$output = (object)['code'=>$sales_rec['salescode'],'value'=>$sales_rec['sales'],'pending'=> 0];
$total_amount_data = $sales_rec['sales'];
}
$sales_est_balance = mysqli_query($connect,"select salescode,ifnull((totalamount),0)as sales from second_transaction_est where salescode='$sales_code'&& status!='deleted'");
while($sales_est_rec = mysqli_fetch_array($sales_est_balance)) {
$output = (object)['code'=>$sales_est_rec['salescode'],'value'=>$sales_est_rec['sales'],'pending'=> 0];
$total_amount_data = $sales_est_rec['sales'];
}
$collection_balance = mysqli_query($connect,"SELECT id, date, customer, sales_code, totalamount, pendingamount, amount, otheramount, paymentmethod, remark, cheque, code, user, time, financialyear, editdate, edittime, status FROM creditdetails where sales_code='$sales_code'&& status!='deleted'");
while($collection_rec = mysqli_fetch_array($collection_balance)) {
$amount_paid = $collection_rec['amount'] + $collection_rec['otheramount'];
$total_amount_paid += $amount_paid;
}
$pending_amount =  $total_amount_data - $total_amount_paid;
$output->pending = $pending_amount;
echo json_encode($output);
} else if($sales_code == 'opening') {
$total_amount_paid = 0;
$opening_balance = mysqli_query($connect,"select salesopening from customerdetails where code='$customer'&& status!='deleted'");
$dis_opening = mysqli_fetch_assoc($opening_balance);
$opening_value = $dis_opening['salesopening'];
$collection_balance = mysqli_query($connect,"SELECT id, date, customer, sales_code, totalamount, pendingamount, amount, otheramount, paymentmethod, remark, cheque, code, user, time, financialyear, editdate, edittime, status FROM creditdetails where sales_code='$sales_code' && customer = '$customer' && status!='deleted'");
while($collection_rec = mysqli_fetch_array($collection_balance)) {
$amount_paid = $collection_rec['amount'] + $collection_rec['otheramount'];
$total_amount_paid += $amount_paid;
}
$pending_amount =  $opening_value - $total_amount_paid;
$output = (object)['code'=>null,'value'=> $opening_value,'pending'=>$pending_amount];
echo json_encode($output);
}
else
{
 echo "";
}

?>
