<?php 
session_start();
ob_start(); 
include "header.php";
//$objIms->Semifinisheditem_alter();
?>


<link href="../css/select2.css" rel="stylesheet" />

<?php

if(isset($_POST["del"]))
{
	$tem_id=$_POST["del"];
	
	$del="delete from tmp_sales_detail where id=$tem_id and session_login_id = '".$_SESSION['login_id']."'";
	mysql_query($del);

}



if(isset($_POST["additems"]))
{
	$item_id=$_POST["item_id"];
	
	$result=$_REQUEST["item_nm"];
    $result_explode = explode('|', $result);
    $item_nm = $result_explode[0];
	$qty=$_POST["qty"];
	$unit_name=$_POST["unit"];
	$unit_id=$_POST["unit_id"];
	$unit_price=$_POST["unit_price"];
	$price=$_POST["price"];
	$discount=$_POST["discount"];
	$cgst=$_POST["cgst"];
	$sgst=$_POST["sgst"];
	$igst=$_POST["igst"];
	
	if(($item_id>0) and ($qty>0) and ($price>0) and ($unit_id>0))
	{
	$sqlchk="select * from tmp_sales_detail where session_login_id = '".$_SESSION['login_id']."' and item_id='$item_id' and unit_id='$unit_id' and pur_price='$unit_price' and unit_price='$price'";
	$exechk=mysql_query($sqlchk);
	if(mysql_num_rows($exechk)==0){
							 $sql2="insert into tmp_sales_detail(item_id,item_name,qty,unit_price,unit_id,unit_name,pur_price,discount,cgst,sgst,igst,session_login_id) values('$item_id','$item_nm','$qty','$price','$unit_id','$unit_name','$unit_price','$discount','$cgst','$sgst','$igst', '".$_SESSION['login_id']."')";
				  			$final2=mysql_query($sql2);					
						
	 	}
		else
		{
		$msg='<span style="color:#FF0000">Item Already Exists...</span>';
		}
	
		
	}
}

