<? session_start();
if(strlen($brcode)<=0)
{
 print "<script> alert('Session timed out'); parent.document.location='../ind.php'; </script>";
 return;
}

include("../opendb.php");
include("../test.php");

//newly added

$us=mysqli_query($db,"select level from bruser where username='$user' and branch = '$brcode'")or die(mysqli_error());
$r=mysqli_fetch_row($us);
$user_level=$r[0];

$dt=$y.'-'.$m.'-'.$d;
//print $user_level;
//print $dt;

if($user_level<=4)
{
$sq="select to_days(curdate())-to_days('$dt')";
$dtre=mysqli_query($db,$sq)or die(mysqli_error());
$dtrow=mysqli_fetch_row($dtre);

if($dtrow[0]>3 || $dtrow[0]<0)
{
 print "<script> alert('Invalid Date, Entry possible for last 3 days only'); history.back(1); </script>";
 return;
}
}
//


   $tbl= $user.str_replace('.','',$REMOTE_ADDR).'itm' ;
if($save)
{
$curdate=$y.'-'.$m.'-'.$d;
$pudate=$y1.'-'.$m1.'-'.$d1;
$cc=mysqli_query($db,"select * from item_purchase where purinvoice='$inv' and brcode='$brcode' and pdate='$pudate' and sup='$supplier' ");
if(mysqli_num_rows($cc)>0)
{
 print "<script> alert('Duplicate purchase invoice no'); history.back(1); </script>";
 return;
}


$res=mysqli_query($db,"select * from $tbl");
if(mysqli_num_rows($res)<=0)
{
 print "<script> alert('Table Empty'); </script>";
 return;
}
$jvr=mysqli_query($db,"select max(jvno) from journal2 where brcode='$brcode'");
 $j_row=mysqli_fetch_row($jvr);
  if($j_row[0]<=0)
   $jvno=1;
  else
  $jvno=($j_row[0]+1);

while($row=mysqli_fetch_array($res))
{
$sql="insert into item_purchase values('$row[0]','$row[1]','$row[2]','$row[3]','$row[4]', '$row[5]', '$row[6]','$row[7]','$row[8]','$row[9]','$row[10]','$row[11]','$inv', '$brcode', '-','-','$supplier','$pudate','$curdate','$jvno','$row[chasis]','0','$row[config]','$row[cessp]','$row[cessamt]','$row[others]')";
mysqli_query($db,$sql)or die('<b>item_purchase write errr:'.mysqli_error());

$sq="update veh_purchase set newconfig='$row[config]' where chasis='$row[chasis]' and brcode='$brcode'";
mysqli_query($db,$sq) or die(mysqli_error());
log_entry($brcode,$user,$REMOTE_ADDR,"item purchase entry-$row[chasis]-jv $jvno");

$supres=mysqli_query($db,"select supname from sup_master where code='$supplier'");
$surow=mysqli_fetch_row($supres);
$supplier=$surow[0];
if($row[taxp]=='14.50'||$row[taxp]=='4'||$row[taxp]=='13.50'||$row[taxp]=='2'||$row[taxp]=='5')
{ 


  $sql="insert into journal2 values('$curdate','$jvno','Dr','Purchase $row[taxp](other)','$row[net]', '0','Item P.Bill No: $inv','$brcode','I pur','',' ','$inv')";
mysqli_query($db,$sql) or die("J V Write error 1:".mysqli_error());

  $sql="insert into journal2 values('$curdate','$jvno','Dr','Input tax $row[taxp](other)','$row[taxamt]', '0','Item P.Bill No: $inv','$brcode','I pur',' ',' ','$inv')";
mysqli_query($db,$sql) or die("J V Write error 2:".mysqli_error());

  $sql="insert into journal2 values('$curdate','$jvno','Dr','Input Cess $row[cessp](other)','$row[cessamt]', '0','P.Bill No: $inv','$brcode','I pur',' ',' ','$inv')";
mysqli_query($db,$sql) or die("J V Write error 2cess:".mysqli_error());

$sql="insert into journal2 values('$curdate','$jvno','Dr','Other Charges (Item)','$row[others]', '0','Item P.Bill No: $inv','$brcode','I pur','',' ','$inv')";
mysqli_query($db,$sql) or die("J V Write error 4:".mysqli_error());


 $sql="insert into journal2 values('$curdate','$jvno','Cr','$supplier','0','$row[gtot]','Item P.Bill No: $inv','$brcode','I pur',' ',' ','$inv')";
mysqli_query($db,$sql) or die("J V Write error 3:".mysqli_error());

}
else
{
 $sql="insert into journal2 values('$curdate','$jvno','Dr','Purchase other (Un registered)','$row[net]', '0','Item P.Bill No: $inv','$brcode','I pur',' ','','$inv')";
mysqli_query($db,$sql) or die("J V Write error 1:".mysqli_error());

 $sql="insert into journal2 values('$curdate','$jvno','Cr','$supplier','0','$row[net]','Item P.Bill No: $inv','$brcode','I pur','','','$inv')";
mysqli_query($db,$sql) or die("J V Write error 3:".mysqli_error());
 print "<font color=green><b>Data has been saved</b></font>";
}
}
$jvd=mysqli_query($db,"select sum(dramt)-sum(cramt) from journal2 where jvno='$jvno' and brcode='$brcode'");
$difrow=mysqli_fetch_array($jvd);
$dif=$difrow[0];
$x=abs($dif);
if($dif<0)
{
$sql="insert into journal2 values('$curdate','$jvno','Dr','Round Off','$x', '0','Round ofPurchase other (Un registered):$inv','$brcode','I Pur','','','$inv')";
mysqli_query($db,$sql) or die("J V Write error dif1:".mysqli_error());
}
else if($dif>0)
{
 $sql="insert into journal2 values('$curdate','$jvno','Cr','Round Off','0','$x','Round of Purchase other (Un registered):$inv','$brcode','I pur','','','$inv')";
mysqli_query($db,$sql) or die("J V Write error dif:".mysqli_error());
}

mysqli_query($db,"delete from $tbl") or die(mysqli_error());
print "Data has been saved";
// print "<script>parent.document.location='purch_frm.html' </script>";
 return;
}

