<?php if(isset($_SESSION['msg']) ){?>
<div class="alert alert-info">                
<h4>Info!</h4>
<?php echo $_SESSION['msg']; unset($_SESSION['msg']); ?>
</div> <?php }  ?> 
<?php
 if(isset($_REQUEST['update']))
 {
	 
	$month			= date("m");
	$year			= date("Y");
	$invoice_prefix	= "RHLLP/2018-2019/";
	$invoice_no		= $_POST['bill_no'];
	//delete old Entries
	$sql			= mysql_query(" DELETE FROM `tbl_sale` WHERE `bill_no`='$invoice_no'  ")or die(mysql_error());
	
	$images	        = "";
	$grand_total	= $_POST['grand_total'];
	$date			= date("Y-m-d",strtotime($_POST['date']));
	for($i=0;$i<count($_POST['product_id']);$i++)
	{
		$product_id             = $_POST['product_id'][$i]; 	
		$product_rate           = $_POST['product_rate'][$i];
		$product_qty            = $_POST['product_qty'][$i];
		$product_total         	= $_POST['product_total'][$i];
		$gst_rate				= $_POST['gst_rate'][$i];
		mysql_query("insert into `tbl_sale` set `bill_no`='$invoice_no',`date`='$date',`images`='$images',`product_id`='$product_id',`product_rate`='$product_rate',`product_qty`='$product_qty',`gst_rate`='$gst_rate',`product_total`='$product_total',`grand_total`='$grand_total' ")or die(mysql_error());
	}
	 mysql_query(" update `tbl_invoice` SET `invoice_no`='$invoice_no',`invoice_prefix`='$invoice_prefix',`month`='$month',`year`='$year',`amt`='$grand_total',`date`='$date',`bill_mode`='SALE' where `invoice_no`='$invoice_no' and `invoice_prefix`='$invoice_prefix' ")or die(mysql_error());
	 $_SESSION['msg'] = 'Sale Bill Added Sucessfully!!'.'<a target="_blank" href="pages/invoice/sale_invoice.php?invoice_no='.$invoice_no.'&invoice_prefix='.$invoice_prefix.'">Print Invoice</a>';
	 header("location:home.php?page=sale_invoice");	 
 
 }
 ?>           
<div class="row-fluid" >
    <div class="span12">
        <div class="head clearfix">
            <div class="isw-ok"></div>
            <h1><?php if(isset($_REQUEST['bill_no'])) { echo "Modify";}else {echo "Add";}?> Sale Invoice</h1>
        </div>
        <div class="block-fluid">
            <form class="form-horizontal" autocomplete='off' onsubmit="return get_validation();" action="" method="post" enctype="multipart/form-data">
              <fieldset>
              <?php
			   if(isset($_REQUEST['bill_no']))
			   {
				   $bill_no       =  $_REQUEST['bill_no'];
				   $modify_menu   =  mysql_query("SELECT * FROM `tbl_sale` WHERE `bill_no` = '$bill_no' ");
				   $show_modify   =  mysql_fetch_array($modify_menu);
			   }
			  ?>
              <input type="hidden" name="bill_no" placeholder="Page Name" <?php if(isset($_REQUEST['bill_no'])){?> required value="<?php echo $show_modify['bill_no'];  ?>"<?php } ?> id="txt_name" autocomplete="off" />
                     <div class="row-form clearfix">
                        <div class="span3">
                        	<label>Bill Date</label>
                            <input type="text" name="date" placeholder="Bill Date" <?php if(isset($_REQUEST['bill_no'])){?>value="<?php echo date('d-m-Y',strtotime($show_modify['date']));?>"<?php } ?> id="date" />
                        </div>
                     </div>
                     <?php 
					 $menu 		     =  mysql_query("SELECT * FROM `tbl_sale` WHERE `bill_no` = '$bill_no' order by `id` ASC ");
					 $i				 = 0;
				   	 while($modify   =  mysql_fetch_array($menu))
					 {?>				   
                     <div class="row-form clearfix" id="rowCount<?php echo $i;?>">
                        <div class="span4">
                        	<label>Product Name</label>
                            <select name="product_id[]" required>
                            <option value="">Select Product</option>
                            <?php
							$st		= array();
							$sql_st	= mysql_query("SELECT * FROM `tbl_product` ORDER BY `name` ASC ")or die(mysql_error());
							while($row_st= mysql_fetch_array($sql_st))
							{
								$type = '';
								if(isset($_REQUEST['bill_no'])&&($modify['product_id']==$row_st['id'])){ $type ='selected';}
								echo "<option value='".$row_st['id']."' $type>".$row_st['name']."</option>";
							}
							?>
                            </select>
                        </div>
                        <div class="span2">
                        	<label>Rate</label>
                        	<input type="text" name="product_rate[]" id="product_rate_<?php echo $i;?>" onblur="amout_des('product_rate_<?php echo $i;?>',this.value);" <?php if(isset($_REQUEST['bill_no'])){?>value="<?php echo $modify['product_rate'];  ?>"<?php } ?> onkeyup="check_amt(<?php echo $i;?>);" onclick="this.select();" />
                        </div>   
                        <div class="span2">
                        	<label>Qty</label>
                        	<input type="text" name="product_qty[]" id="product_qty_<?php echo $i;?>" onblur="amout_des('product_qty_<?php echo $i;?>',this.value);" <?php if(isset($_REQUEST['bill_no'])){?>value="<?php echo $modify['product_qty'];  ?>"<?php } ?> onkeyup="check_amt(<?php echo $i;?>);" onclick="this.select();"/>
                        </div>
                        <div class="span1">
                        	<label>GST Rate</label>
                        	<input type="text" name="gst_rate[]" id="gst_rate_<?php echo $i;?>" onblur="amout_des('gst_rate_<?php echo $i;?>',this.value);" <?php if(isset($_REQUEST['bill_no'])){?>value="<?php echo $modify['gst_rate'];  ?>"<?php } ?> onkeyup="check_amt(<?php echo $i;?>);" onclick="this.select();"/>
                        </div>
                        <div class="span2">
                        	<label>Total</label>
                        	<input type="text" name="product_total[]" <?php if(isset($_REQUEST['bill_no'])){?>value="<?php echo $modify['product_total'];  ?>"<?php } ?> id="product_total_<?php echo $i;?>" readonly="readonly" onclick="this.select();" />
                        </div>
                        <div class="span1">
                        	<label>&nbsp;</label>
                            <a style="color:#fff;background:#00C;" href="javascript:void(0);" onclick="removeRow(<?php echo $i;?>);" class="new">Delete</a>
                       </div>
                     </div>
                     <?php $i++;} ?>
                   <div id="addedRows"></div>
                   <div class="row-form clearfix" style=" background:#C99">
                        <div class="span2">
                            <label>&nbsp;</label>
                            <input type="button" onclick="addMoreRows(this.form);" value="Add More Products" id="add_more1" />
                        </div>
                     </div>
                   <div class="row-form clearfix">
                	<div class="span2">
                        	<label>Grand Total</label>
                        	<input type="text" name="grand_total" <?php if(isset($_REQUEST['bill_no'])){?>value="<?php echo $show_modify['grand_total'];  ?>"<?php } ?> id="grand_total" readonly="readonly" value="0.00" />
                        </div>
                    <div class="span2">
                    	<label>&nbsp;</label>
                        <input type="submit" name="<?php if(isset($_REQUEST['bill_no'])){echo "update"; }else{ echo "submit";}?>" class="btn btn-block" value="<?php if(isset($_REQUEST['bill_no'])){ echo "Update"; }else{ echo "Save";}?>"/></div>
                </div>
              </fieldset>
            </form>  
        </div> 
    </div>
