<? session_start();
$brcode=$_SESSION['brcode'];
$user=$_SESSION['user'];

date_default_timezone_set("Asia/Kolkata");
$logdt=date("Y-m-d");
$logtime=date("H:i:s");

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 brcode = '$brcode'")or die(mysqli_error($db));
$r=mysqli_fetch_row($us);
$user_level=$r[0];
$y=$_REQUEST['y'];
$m=$_REQUEST['m'];
$d=$_REQUEST['d'];
$y1=$_REQUEST['y1'];
$m1=$_REQUEST['m1'];
$d1=$_REQUEST['d1'];

$save=$_REQUEST['save'];

$submit=$_REQUEST['submit'];

$item=$_REQUEST['item'];
$taxp=$_REQUEST['taxp'];
$unirate=$_REQUEST['unirate'];
$qty=$_REQUEST['qty'];
$gross=$_REQUEST['gross'];
$disc=$_REQUEST['disc'];
$uni_amt=$_REQUEST['uni_amt'];



$taxamt=$_REQUEST['taxamt'];
$gtot=$_REQUEST['gtot'];
$disfree=$_REQUEST['disfree'];
$pno=$_REQUEST['pno'];
$chasis=$_REQUEST['chasis'];
$config=$_REQUEST['config'];

$cessp=$_REQUEST['cessp'];
$cessamt=$_REQUEST['cessamt'];
$oth=$_REQUEST['oth'];
$ttype=$_REQUEST['ttype'];



$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($db));
$dtrow=mysqli_fetch_row($dtre);

if($dtrow[0]>5 || $dtrow[0]<0)
{
 print "<script> alert('Invalid Date, Entry possible for last 5 days only'); history.back(1); </script>";
 return;
}
}
//'$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]','$row[ttype]'

$inv=$_REQUEST['inv'];
$supplier=$_REQUEST['supplier'];




   $tbl= $user.str_replace('.','',$REMOTE_ADDR).'itma' ;
   
   print $tbl;
if($save)
{
$curdate=$y.'-'.$m.'-'.$d;
$pudate=$y1.'-'.$m1.'-'.$d1;
$cc=mysqli_query($db,"select * from item_purchase_veh where purinvoice='$inv' and brcode='$brcode'  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_veh 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','0','0','0','$row[cessp]','$row[cessamt]','$row[others]','$row[ttype]','material')";
mysqli_query($db,$sql)or die('<b>item_purchase write errr:'.mysqli_error($db));


}
$ip_address = "$jvno|Spare Purchase|Add";
log_entry($brcode,$user,$ip_address,"item purchase entry-$row[chasis]-jv $jvno",$db);

$supres=mysqli_query($db,"select web from sup_master where icode='$supplier' ");
$surow=mysqli_fetch_row($supres);
$supplierhead=$surow[0];


$res1=mysqli_query($db,"select sum(net) net,taxp,ttype,pno from $tbl group by taxp");
while($row1=mysqli_fetch_array($res1))
{

if($row1['ttype']=='INTRA STATE')
{ 

  $sql="insert into journal2 values('$curdate','$jvno','Dr','Inward Supply - Accessories','$row1[net]', '0','Item grno $row1[pno] P.Bill No: $inv','$brcode','I pur','',' ','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error 1:".mysqli_error($db));
}

else
{
 $sql="insert into journal2 values('$curdate','$jvno','Dr','Inward Supply - Accessories','$row1[net]', '0','Item grno $row1[pno] P.Bill No: $inv','$brcode','I pur',' ','','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error 1:".mysqli_error($db));

}
}

$res1=mysqli_query($db,"select sum(taxamt) taxamt,taxp,ttype,pno from $tbl group by taxp");
while($row1=mysqli_fetch_array($res1))
{

if($row1['ttype']=='INTRA STATE')
{ 
$taxper=$row1['taxp']/2;
$taxa=$row1['taxamt']/2;

  $sql="insert into journal2 values('$curdate','$jvno','Dr','Input Tax','$taxa', '0','Item grno $row1[pno] Pur.Bill No: $inv','$brcode','I pur',' ',' ','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error 2:".mysqli_error($db));

  $sql="insert into journal2 values('$curdate','$jvno','Dr','Input Tax','$taxa', '0','grno $row1[pno] P.Bill No: $inv','$brcode','I pur',' ',' ','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error 2cess:".mysqli_error($db));
}

else
{

$sql="insert into journal2 values('$curdate','$jvno','Dr','Input Tax','$row1[taxamt]', '0','grno $row1[pno] Purch.Bill No: $inv','$brcode','I pur',' ',' ','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error 2cess:".mysqli_error($db));

}
}

$res1=mysqli_query($db,"select sum(others) others from $tbl ");
while($row1=mysqli_fetch_array($res1))
{

if($row1['others']>0)
{
$sql="insert into journal2 values('$curdate','$jvno','Dr','Other Charges (Item)','$row1[others]', '0','Item grno $pno P.Bill No: $inv','$brcode','I pur','',' ','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error 4:".mysqli_error($db));
}
}
 //$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($db));

//}


$res1=mysqli_query($db,"select sum(gtot) gtot from $tbl ");
while($row1=mysqli_fetch_array($res1))
{

 $sql="insert into journal2 values('$curdate','$jvno','Cr','$supplierhead','0','$row1[gtot]','Item grno $pno P.Bill No: $inv','$brcode','I pur','','','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error 3:".mysqli_error($db));
 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) grno $pno :$inv','$brcode','I Pur','','','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error dif1:".mysqli_error($db));
}
else if($dif>0)
{
 $sql="insert into journal2 values('$curdate','$jvno','Cr','Round Off','0','$x','Round of Purchase other (Un registered) grno $pno :$inv','$brcode','I pur','','','$inv','$logtime $user','$logdt')";
mysqli_query($db,$sql) or die("J V Write error dif:".mysqli_error($db));
}

mysqli_query($db,"delete from $tbl") or die(mysqli_error($db));
print "Data has been saved";
mysqli_query($db,"drop table $tbl"); //or die($tmp.'Cannot be created '.mysqli_error($db));

// 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;
 }
   $sql="create table if not exists $tbl (code varchar(20),item_code varchar(50),taxp float(12,2) ,uni_amt double (12,2),qty double(12,2),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),ttype varchar(100))";
   mysqli_query($db,$sql);//  or die($tmp.'Cannot be created '.mysqli_error($db));

  $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_veh 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','$ttype')";
 mysqli_query($db,$sql) or die ('<b>tmp table err:'.$tbl.mysqli_error($db));
 }
 $act1=$_REQUEST['act1'];
 $code1=$_REQUEST['code1'];
 if($act1=='del')
  {
      print "delete from $tbl where code='$code1'";
     mysqli_query($db,"delete from $tbl where code='$code1'");
  }
?>
<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.d.value;
var mon1=document.f1.m.value;
var year1=document.f1.y.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?>" method='post'>

<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_veh 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 web!='null'  order by supname");

while($row=mysqli_fetch_row($res))
{
 print "<option value='$row[16]'>$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 partmaster where partcode='$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?act1=del&code1=$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($db));
$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>