if($submit)
 {
 if($gtot<=0)
 {
   print "<script> alert('Invalid Amount'); history.back(1); </script>";
   return;
 }
mysqli_query($db,"drop table $tbl"); //or die($tmp.'Cannot be created '.mysqli_error());
   $sql="create table $tbl (code varchar(20),item_code varchar(50),taxp float(12,2) ,uni_amt double (12,2),qty int(5),gross double(12,2) ,disc float(12,2),net float(12,2) ,taxamt float(12,2) ,gtot float(12,2) ,disfree float(12,2), pno int(5),brcode varchar(20),chasis varchar(100), config varchar(100), cessp double(12,2),cessamt double(14,2),others double(14,2))";
   mysqli_query($db,$sql);//  or die($tmp.'Cannot be created '.mysqli_error());

  $code=date("dmy",time()).substr(time(),7,3); 
  $code=str_replace(' ','-',$code);
  $pur_date=$y.'-'.$m.'-'.$d;

  $res=mysqli_query($db,"select max(pno) from item_purchase where brcode='$brcode'");
   $pno_row=mysqli_fetch_row($res);
  $pno=$pno_row[0];
$unirate=$gtot/$qty;

   if($pno<=0)
     $pno=1;
    else
     $pno=$pno+1;

   $sql="insert into $tbl values('$code','$item','$taxp','$unirate','$qty','$gross', '$disc','$uni_amt','$taxamt','$gtot','$disfree','$pno','$brcode','$chasis','$config','$cessp','$cessamt','$oth')";
 mysqli_query($db,$sql) or die ('<b>tmp table err:'.$tbl.mysqli_error());
 }
 if($act=='del')
  {
     mysqli_query($db,"delete from $tbl where code='$code'");
  }
?>
<style>
body,td{font-family:'arial narrow';letter-spacing:1;}
tr{background-color:c1d7bb}
.mnu{margin-left:5}
</style>

<script>




function validate()
{
 var purinvoice=document.f1.inv.value;
 var sub="true";
 if(purinvoice.length<=0)
 {
   alert('Invalid Invoice NO'); sub="false";
 }





var day1=document.f1.d1.value;
var mon1=document.f1.m1.value;
var year1=document.f1.y1.value;
var chdt=day1+"/"+mon1+"/"+year1;

var tempdt=year1+"-"+mon1+"-"+day1;
var tempact=document.f1.act.value;
var tempacf=document.f1.acf.value;


function ValidateDate() 
{
 
    var msg = '';
 
    this.isDate = function(date) 
     {
 
        var explodeData = date.explode("/");
        var day = explodeData[0];
        var month = explodeData[1];
        var year = explodeData[2];
 
        var thisMonth = new Date(year, month, 0);
        var daysInMonth = thisMonth.getDate();
        var pattern = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
 
        if (!pattern.test(date)) {
            msg = "invalid date format";
        }
        else if (day > daysInMonth) {
            msg = "invalid day";
        }
        else if (month > 12) {
            msg = "invalid month";
        }
 
        if (msg) {
            return false;
        } else {
            return true;
        }
    }
 
    this.getMsg = function() 
    {
 
        return msg;
    }
}

 
 vDate = new ValidateDate();
 
if (vDate.isDate(chdt))

 {

if(tempdt>=tempacf&&tempdt<=tempact)
{

//alert('hii');

}
else
{
sub="false";

document.f1.m1.focus();

alert('date should be in between current Financial Year');

}

 //alert("Date is valid");
 }
else 

{
 sub="false";

document.f1.d1.focus();
alert("Date is not valid: " + vDate.getMsg()); 
}




 if(sub=="false")
  return false;
 else
  return true;
}
</script>
<body bgcolor='ivory' onSubmit="return validate()">
<center>
<form name='f1' action="<?print $PHP_SELF?>">