if(isset($_POST["Save"]))
{
	$paid_amt=$_POST["paid_amt"];
	$o_date = date('d-m-Y', strtotime($_POST["order_date"]));	
	$order_date=$objIms->DateToInt($o_date);
	$stampdate=$objIms->DateToInt(date('d-m-Y'));	
	$client_id=$_POST["client_name"];
	$sales_type=$_POST["invoice_type"];
	$discount=$_POST["totdiscount"];
	$result=$_POST["grand_total"];
	$round_off=$_POST["round_off"];	
	$payment_mode=$_POST["r3"];
	$bank_id=$_POST["bank"];
	$invoice_no=$objIms->trasaction_no();
	 $sql_1="select * from tmp_sales_detail where session_login_id = '".$_SESSION['login_id']."'";
	$res_1=mysql_query($sql_1);
	if((mysql_num_rows($res_1)>0))
	{
	
			if(($paid_amt<=$round_off) and ($paid_amt<>""))
			{
				 $sql_insmas="insert into tbl_sales(client_id,sales_type,stampdate,session_login_id) values('$client_id','$sales_type','$order_date', '".$_SESSION['login_id']."')";
				
				$res_insmas=mysql_query($sql_insmas);
				$lastid=mysql_insert_id();
				
				$Sale_no='SELL/'.date('M').'/'.date('Y').'/'.$lastid;
				$sql_upmas="Update tbl_sales set sale_no='$Sale_no' where id='$lastid' and session_login_id = '".$_SESSION['login_id']."'";
				$res_upmas=mysql_query($sql_upmas);

				if($payment_mode=='Cheque')
					{

					$cheque_date = $_POST['cheque_date'];
					$cheque_date = date('Y-m-d', strtotime($cheque_date));
					$sql_acc="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Cr_Amt,sales_type,cash_type,clear,discount, grand_tot , payment_mode , bank_id, session_login_id) values('$invoice_no','$lastid','$stampdate','$round_off','$paid_amt','Sales','Debit',1,'$discount','$result' ,'$payment_mode','$bank_id', '".$_SESSION['login_id']."')";
				
				   $res_acc=mysql_query($sql_acc);
				   	$accid=mysql_insert_id();
					$sql_ck_dtl="INSERT INTO `tbl_cheque_detail` (`account_id`, `bank_name`, `branch_name`, `checque_no`, `checque_date` , `session_login_id`) VALUES ('$accid', '".$_POST['bank_name']."', '".$_POST['branch_name']."', '".$_POST['cheque_no']."', '".$cheque_date."' , '".$_SESSION['login_id']."');";
					 $res_ck_dtl=mysql_query($sql_ck_dtl);

					$sql_cheq = "insert into tbl_bank(head, bankdet_id, debit, sale_mas_id, stampdate, session_login_id) values ('sale_payment', '$bank_id', '$paid_amt', '$lastid','$stampdate', '".$_SESSION['login_id']."' )";
					$res_cheq = mysql_query($sql_cheq);

					// $sql_client = "insert into client_details(client_id, cr_amount, sell_mstr_id, stampdate) values ('$client_id', '$paid_amt', '$lastid', '$stampdate' )";
					// $res_client = mysql_query($sql_client);
				
				    $res_acc=mysql_query($sql_acc);

				    
					}
					elseif ($payment_mode=='Cash') {

				$sql_ins="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Cr_Amt,sales_type,cash_type,clear,discount, grand_tot , payment_mode , bank_id, session_login_id) values('$invoice_no','$lastid','$stampdate','$round_off','$paid_amt','Sales','Debit',1,'$discount','$result' ,'$payment_mode','$bank_id', '".$_SESSION['login_id']."')";
				
				$res_ins=mysql_query($sql_ins);

		    	/*$sql_cash = "insert into cash_detail (sales_mas_id, sales_type, dr_amount, stampdate) values('$lastid','sale', '$paid_amt','$stampdate')";
				$res_cash=mysql_query($sql_cash);*/

				$accid=mysql_insert_id();
					}
		//  here in this section due option field should insert and journal entries of them//			
					else
					{
				$sql_due = "insert into client_details(client_id, dr_amount, sell_mstr_id, stampdate, session_login_id) values('$client_id', '$round_off', '$lastid', '$stampdate', '".$_SESSION['login_id']."')";
				$res_due=mysql_query($sql_due);

				$sql_ins1="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Cr_Amt,sales_type,cash_type,clear,discount, grand_tot , payment_mode , bank_id, session_login_id) values('$invoice_no','$lastid','$stampdate','$round_off','$round_off','Sales_Due','Debit',0,'$discount','$result' ,'$payment_mode','$bank_id', '".$_SESSION['login_id']."')";
				
				$res_ins1=mysql_query($sql_ins1);	

					}
					$sql_cash = "insert into cash_detail (sales_mas_id, sales_type, dr_amount, stampdate, session_login_id) values('$lastid','sale', '$round_off','$stampdate', '".$_SESSION['login_id']."')";
				$res_cash=mysql_query($sql_cash);
				
					while($result=mysql_fetch_array($res_1))
					{
					$item_id=$result["item_id"];
					$qty=$result["qty"];
					$unit_price=$result["unit_price"];
					$pur_price=$result["pur_price"];
					$unit_id=$result["unit_id"];
					$tmpdiscount=$result["discount"];
					$cgst=$result["cgst"];
					$sgst=$result["sgst"];
					$igst=$result["igst"];
					$sql4="insert into tbl_sales_detail(salesmas_id,item_id,qty,unit_price,unit_id,discount,cgst,sgst,igst,session_login_id)values('$lastid','$item_id','$qty','$unit_price','$unit_id','$tmpdiscount','$cgst','$sgst','$igst', '".$_SESSION['login_id']."')";
					//echo $sql4;
					$rs1=mysql_query($sql4);
					
					 $sel="select * from tbl_stock where session_login_id = '".$_SESSION['login_id']."' and item_id='$item_id' and unit_id='$unit_id' and unit_price='$pur_price' and sell_price='$unit_price'";
					$query=mysql_query($sel);
					if(mysql_num_rows($query)>0)
					{
					$rsq=mysql_fetch_array($query);
					$tot_qty=$rsq["tot_qty"]-$qty;
					$update="update tbl_stock set tot_qty='$tot_qty' where session_login_id = '".$_SESSION['login_id']."' and item_id='$item_id' and unit_id='$unit_id' and unit_price='$pur_price' and sell_price='$unit_price'";
					mysql_query($update);
					}
					
					}
					$sql="delete from tmp_sales_detail where session_login_id = '".$_SESSION['login_id']."'";
				$rest=mysql_query($sql);
				
							
				
				header("location:sales_reciept.php?uid=".md5($lastid));
					
			}
	}
	
}

?>

	 <?php 
