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

include("../opendb.php");
$tbl= $user.str_replace('.','',$REMOTE_ADDR).'invitm' ; 


//newly added

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

$dt=$invy.'-'.$invm.'-'.$invd;
//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;
}
}
//
?>
<script>
 function valid()
  {
   submitOK="true";
   if(document.f1.cust.selectedIndex<=0 && document.f1.dea.selectedIndex<=0)
   {
     submitOK="false";
     document.f1.cust.focus();

     alert('Invalid customer/dealer'); 
     //return false;
   }


var day1=document.f1.invd.value;
var mon1=document.f1.invm.value;
var year1=document.f1.invy.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
{
submitOK="false";

document.f1.invm.focus();

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

}

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

{
 submitOK="false";

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

  if(submitOK=="true")
   return true;
  else
   return false;


  }
</script>
<?

 $res=mysqli_query($db,"select max(invno) from invoice_item where brcode='$brcode'");
   $pno_row=mysqli_fetch_row($res);
  $pno=$pno_row[0];
   if($pno<=0)
     $pno=1;
    else
     $pno=$pno+1;

if($submit)
 {
    $sql="create table $tbl (code varchar(50),item_code varchar(50),taxp float(12,2) ,uni_amt float (12,2),qty int(5),gross float(12,2) ,net float(12,2) ,taxamt float(12,2) ,gtot float(12,2), pno int(5),brcode varchar(20))";
   mysqli_query($db,$sql);

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

   $sql="insert into $tbl values('$item_code','$item','$taxp','$uni_amt','$qty','$gross', '$net','$taxamt', '$gtot','$pno','$brcode')";

 mysqli_query($db,$sql) or die ('$tbl err'.mysqli_error());
 }

//**********************************************
if($save)
{

 $in=mysqli_query($db,"select max(invno) from invoice_item where brcode='$brcode'");
  $invrow=mysqli_fetch_row($in);
   if($invrow[0]<=0)
    $invno=1;
   else
    $invno=$invrow[0]+1;

  
 $j=mysqli_query($db,"select max(jvno) from journal2 where brcode='$brcode'");
  $jvrow=mysqli_fetch_row($j);
   if($jvrow[0]<=0)
    $jvno=1;
   else
    $jvno=$jvrow[0]+1;

  $re=mysqli_query($db,"select * from $tbl") or die($tbl.' err:'.mysqli_error());
  while($row=mysqli_fetch_array($re))
  {
   if(strlen($dea)>0)
    { $customer=$dea; $ctype='D';}
   else
    { $customer=$cust; $ctype='C';}
$invdate=$invy.'-'.$invm.'-'.$invd;

$itres=mysqli_query($db,"select item_code from item_purchase where code='$row[code]' and brcode='$brcode'");
$itcoderow=mysqli_fetch_row($itres);

    $sql="insert into invoice_item (code,item_code,taxp,uni_amt,qty,gross,net,taxamt,gtot, invno,brcode,da,jvno,soldto,saletype,invdate) values('$row[code]','$itcoderow[0]','$row[taxp]','$row[uni_amt]', '$row[qty]' ,'$row[gross]', '$row[net]','$row[taxamt]', '$row[gtot]','$row[pno]' ,'$brcode','$da','$jvno','$customer','$ctype','$invdate')";
 mysqli_query($db,$sql) or die(mysqli_error());

$sql="insert into journal2 values('$invdate','$jvno','Dr','$customer','$row[gtot]', '0','Item Sales INV No: $invno','$brcode','Itm sale',' ','','$invno')";
mysqli_query($db,$sql) or die("J V Write error 1:".mysqli_error());

$sql="insert into journal2 values('$invdate','$jvno','Cr','Output tax $taxp', '0','$row[taxamt]','Item Sales INV No: $invno','$brcode','Itm sale',' ',' ','$invno')";
mysqli_query($db,$sql) or die("J V Write error 2:".mysqli_error());

 $sql="insert into journal2 values('$invdate','$jvno','Cr','Sales $taxp(other)','0','$row[net]','Item Sales INV No: $invno','$brcode','Itm sale',' ',' ','$invno')";
mysqli_query($db,$sql) or die("J V Write error 3:".mysqli_error());

mysqli_query($db,"update item_purchase set sale_invoice='$invno',sale_count=(sale_count+$row[qty]) where code='$row[code]' and brcode='$brcode'");
 mysqli_query($db,"delete from $tbl");
print "<font color=green>Data has been saved</font>";
 }
}

 if($act=='del')
  {
     mysqli_query($db,"delete from $tbl where code='$code'")or die(mysqli_error());
  }
?>
<script>
	parent.banner1.location='itemlist.php';
</script>

<style>
body,td{font-family:'arial narrow';letter-spacing:1;}
tr{background-color:c1d7bb}
.mnu{margin-left:5}
</style>
<BODY BGCOLOR='IVORY'>

<style>
.x{font-size:13.96}
th{background-color:598259;color:ivory}
</style>
</center>
<form name='f1' action='<?print $PHP_SELF?>' onSubmit="return valid()">
<table>
<tr><td>
Invoice Date </td><td>dd<input type=text name='invd' value='<?print date("d",time())?>' size=2>
mm<input type=text name='invm' value='<?print date("m",time())?>' size=2>
yy<input type=text name='invy' value='<?print date("Y",time())?>' size=4></td> </tr>
<tr><td>
Sold To  Dealer </td><td><select name='dea'>
<option></option>
<?
$r=mysqli_query($db,"select * from sup_master where branch='$brcode' order by supname");
while($ro=mysqli_fetch_array($r))
{
 print "<option>$ro[supname]</option>";
}
?>
</select> </td></tr>
<tr><td align=right>
Customer </td><td><select name='cust'> <option></option>
<?
$r=mysqli_query($db,"select * from cust_master where branch='$brcode' order by acname");
while($ro=mysqli_fetch_array($r))
{
 print "<option>$ro[acname]</option>";
}
?>
</select>
</td></tr>
</table>
<br>
<b>SELECTED ITEMS</b>
<table class=x width=100%>
<th>Item  <th>Tax Rate <th>Unit Price <th> Qty  <th>Gross Value <th>Net value
<th>Tax Amt. <th>Grant Total<th>Delete
<?
$tot=0;
$res=mysqli_query($db,"select * from $tbl");

while($row=mysqli_fetch_row($res))
{
$itemname=explode('-',$row[1]);

 $rr=mysqli_query($db,"select chasis from item_purchase where code='$itemname[0]'")or die('itemmaster err'.mysqli_error());
  $item_row=mysqli_fetch_array($rr);
//$item_row[1]
 print "<tr><td>$itemname[1]<br>Chasis:$item_row[0]</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=center><a href='$PHP_SELF?act=del&code=$row[0]'><img src='../img/delete2.gif' border=0></a></td>";
$tot+=$row[8];
}
print "<tr><td colspan=7 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>
