<?php
session_start();
$brcode=$_SESSION['brcode'];
$user=$_SESSION['user'];
if(strlen($brcode)<=0)
{
    print "<script> alert('Session timed out'); parent.document.location='../index.php'; </script>";
    return;
}
$cname=$_REQUEST[cname];
include("../opendb.php");
$brnchtp=$_REQUEST[brnchtp];
print $brnchtp;
$tbl="advamt".$brcode.$user;
mysqli_query($db,"drop table $tbl"); 
if($brnchtp=='spr')
{
    $sq=mysqli_query($db,"select distinct(invno) from spareinvoice where brcode='$brcode' and customer='$cname' order by invno desc");  
    print "<option value='select'>-select-</option>";
    while($rw=mysqli_fetch_array($sq))
    {
	    $tot_payment=0;
	    $outstanding=0;
        $sql=mysqli_query($db,"select sum(amt) from downpayment where invno='$rw[0]' and customer='$cname' and brcode='$brcode'");
        $res=mysqli_fetch_array($sql);
        $adv=$res[0];
        if((mysqli_num_rows($sql)<=0)||($res[0]==''))
        {
            $adv=0; 
        }
	    $sql1=mysqli_query($db,"select sum(tot) from spareinvoice where invno='$rw[0]' and customer='$cname' and brcode='$brcode'");
   	    $res1=mysqli_fetch_array($sql1);
	    $tot_payment=$res1[0];
	    if(mysqli_num_rows($sql1)<=0)
       	{
      		$tot_payment=0; 
       	}
   	    if($tot_payment>0)
	    {      
       		$outstanding=$tot_payment-$adv;
    	}
        if($outstanding>0)
        {?>
            <option value='<? echo $rw[0] ?>'><? echo $rw[0] ?></option>
            <?
        }
    }
}
if($brnchtp=='pur')
{
    $sq=mysqli_query($db,"select distinct(pbillno) from sparepurchase where brcode='$brcode' and suplier='$cname' order by pbillno desc");  
    print "<option value='select'>-select-</option>";
    while($rw=mysqli_fetch_array($sq))
    {
        $tot_payment=0;
        $outstanding=0;
        $sql=mysqli_query($db,"select sum(amt) from downpayment where invno='$rw[0]' and customer='$cname' and brcode='$brcode'");
        $res=mysqli_fetch_array($sql);
        $adv=$res[0];
        if((mysqli_num_rows($sql)<=0)||($res[0]==''))
        {
            $adv=0; 
        }
        $sql1=mysqli_query($db,"select sum(tot) from sparepurchase where pbillno='$rw[0]' and suplier='$cname' and brcode='$brcode'");
   	    $res1=mysqli_fetch_array($sql1);
	    $tot_payment=$res1[0];
	    if(mysqli_num_rows($sql1)<=0)
       	{
      		$tot_payment=0; 
       	}
   	    if($tot_payment>0)
	    {      
       		$outstanding=$tot_payment-$adv;
    	}
        if($outstanding>0)
        {?>
            <option value='<? echo $rw[0] ?>'><? echo $rw[0] ?></option>
        <?
        }
    }
}
?>