</div> 
<script>
var rowCount=100;
function addMoreRows() 
{
	rowCount ++;
	var product_rate = "'product_rate_"+rowCount+"'";
	var product_qty  = "'product_qty_"+rowCount+"'";
	var gst_rate	 = "'gst_rate_"+rowCount+"'";
	var recRow = '<div class="row-form clearfix" id="rowCount'+rowCount+'"><div class="span4"><label>Product Name</label><select name="product_id[]" required><option value="">Select Product</option><?php $st = array(); $sql_st	= mysql_query("SELECT * FROM `tbl_product` ORDER BY `name` ASC ")or die(mysql_error()); while($row_st= mysql_fetch_array($sql_st)) {  echo "<option value=".$row_st['id'].">".$row_st['name']."</option>"; } ?></select></div><div class="span2"><label>Rate</label><input type="text" name="product_rate[]" id="product_rate_'+rowCount+'" onblur="amout_des('+product_rate+',this.value);" onkeyup="check_amt('+rowCount+');" onclick="this.select();" value="0.00" /></div><div class="span2"><label>Qty</label><input type="text" name="product_qty[]" id="product_qty_'+rowCount+'" onblur="amout_des('+product_qty+',this.value);" onkeyup="check_amt('+rowCount+');" onclick="this.select();" value="0"/></div><div class="span1"><label>GST Rate</label><input type="text" name="gst_rate[]" id="gst_rate_'+rowCount+'" onblur="amout_des('+gst_rate+',this.value);" onkeyup="check_amt('+rowCount+');" onclick="this.select();" value="0.00" /></div><div class="span2"><label>Total</label><input type="text" name="product_total[]" id="product_total_'+rowCount+'" readonly="readonly" onclick="this.select();" value="0.00" /></div><div class="span1"><label>&nbsp;</label><a style="color:#fff;background:#00C;" href="javascript:void(0);" onclick="removeRow('+rowCount+');" class="new">Delete</a></div></div>';
	jQuery('#addedRows').append(recRow);
	}
	function removeRow(removeNum) {
	jQuery('#rowCount'+removeNum).remove();
}

function grand_total_amt()
{
	var total_amt = 0; 
    var lols         = document.getElementsByName("product_total[]");
	for (var i=0, n=lols.length;i<n;i++)
	{
		var type1    = document.getElementsByName("product_total[]");
		total_amt    = (parseFloat(total_amt) + parseFloat((type1[i].value))).toFixed(2);
	}
	$("#grand_total").val(total_amt);
}
function check_amt(id)
{
	var product_rate   = parseFloat($("#product_rate_"+id).val());	
	var product_qty    = parseFloat($("#product_qty_"+id).val());	
	var product_gst    = parseInt($("#gst_rate_"+id).val());	
	var val			   = product_rate*product_qty;
	
	var gst_amt		   = (val*product_gst)/100;
	var val_1		   = val+gst_amt;
	$("#product_total_"+id).val(val_1);
	amout_des("product_total_"+id,val_1);
	grand_total_amt();	
}
function amout_des(id,val)
{
	var num = parseFloat(val);
	if(!isNaN(num))
	{
		var n = num.toFixed(2)
		document.getElementById(id).value = n;
	}
	else
	{
		document.getElementById(id).value = '0.00';
	}
}
function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
function capital_letter(id)
{
    var arr 		  = $('#'+id).val().split(' ');
    var result 		  = "";
    for (var x=0; x<arr.length; x++)
        result+=arr[x].substring(0,1).toUpperCase()+arr[x].substring(1)+' ';
    $('#'+id).val(result.substring(0, result.length-1));
}
</script>