<table cellspacing=1 cellpadding=1 bgcolor=green width=100%>
<tr><td align=center>
<table cellspacing=5 width=100%>
<tr><td colspan=4 align=center bgcolor='green'><font color=ivory><b>ITEM PURCHASE No(
<?
   $res=mysqli_query($db,"select max(pno) from item_purchase where brcode='$brcode'");
   $pno_row=mysqli_fetch_row($res);
  $pno=$pno_row[0];
   if($pno<=0)
     $pno=1;
    else
     $pno=$pno+1;

 print $pno.")";
?>
</TD></TR>
<tr>
  <td> Current Date</td><td>
   dd <input type=text name='d' size=2 value='<?print date("d",time())?>'>
   mm <input type=text name='m' size=2 value='<?print date("m",time())?>'>
   yy <input type=text name='y' size=4 value='<?print date("Y",time())?>'>
 <td><font color=red>Pur. Invoice </td><td align=right><input type=text name='inv'></td>

<tr><td>Supplier </td><td><select name='supplier'>
<?
if ($brcode=='PSN236')
	$res=mysqli_query($db,"select * from sup_master");
else
	$res=mysqli_query($db,"select * from sup_master where branch='$brcode'");

while($row=mysqli_fetch_row($res))
{
 print "<option value='$row[0]'>$row[1]</option>";
}
?>
</select> 
</td><td colspan=2>
Pur Dt 
   dd <input type=text name='d1' size=2 value='<?print date("d",time())?>'>
   mm <input type=text name='m1' size=2 value='<?print date("m",time())?>'>
   yy <input type=text name='y1' size=4 value='<?print date("Y",time())?>'>
</td></tr>
</table>
</td></tr>
</table>
<br>
<style>
.x{font-size:13.96}
th{background-color:598259;color:ivory}
</style>
</center>
<table class=x width=100%>
<th>Item  <th>Tax Rate <th>Unit Price <th> Qty  <th>Gross Value <th>Cash Disc <th>Net value
<th>Tax Amt.<th>Other Amt. <th>Grant Total <th>Disc/Gift <br>Free<th>Delete
<?
$tot=0;
$res=mysqli_query($db,"select * from $tbl");
while($row=mysqli_fetch_row($res))
{
 $rr=mysqli_query($db,"select * from itemmaster where code='$row[1]'");
  $item_row=mysqli_fetch_row($rr);
 print "<tr><td>$item_row[1]</td><td align=right>$row[2]</td><td align=right>$row[3]</td><td align=right>$row[4]</td><td align=right>$row[5]</td>";
 print "<td align=right>$row[6]</td><td align=right>$row[7]</td><td align=right>$row[8]</td><td align=right>$row[25]</td><td align=right>$row[9]</td><td align=right>$row[10]</td><td  align=center><a href='$PHP_SELF?act=del&code=$row[0]'><img src='../img/delete2.gif' border=0></a></td>";
$tot+=$row[9];
}
print "<tr><td colspan=9 align=center>Total </td><td align=right>$tot</td><td colspan=2></td></tr>";
?>
</table>
<br>

<table class=x>
<th>Tax% <th>Tax Amount <th>Before Tax Amount
<?
//include("../test.php");
$t1=0;
$t2=0;
$res=mysqli_query($db,"select taxp,sum(taxamt),sum(net) from $tbl group by taxp");
while($row=mysqli_fetch_row($res))
{
 print "<tr><td align=right>". putComa($row[0])."</td><td align=right>". putComa($row[1])."</td><td align=right>".putComa($row[2])."</td></tr>";
$t1+=$row[1];
$t2+=$row[2];
}
print "<tr><td>Total</td><td align=right>".putComa($t1)."</td><td align=right>".putComa($t2)."</td></tr>";
?>

<?
//
$acpd=mysqli_query($db,"select * from acperiod") or die ('err'.mysqli_error());
$acrow=mysqli_fetch_row($acpd);


?>
<tr><td><input type=hidden name='acf' value='<?print $acrow[0]?>'></td>
<td><input type=hidden name='act' value='<?print $acrow[1]?>'></td>
</tr>

</table> 
<br>
<input type=submit value='SAVE' name='save'>
</form>
