<?
session_start();
include("../opendb.php");
include("../test.php");
$tbl="sparetmp".$brcode.$user;
$tbl2="stkval".$brcode.$user;
print "<center> <font color='red'><b>$branch</b> </font><br><font size=7><b><i><font color=#23D21D>Stock</font></I> </b><font size=6>Valuation ";
print "<table border=1><th>Date <th>Part Code <th>Part Name <th>Qty<th>Price<th>Total";
mysqli_query($db,"CREATE TABLE $tbl2 (partcode varchar(200),partname varchar(200),entrydate date,supqty double(10,2),price double(10,2))");

mysqli_query($db,"delete from $tbl2");

$re=mysqli_query($db,"select * from $tbl order by partcode");
while($row=mysqli_fetch_array($re))
{
 $t='stk';
  $no=$row[supqty];
 $sql="select entrydate,supqty,aprice,disc,hand,tax,taxtype from sparepurchase where partcode='$row[partcode]'  and brcode='$brcode' order by entrydate desc";
  $chk=mysqli_query($db,$sql)or die(mysqli_error());
 if(mysqli_num_rows($chk)<=0)
 {
//   print "<tr bgcolor='ivory'><td colspan=5><font color=red>Item $row[partcode] Not found</td></tr>";
 $sql="select effectfrom,ndpcost from spareprmast where partcode='$row[partcode]' and brcode='$brcode' order by effectfrom desc limit 1";

  $chk=mysqli_query($db,$sql)or die(mysqli_error());
 $t='pr';
 }
   while($row1=mysqli_fetch_array($chk))
   {
     if($t=='stk')
    {
$pcode=$row[partcode];
$pname=htmlspecialchars(addslashes($row[partname]));
$dt=$row1[entrydate];
//$dis=$row1[[price]*$row1[disc]
//$am1=$row1[price]-$dis

$pr=$row1[2]/$row1[1];
if($row1[hand]>0)
{
 $hnd=($pr*$row1[hand]/100);
 $pr+=$hnd;
}
if($row1[taxtype]=='CST')
{
 $tx=($pr*$row1[tax]/100);
 $pr+=$tx;
}
$qt=$row1[1];
    }
else
{
$pcode=$row[partcode];
$pname=htmlspecialchars(addslashes($row[partname]));
$dt=$row1[effectfrom];
$pr=$row1[1];
$qt=$row[supqty];
}
     if($t=='pr' && $no>$row1[1])
     { 
       $sq="insert into $tbl2 values('$pcode','$pname','$dt', '$qt','$pr')";

      mysqli_query($db,$sq) or die('err1'.mysqli_error());
      $no-=$qt;
     }
else if($no>0)
     { 
       $sq="insert into $tbl2 values('$pcode','$pname','$dt', '$no','$pr')";
      mysqli_query($db,$sq) or die('err2'.mysqli_error());
      $no-=$no;
     }
$pcode=$row[partcode];
$pname=htmlspecialchars(addslashes($row[partname]));
$dt=$row1[entrydate];
$pr=$row1[2];

  }
if($no>0)
     { 
       $sq="insert into $tbl2 values('$pcode','$pname','$dt', '$no','$pr')";
      mysqli_query($db,$sq) or die('err2'.mysqli_error());
      $no-=$no;
     }
}
 
$re2=mysqli_query($db,"select * from $tbl2 order by partcode");
while($row=mysqli_fetch_array($re2))
{
$x=$row[price]*$row[supqty];
  print "<tr><td>".datetohtml($row[entrydate])."</td><td>$row[partcode]</td><td>$row[partname]</td>";
  print "<td align=right>$row[supqty]</td><td align=right>$row[price]</td><td align=right>$x</td></tr>";
$tq+=$row[supqty];
$totx+=$x;
}
print "<tr><td colspan=3><center><b>Total</b></td><td align=right><b>$tq</td><td></td>";
print "<td align=right><b>".putComa($totx)."</td>";
     
?>


