<?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['submit']))
 {
	$sql			= mysql_query(" SELECT max(`bill_no`) FROM `tbl_purchase` WHERE 1  ")or die(mysql_error());
	$data			= mysql_fetch_array($sql);
	if($data['max(`bill_no`)']!='NULL')
	{
		$bill_no	= $data['max(`bill_no`)']+1;
	}
	else
	{
		$bill_no	= 1;
	}
	$client_id      = ucwords(strtolower(mysql_real_escape_string($_POST['client_id'])));
	$serial_no		= mysql_real_escape_string($_POST['serial_no']);
	$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];
		mysql_query("insert into `tbl_purchase` set `bill_no`='$bill_no',`client_id`='$client_id',`date`='$date',`serial_no`='$serial_no',`images`='$images',`product_id`='$product_id',`product_rate`='$product_rate',`product_qty`='$product_qty',`product_total`='$product_total',`grand_total`='$grand_total' ")or die(mysql_error());
	}
	 $_SESSION['msg'] = 'Purchase Added Sucessfully!!';
	 header("location:home.php?page=purchase");	 
 }
 ?>           
<div class="row-fluid" >
    <div class="span12">
        <div class="head clearfix">
            <div class="isw-ok"></div>
            <h1><?php if(isset($_REQUEST['page_id'])) { echo "Modify";}else {echo "Add";}?> Purchase</h1>
        </div>
        <div class="block-fluid">
            <form class="form-horizontal" autocomplete='off' onsubmit="return get_validation();" action="" method="post" enctype="multipart/form-data">
              <fieldset>
                     <div class="row-form clearfix">
                     	<div class="span3">
                        	<label>Bill From</label>
                            <select name="client_id" required>
                            <option value="">Select One</option>
                            <?php
							$st		= array();
							$sql_st	= mysql_query("SELECT * FROM `tbl_clients` ORDER BY `name` ASC ")or die(mysql_error());
							while($row_st= mysql_fetch_array($sql_st))
							{
								$type = '';
								if(isset($_REQUEST['page_id'])&&($show_modify['state']==$row_st['id'])){ $type ='selected';}
								echo "<option value='".$row_st['id']."' $type>".$row_st['name']."</option>";
							}
							?>
                            </select>
                        </div>
                        <div class="span3">
                        	<label>Serial No</label>
                        	<input type="text" name="serial_no" placeholder="Serial No" <?php if(isset($_REQUEST['page_id'])){?>value="<?php echo $show_modify['serial_no'];  ?>"<?php } ?> id="serial_no" />
                        </div>
                        <div class="span3">
                        	<label>Supporting Documents</label>
                        	<input type="file" name="images[]"/>
                        </div>
                        <div class="span3">
                        	<label>Bill Date</label>
                            <input type="text" name="date" placeholder="Bill Date" <?php if(isset($_REQUEST['page_id'])){?>value="<?php echo $show_modify['date'];  ?>"<?php } ?> id="date" />
                        </div>
                     </div>
                     <div class="row-form clearfix">
                        <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['page_id'])&&($show_modify['state']==$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_1" onblur="amout_des('product_rate_1',this.value);" onkeyup="check_amt(1);" onclick="this.select();" value="0.00" />
                        </div>   
                        <div class="span2">
                        	<label>Qty</label>
                        	<input type="text" name="product_qty[]" id="product_qty_1" onblur="amout_des('product_qty_1',this.value);" onkeyup="check_amt(1);" onclick="this.select();" value="0"/>
                        </div>
                        <div class="span2">
                        	<label>Total</label>
                        	<input type="text" name="product_total[]" id="product_total_1" readonly="readonly" onclick="this.select();" value="0.00" />
                        </div>
                        <div class="span2">
                            <label>&nbsp;</label>
                            <input type="button" onclick="addMoreRows(this.form);" value="Add More" id="add_more1" />
                        </div>
                     </div>
                     <div id="addedRows"></div>
                <div class="row-form clearfix">
                	<div class="span2">
                        	<label>Grand Total</label>
                        	<input type="text" name="grand_total" id="grand_total" readonly="readonly" value="0.00" />
                        </div>
                    <div class="span2">
                    	<label>&nbsp;</label>
                        <input type="submit" name="<?php if(isset($_REQUEST['page_id'])){echo "update"; }else{ echo "submit";}?>" class="btn btn-block" value="<?php if(isset($_REQUEST['page_id'])){ 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 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="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    = parseInt($("#product_qty_"+id).val());	
	var val			   = product_rate*product_qty;
	$("#product_total_"+id).val(val);
	amout_des("product_total_"+id,val);
	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>   
<?php

	$menu		= mysql_query("SELECT distinct `bill_no` FROM `tbl_purchase` WHERE 1 order by `id` ASC")or die(mysql_error());
	$count		= mysql_num_rows($menu);
?>     
<div class="row-fluid" >
<div class="span12">    
<div class="head clearfix">
<div class="isw-ok"></div>
<h1>View Purchase List</h1>
</div>   
<div class="block-fluid">
<table cellpadding="0" cellspacing="0" width="100%" class="table" id="example">
    <thead>
        <tr>
            <th>S.No.</th>
            <th>Date</th>
            <th>Client Name</th>
            <th>Bill No</th>
            <th>Serial No</th>
            <th>Grand Total</th>
            <th>Modify</th>
        </tr>
    </thead>                 
    <tbody>
        <?php
        $i=1;
        while($show_menu = mysql_fetch_array($menu)) 
        {
			$sql		= mysql_query("SELECT * FROM `tbl_purchase` WHERE `bill_no`='".$show_menu['bill_no']."' ")or die(mysql_error());
			$data		= mysql_fetch_array($sql);
        ?>	
            <tr>
            <td style="text-align:center;"><?php echo $i++; ?></td>
            <td style="text-align:center;"><?php echo date("d-m-Y",strtotime($data['date'])); ?></td>
            <td><?php echo client($data['client_id']); ?></td>
            <td style="text-align:center;"><?php echo $data['bill_no']; ?></td>
            <td style="text-align:center;"><?php echo $data['serial_no']; ?></td>
            <td style="text-align:right;"><?php echo $data['grand_total']; ?></td>
            <td class="center" style="text-align:center">
                <a href="home.php?page=purchase_modify&bill_no=<?php echo $data['bill_no'];?>"><img src="images/edit_new.png"  border="0" style="width: 20px;"/></a>
            </td>
        </tr>
       <?php } ?>                
    </tbody>            
</table> 
</div>    
</div>
</div>            
<script>
$(document).ready(function() {
var table = $('#example').DataTable( {
"order": [[ 2, "asc" ]],
"pageLength": 50,stateSave: true,
fixedHeader: {
header: true,
footer: true
}
} );
table.on( 'order.dt search.dt', function () {
table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw(); } );
</script>