//Generate order no..............................................
		/*function getTotalEmployees() {
		$query = "SELECT max(id) as numss FROM tbl_pur_order_master";
		 $totalrecord = mysql_fetch_array(mysql_query($query));
		$num = $totalrecord[numss]; 
		//	echo $totalrecord;		 
		++$num; // add 1;
		$len = strlen($num);
		for($i=$len; $i< 6; ++$i) {
		$num = '0'.$num;
		}
		return $num;
		}		

$mm=$db->findmm($date=date('d-m-Y'));
$yy=$db->findyy($date=date('d-m-Y'));

//$uresult=strtoupper($result) ;
$number = getTotalEmployees();
$order_no = 'P0/USC/'.$number.'/'.$mm.'-'.$yy;*/
//echo $order_no;			
//end...............................................................	
?>



		
	<script type="text/javascript">
	$(document).ready(function() {                
	$("#form1").validate({
	rules: {
	delv_location: "required",
	
	sales_type: "required",
	
	},
	messages: {
	delv_location:"",
	
	sales_type:"",
	
	},
	});                
	});
	</script>
		 <style>
			select.error { background-color:#ffa8a8; border: 1px dotted red;  }
			input.error{ background-color:#ffa8a8;   }
			textarea.error{ background-color:#ffa8a8; border: 1px dotted red;  }
			
			/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
   
    z-index: 9; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 250;
    top: 0;
    width: 80%; /* Full width */
    
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
         </style>
		 
        <script type="text/javascript"> 
 		/*jQuery(document).ready(function(){
			$('#item_nm').autocomplete({source:'../ProgramFile/auto/suggest_stock.php', minLength:1,
			select: function (event, ui) {
        	$("#item_id").val(ui.item.id); // display the selected id
       		$("#item_nm").val(ui.item.value); // display the selected text.
			$("#unit").val(ui.item.unit_name);
			$("#price").val(ui.item.sell_price);
			$("#unit_id").val(ui.item.unit_id);
			$("#av_qty").val(ui.item.tot_qty);
			$("#unit_price").val(ui.item.unit_price);
			$("#cgst").val(ui.item.cgst);
			$("#sgst").val(ui.item.sgst);
			$("#igst").val(ui.item.igst);
		    }
			});

}); */
</script>

<script type="application/javascript">
	  function isNumber(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}
	
	function chkamt(str)
	{
	 str=eval(str);
	var av=eval(document.getElementById("round_off").value);
	//alert(str+" "+av);
	if(av<str)
	{
	alert("Paid Amount Should Not Be Greater Than Round Off Amount");
	document.getElementById("paid_amt").value='';
	
	}
	}
	
	function maxqty(str)
	{ str=eval(str);
	var av=eval(document.getElementById("av_qty").value);
	//alert(str+" "+av);
	if(av<str)
	{
	alert("Sell Qty Should Not Be Greater Than Available Qty");
	document.getElementById("qty").value='';
	
	}
	}
	
	
	function discountc(str)
		{ 
		var totalamt=document.getElementById("totamt").value;
		var totalnet=document.getElementById("grand_total").value;
		var ctr=document.getElementById("count").value;
		
		if(str=="")
			{
				str=0;
			}else{ str=str;}
		//var totaltax=document.getElementById("tax_percent"+Ival).value;
		var perc=eval(totalamt)*eval(str)/100;
		var nettotal=eval(totalamt)-eval(perc);
		//var tax=eval(nettotal)*eval(totaltax)/100;
		
		document.getElementById("discount_amt").value=perc.toFixed(2);
		
		
		var taxpercentab;
		var tax;
		var checkboxtax;
		 
		for(var st=1;st<ctr;st++)
			{
			 taxpercentab=document.getElementById("tax_percent"+st).value;
			
			 tax=eval(nettotal)*eval(taxpercentab)/100;
			 
			document.getElementById("taxamount"+st).value=tax.toFixed(2); 
			checkboxtax=document.getElementById("checkboxtax"+st).checked;
			if(checkboxtax==true)
				{
				nettotal=nettotal+tax;
				}
			}
		
		document.getElementById("grand_total").value=nettotal.toFixed(2);
		document.getElementById("round_off").value=Math.round(nettotal);
		//document.getElementById("taxamount"+Ival).value=tax.toFixed(2);
		}
		
		function check(str) {
		//
		var terms = document.getElementById("checkboxtax"+str);
		var totalamt=document.getElementById("grand_total").value;
		var sum_amt=document.getElementById("totamt").value;		
		var tax_percent=document.getElementById("tax_percent"+str).value;
		
		
		var totaltax=eval(sum_amt)*(eval(tax_percent)/100);
		
		document.getElementById("taxamount"+str).value=totaltax.toFixed(2);
        if(terms.checked == true){
		//alert(totamt);
			var total_tax=eval(sum_amt)+eval(totaltax);				
		}
		else{
			var total_tax=eval(sum_amt)-eval(totaltax);			
			}	
			document.getElementById("grand_total").value=total_tax.toFixed(2);
			document.getElementById("round_off").value=Math.round(total_tax);
		
        }
		
		/*function readone(str)
		{
		if(str=='Retail Invoice')
		{
		var ctr=document.getElementById("count").value;
		for(var st=1;st<ctr;st++)
			{
			
			
			document.getElementById("checkboxtax"+st).disabled=true;
			}
		}	
			
		}*/
	</script>
<script type="text/javascript" language="javascript">

var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
document.getElementById("tax_name")=strUser;
</script>	
<style type="text/css">
<!--
.table_bg{ border:#CCCCCC solid 1px; border-radius:5px; height:auto; width:auto; padding:20px; margin-bottom:10px;}


-->
 
</style>
<!-- Page wrapper  -->
        <div class="page-wrapper">
            
            <!-- Container fluid  -->
            <div class="container-fluid">
                <!-- Start Page Content -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
							<h3>Sale <span style="float:right"><button onclick="goBack()" class="btn btn-info btn-sm">Go Back</button><script>
function goBack() {
    window.history.back();
}
</script></span></h3><hr />
<form id="form1" name="form1" method="post" action="">
<table width="100%" cellpadding="4" >
  <tr>
    <td width="7%" height="38" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>Client</strong></td>
    <td width="1%" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td width="28%" nowrap="nowrap" bgcolor="#FFFFFF" id="cnm" ><select name="client_name" id="client_name" class="form-control" onchange="sup_state()" style="width:200px;" >
      <option value="">---Please Select---</option>
      <?php 
							$sqlc="select * from tbl_client where session_login_id = '".$_SESSION['login_id']."'";
							//echo $sqlc;
							$c=mysql_query($sqlc);
							if(mysql_num_rows($c)>0){
							while($cs=mysql_fetch_array($c))
							{?>
      <option value="<?=$cs["id"];?>" <?php if(($cs["id"])==$_POST["client_name"]){ ?> selected="selected" <?php }?>>
      <?=$cs["client_name"];?> |  <?=$cs["contact_no"];?>
      </option>
      <?php }}?>
    </select>
	<input type="hidden" name="state_code" id="state_code" value="<?php echo $_SESSION['state_code'];?>" readonly="" style="width:150px" />
	<input type="hidden" name="c_state_code" id="c_state_code" value="<?php if(isset($_POST['c_state_code'])) { echo  $_POST['c_state_code']; }?>" readonly="" style="width:150px" />
	<button type="button" id="myBtn" class="btn btn-sm btn-info">add client</button></td>
    <td height="38" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>Invoice Date </strong></td>
    <!-- <td nowrap="nowrap" bgcolor="#FFFFFF" ><strong>:</strong></td> -->
    <td nowrap="nowrap" bgcolor="#FFFFFF" ><?php if(($_POST["order_date"])=="") { $dt=date("d-m-Y");} else { $dt=$_POST["order_date"];}?>
        <input name="order_date" type="date" id="order_date"   style="width:185px; background-color:#FFF;"  value="<?=$dt?>" class="tcal form-control" /><input type="hidden" name="invoice_type" value="Tax Invoice"></td>

    </tr>
</table>
<br />
<div class="panel">
<div class="panel-heading"><strong>Add Item </strong></div>
            <p>&nbsp;</p>
			
			 <table width="100%" class="table table-bodered tbrd">
            <tr height="32" align="left">
            <td width="6%" nowrap="nowrap">Item Name</td>
            
            <td width="22%" nowrap="nowrap"><select name="item_nm" id="item_nm" onchange="fun()" class="form-control">
			<option value="">item / pur price / sell price </option>
			 
			<?php 
							$sqlitm="select * from tbl_purchase_details where session_login_id = '".$_SESSION['login_id']."'";
							//echo $sqlc;
							$citm=mysql_query($sqlitm);
							if(mysql_num_rows($citm)>0){
							while($row_itm=mysql_fetch_array($citm))
							{
							$sqlitm2="select * from tbl_item where id = '".$row_itm["item_id"]."' and session_login_id = '".$_SESSION['login_id']."'";
							//echo $sqlc;
							$citm2=mysql_query($sqlitm2);
							$row_itm2=mysql_fetch_array($citm2);
							?>
        <option value="<?=$row_itm2["item_name"];?>|<?=$row_itm["pur_price"];?>|<?=$row_itm["sell_price"];?>">
     <p> <?=$row_itm2["item_name"];?> / <?=$row_itm["pur_price"];?> / <?=$row_itm["sell_price"];?></p>
        </option>
        <?php }}?>
	
		</select>
              <input type="hidden" name="item_id" id="item_id" style="width:350px" /></td>
            <td width="2%" nowrap="nowrap">Unit</td>
           
            <td width="11%" nowrap="nowrap"><input name="unit" id="unit" style="width:75px;" readonly="" />
              <input type="hidden" name="unit_id" id="unit_id" style="width:200px;">             </td>
			<td width="5%" nowrap="nowrap">Unit Price</td>
           
            <td width="11%" nowrap="nowrap"><input type="hidden" name="unit_price" id="unit_price"  /><input type="text" name="price" id="price" readonly="" style="width:75px"  /></td>
			<td width="5%" nowrap="nowrap">Avail Qty </td>
			
            
            <td width="8%" nowrap="nowrap"><input type="text" name="av_qty" id="av_qty" style="width:75px" readonly="" /></td>
            <td width="3%" nowrap="nowrap">Qty</td>
           
            <td width="9%" nowrap="nowrap"><input type="text" name="qty" id="qty" style="width:75px" onblur="maxqty(this.value)" onkeypress="return isNumber(event)"/></td>
            </tr>
            <tr height="32" align="left">
              <td >Discount(in %)</td>
             
              <td ><input type="text" name="discount" id="discount" onkeypress="return isNumberDis(event,this);" style="width:75px" /></td>
              <td >CGST(in %)</td>
              
              <td ><input type="text" name="cgst" id="cgst" onkeypress="return isNumberKey(event)" style="width:75px" readonly="" /></td>
              <td >SGST(in %)</td>
              
              <td ><input type="text" name="sgst" id="sgst" onkeypress="return isNumberKey(event)" style="width:75px" readonly=""  /></td>
              <td >IGST(in %)</td>
              
              <td ><input type="text" name="igst" id="igst" onkeypress="return isNumberKey(event)" style="width:75px" readonly=""  /></td>
             
              <td nowrap="nowrap" colspan="2"><input type="submit" name="additems" id="additems" value="Add Items" class="btn btn-success" style="margin-top::0px" /></td>
              </tr>
           </table>
			
</div>
<script type="text/javascript">
   function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
} 
	function isNumberDis(evt, element) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if (charCode > 31 && (charCode < 48 || charCode > 57) && !(charCode == 46 || charCode == 8))
    return false;
  else {
    var len = $(element).val().length;
    var index = $(element).val().indexOf('.');
    if (index > 0 && charCode == 46) {
      return false;
    }
    if (index > 0) {
      var CharAfterdot = (len + 1) - index;
      if (CharAfterdot > 3) {
        return false;
      }
    }

  }
  return true;
}
</script>

     <div class="panel">
            <div class="panel-heading"><strong>Item List of Purchase <?=@$msg?></strong></div>
            <p>&nbsp;</p>
			  <?php 
				 $sql_viewtmp="select *  from tmp_sales_detail where session_login_id = '".$_SESSION['login_id']."'";
				$res_viewtmp=mysql_query($sql_viewtmp);
				if(mysql_num_rows($res_viewtmp)>0)
				{ 
					$i=1;
					$sums=0;
					$totdis=0;
					?>
            <table width="100%" class="table table-striped">
		
          
                     
                     <tr height="32" align="left">
            <th nowrap="nowrap" width="7%">Si No</th>
            <th nowrap="nowrap" >Item Name</th>
           
            <th nowrap="nowrap" width="20%">Unit Name </th>
            <th nowrap="nowrap" width="20%">Order Qty</th>
            <th nowrap="nowrap" width="20%">Price(Per)</th>
            <th nowrap="nowrap" width="20%">Total</th>
            <th nowrap="nowrap" width="20%">Discount</th>
            <th width="20%" nowrap="nowrap">CGST(%)</th>
           
            <th width="20%" nowrap="nowrap">SGST(%)</th>
            
            <th width="20%" nowrap="nowrap">IGST(%)</th>
          
            <th nowrap="nowrap" width="20%">Total Price</th>
            <th nowrap="nowrap" width="20%">Delete</th>
              </tr>
            <?php
				while($rows=mysql_fetch_assoc($res_viewtmp))
					{
						
						
						
						
							
							
			?>
           
            <tr height="32">
            <td nowrap="nowrap" width="7%"><?php echo $i;?></td>
           
		    <td nowrap="nowrap" ><?php echo $rows["item_name"];?></td>
            
            <td nowrap="nowrap" width="20%"><?php echo $rows["unit_name"];?></td>
            <td nowrap="nowrap" width="20%"><?php echo $rows["qty"];?></td>
            <td nowrap="nowrap" width="20%"><?php echo $rows["unit_price"];?></td>
            <td nowrap="nowrap" width="20%"><?php  $totsum=($rows["qty"]*$rows["unit_price"]); echo number_format($totsum,2);?></td>
            <td nowrap="nowrap" width="20%"><?php  $discount=$totsum*($rows["discount"]/100); echo number_format($discount,2); $totprice=($totsum-$discount);?></td>
            <td width="20%" nowrap="nowrap"><?php echo $rows["cgst"];?>
           <?php  $cgst=$totprice*($rows["cgst"]/100);  number_format($cgst,2);?></td>
            <td width="20%" nowrap="nowrap"><?php echo $rows["sgst"];?><?php  $sgst=$totprice*($rows["sgst"]/100);  number_format($sgst,2);?></td>
            <td width="20%" nowrap="nowrap"><?php echo $rows["igst"];?><?php  $igst=$totprice*($rows["igst"]/100);  number_format($igst,2);?></td>
            <td nowrap="nowrap" width="20%"><?php  $totamt=$totprice+$cgst+$sgst+$igst; echo number_format($totamt,2);?></td>
            <td nowrap="nowrap" width="20%"><button type="submit" name="del" class="btn btn-danger" value="<?=$rows["id"]?>">Delete</button></td>
            </tr>  <?php $sums=$sums+($totamt);$i++;
			$totdis=$totdis+$discount;
			} ?>   
            <tr height="32">
              <td nowrap="nowrap">&nbsp;</td>
              <td colspan="9" nowrap="nowrap"><div align="right"><strong>Total : </strong></div></td>
              <td nowrap="nowrap"><?php echo number_format($sums,2);?>
                <input type="hidden" name="totamt" id="totamt" value="<?php echo $sums;?>" /><input type="hidden" name="totdiscount" id="totdiscount" value="<?php echo $totdis;?>" /></td>
              <td nowrap="nowrap">&nbsp;</td>
            </tr>           
           </table>
		    <table width="100%" class="table table-bordered">
          <tr>
            <td width="85%"><div align="right"><strong>Grand Total</strong></div></td>
            <td width="15%"><input type="text" name="grand_total" id="grand_total" style="width:100px; border:none; background:#FFFFFF;" readonly value="<?php echo $sums;?>"/></td>
          </tr>
		  
          <tr>
            <td><div align="right"><strong>Round Off</strong></div></td>
            <td> <input type="text" name="round_off" id="round_off" style="width:100px; border:none; background:#FFFFFF;" readonly value="<?php echo round($sums);?>"/></td>
          </tr>
		   <tr><td colspan="" align="right">Add To Bank</td>
			<td colspan=""><select name="bank" id="bank"  onchange="fetch()" style="width:100px"  class="required" required>
     
      <?php 
							$sqlc="select * from tbl_bank_detail where session_login_id = '".$_SESSION['login_id']."'";
							//echo $sqlc;
							$c=mysql_query($sqlc);
							if(mysql_num_rows($c)>0){
							while($cs=mysql_fetch_array($c))
							{?>
      <option value="<?=$cs["id"];?>" >
      <?=$cs["bank_name"];?> (AC/NO:  <?=$cs["acc_no"];?>)
      </option>
      <?php }}?>
    </select></td>
			</tr>
          <tr>
            <td><div align="right"><strong>Paid Amount :</strong></div></td>
            <td><input type="text" name="paid_amt" id="paid_amt" onblur="chkamt(this.value)" required style="width:100px;"   /></td>
          </tr>
		   
        </table>
		<?php }?>
    </div>
	
	<tr><td colspan="2"><b>PAYMENT MODE</b></td></tr>
		  <tr><td colspan="2">
               
                  <input type="radio" id="r3" name="r3" value="Cash"  class="flat-red" checked>
				  Cash
               
               
                  <input type="radio" id="r3" name="r3" style="margin-left:20px"  value="Due" class="flat-red">
                  Due

                  <input type="radio" id="r3" name="r3" style="margin-left:20px"  value="Cheque" class="flat-red">
                  Cheque
               
        	
		
	</td></tr>
	
	
	<hr style="border:6px solid #CCCC00;display:none;" id="cheq_hide_header" />
<div id="cheq_hide" style="display:none; margin:1px;">
 	<table width="100%" class="table table-bordered">
	<tr><td>Bank Name</td>
		<td>
			<input type="text" id="bank_name" name="bank_name" class="w100 form-control" />
		</td>
		<td>Branch Name</td>
		<td>
			<input type="text" id="branch_name" name="branch_name" class="w100 form-control"/>
		</td>
		</tr>
		<tr>
		<td>Cheque Number</td>
		<td>
			<input type="text" id="cheque_no" name="cheque_no" class="w100 form-control"/>
		</td>
		<td>Cheque Date</td>
		<td>
		 <input name="check_date" type="date" id="cheque_date"  style="width:185px; background-color:#FFF"  value="<?=$dt?>" class="tcal" />	</div>
			</td>
			</tr>
		</table>
			</div>
		</div>	

   
<p></p>
		<br />
        <div align="center" style="color:#990000; font-weight:bold;">
          <?php   
		     echo $mas;
		  ?>
        </div>
    <table>
          <tr>
            <td height="35" ><input type="submit" id="Save" name="Save" value="Save" class="btn btn-info" style="margin:inherit; width:100px"/></td>
          </tr>
    </table>

</form>
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
   <div class="card">
						
    <form method="post" id="FORMNAME1">
	<?php  echo $objIms->error;?>
	
										<div class="form-group row">
                                            <label class="col-lg-4 col-form-label" for="val-username">Client Name <span class="text-danger"></span></label>
                                            <div class="col-lg-6">
                                                 <input name="cl_name" type ="text" class="form-control" id="cl_name"  onkeypress="return AllowAlphabet(event)" maxlength="12" value="<?php echo $objIms->client_name?>" required="required" <?php echo $objIms->disableit;?>/>
                                            </div>
                                        </div>
										<!--<div class="form-group row">
                                            <label class="col-lg-4 col-form-label" for="val-username">Address <span class="text-danger">*</span></label>
                                            <div class="col-lg-6">
                                                <textarea name="address" class="form-control" maxlength="50" id="address" <?php echo $objIms->disableit;?> ><?php echo $objIms->address;?></textarea>
                                            </div>
                                        </div>-->
										
											<div class="form-group row">
                                            <label class="col-lg-4 col-form-label" for="val-username">Contact No <span class="text-danger">*</span></label>
                                            <div class="col-lg-6">
                                                <input name="contact_no" type ="text"  class="form-control" id="contact_no" onkeypress="return validate(event)" value="<?php echo $objIms->contact_no?>" required <?php echo $objIms->disableit;?>/>
                                            </div>
                                        </div>

									<!--<div class="form-group row">
                                            <label class="col-lg-4 col-form-label" for="val-username">Contact Person Name <span class="text-danger">*</span></label>
                                            <div class="col-lg-6">
                                                <input type ="text" name="contact_person" class="form-control" id="contact_person" onkeypress="return AllowAlphabet(event)" maxlength="10" value="<?php echo $objIms->contact_person?>" required <?php echo $objIms->disableit;?>/>
                                            </div>
                                        </div>-->
										
										
										<!--<div class="form-group row">
                                            <label class="col-lg-4 col-form-label" for="val-username">Email <span class="text-danger">*</span></label>
                                            <div class="col-lg-6">
                                                <input type ="email" name="email" id="email" class="form-control" value="<?php echo $objIms->email_id?>"  <?php echo $objIms->disableit;?>/>
                                            </div>
                                        </div>-->
										
										<!--<div class="form-group row">
                                            <label class="col-lg-4 col-form-label" for="val-username">GSTin No <span class="text-danger">*</span></label>
                                            <div class="col-lg-6">
                                                <input name="tin_no" type ="text" id="tin_no" class="form-control" value="<?php echo $objIms->tin_no?>"  <?php echo $objIms->disableit;?>/>
                                            </div>
                                        </div>-->

										 
	
		<button type="button" name="add_client" onclick="add_new()" class="btn btn-success m-t-15 waves-effect" >SAVE</button>
</form>

  </div>

                                
                           
  </div>

</div>
</div>


<script type="text/javascript">
    function validate(key)
{
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('contact_no');
//comparing pressed keycodes
if ((keycode < 48 || keycode > 57))
{
    alert("no only allow")
return false;

}
else
{
//Condition to check textbox contains ten numbers or not
if (phn.value.length <10)
{
return true;
}
else
{
    alert("not greater than 10")
return false;

}
}
}
</script>
<script type="text/javascript">
function AllowAlphabet(e)
{
  isIE = document.all ? 1 : 0
  keyEntry = !isIE ? e.which : event.keyCode;
  if (((keyEntry >= '65') && (keyEntry <= '90')) || ((keyEntry >= '97') && (keyEntry <= '122')) || (keyEntry == '46') || (keyEntry == '32') || keyEntry == '45')
     return true;
  else
{
    alert('Please Enter Only Character values.');
    return false;
      }
}
</script>


 </div>
                        </div>
                    </div>
                </div>
                <!-- End PAge Content -->
            </div>
          
     <script src="../js/lib/jquery/jquery.min.js"></script>
    <script src="../js/lib/bootstrap/js/popper.min.js"></script>
    <script src="../js/lib/bootstrap/js/bootstrap.min.js"></script>
    <!-- slimscrollbar scrollbar JavaScript -->
    <script src="../js/jquery.slimscroll.js"></script>
    <!--Menu sidebar -->
    <script src="../js/sidebarmenu.js"></script>
    <!--stickey kit -->
    <script src="../js/lib/sticky-kit-master/dist/sticky-kit.min.js"></script>
    <!--Custom JavaScript -->
    <script src="../js/custom.min.js"></script>
	
	
		<script src="../js/select2.js"></script>
		<script type="text/javascript">
$("input[name='r3']").click(function() {
    var status = $(this).val();
    if (status == 'Cheque') {
        $("#cheq_hide_header").show('slow');
		$("#cheq_hide").show('slow');
    } else {
		$("#cheq_hide").hide();
		$("#cheq_hide_header").hide('slow');
    }
	
	 if (status == 'Due') {
        $("#paid_amt").val('0');
		$("#paid_amt").attr('readonly', true);
    } else {
		$("#paid_amt").val('0');
		$("#paid_amt").attr('readonly', false);
    }
});
</script>
		<script type="text/javascript">
		
			$(document).ready(function() {
				var country = [];
				$("#item_nm").select2({
				  data: country
				});
			});
			
			$(document).ready(function() {
				var country = [];
				$("#client_name").select2({
				  data: country
				});
			});
			function fun(){
		
			var item_name =$("#item_nm").val();
			var s_code =$("#state_code").val();
			var c_s_code =$("#c_state_code").val();
			
			$.ajax({
		type: "POST",
		url: "fetch_item_det.php",
		data: "item_name="+item_name,
		 dataType: 'json', 
		cache: false,
		success: function(data)
			{
			
				var item_id = data[0];
				var unit_name = data[1];
				var unit_id = data[2];
				var unit_price = data[3];
				var price = data[4];
				var av_qty = data[5];
				var cgst = data[6];
				var sgst = data[7];
				var igst = data[8];
				cgst = parseFloat(cgst);
				sgst = parseFloat(sgst);
				igst = parseFloat(igst);
				if((s_code==c_s_code)&&igst>0){
				cgst =igst/2;
				sgst=igst/2;
				igst =0;
				
				}
				if((s_code!=c_s_code)&&igst>0){
				cgst =0;
				sgst=0;
				igst =igst;
				
				}
				
				if((s_code==c_s_code)&&igst==0){
				cgst =cgst;
				sgst=sgst;
				igst =0;
				
				}
				
				if((s_code!=c_s_code)&&igst==0){
				cgst =0;
				sgst=0;
				igst =cgst+sgst;
				
				}
				$('#item_id').val(item_id);
				$('#unit').val(unit_name);
				$('#unit_id').val(unit_id);
				$('#unit_price').val(unit_price);
				$('#price').val(price);
				$('#av_qty').val(av_qty);
				$('#cgst').val(cgst);
				$('#sgst').val(sgst);
				$('#igst').val(igst);
				
				
			}
			});
   
			
			}
		</script>
<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

<script>
function add_new(){

var client_name = $('#cl_name').val();
var contact_no = $('#contact_no').val();
/*var client_address = $('#address').val();
var contact_person = $('#contact_person').val();
var email = $('#email').val();
var tin_no = $('#tin_no').val();*/

 $.ajax({
		type: "POST",
		url: "add_client_ajax.php",
		data: "client_name="+client_name+"&contact_no="+contact_no,
		 dataType: 'json', 
		cache: false,
		success: function(data)
			{
			
 modal.style.display = "none";
  var opt = data[2];
			document.getElementById("cnm").innerHTML=opt;
			document.getElementById("c_state_code").value=<?php echo $_SESSION['state_code'];?>;
			fun();
			}
			});
   
	


}


function sup_state(){
			var client_name =$("#client_name").val();
			$.ajax({
		type: "POST",
		url: "fetch_code.php",
		data: "client_id="+client_name+"&type=cln",
		 dataType: 'json', 
		cache: false,
		success: function(data)
			{
				var state = data[0];
				
				$('#c_state_code').val(state)
				
				fun();
				
			}
			});
   
			
			}
</script>
</body>

</html>