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



<?php

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

}



if(isset($_POST["additems"]))
{
	$item_id=$_POST["item_id"];
	$item_nm=$_POST["item_nm"];
	$qty=$_POST["qty"];
	$unit=explode("/",$_POST["unit"]);
	$unit_id=$unit[0];
	$unit_name=$unit[1];
	$price=$_POST["price"];
	$sell_price=$_POST["sell_price"];
	
	
	if(($item_id>0) and ($qty>0) and ($price>0) and ($unit_id>0))
	{
	

	
	
							$sql2="insert into tmp_purchase_details(item_id,item_name,qty,pur_price,unit_id,unit_name,sell_price,session_login_id) values('$item_id','$item_nm','$qty','$price','$unit_id','$unit_name','$sell_price','".$_SESSION['login_id']."')";
				  			$final2=mysql_query($sql2);
						
						
	 	
	
		
	}
}

if(isset($_POST["Save"]))
{
	$order_no=$_POST["order_no"];	
	$order_date=$objIms->DateToInt($_POST["order_date"]);
	$stampdate=$objIms->DateToInt(date('d-m-Y'));	
	$vendor_id=$_POST["supplier_name"];	
	$totamt=$_POST["totamt"];
	$pay_type=$_POST["pay_type"];
	$discount=$_POST["discount"];
	$freight_charg=$_POST["freight_charg"];
	$cst_amt=$_POST["cst_amt"];
	$result=$_POST["result"];
	$round_off=$_POST["round_off"];
	
	$sql_1="select * from tmp_purchase_details where session_login_id = '".$_SESSION['login_id']."'";
	$res_1=mysql_query($sql_1);
	if((mysql_num_rows($res_1)>0))
	{
	
			if(($order_no<>"") && ($vendor_id<>""))
			{
				$sql_insmas="insert into tbl_purchase_master(order_no,purchase_date,stampdate,supplier_id,discount, freight_charge, cst, grand_tot, round_off, session_login_id) values('$order_no','$order_date','$stampdate','$vendor_id','$discount','$freight_charg','$cst_amt','$result','$round_off', '".$_SESSION['login_id']."')";
				
				$res_insmas=mysql_query($sql_insmas);
				$lastid=mysql_insert_id();
				
				
				
					
					while($result=mysql_fetch_array($res_1))
					{
					$item_id=$result["item_id"];
					$qty=$result["qty"];
					$pur_price=$result["pur_price"];
					$unit_id=$result["unit_id"];
					$sell_price=$result["sell_price"];
					$sql4="insert into tbl_purchase_details(purmas_id,item_id,pur_qty,pur_price,unit_id,sell_price,session_login_id)values('$lastid','$item_id','$qty','$pur_price','$unit_id','$sell_price','".$_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='$sell_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='$sell_price'";
					mysql_query($update);
					}
					else
					{
					$sqls="insert into tbl_stock(item_id,unit_id,tot_qty,unit_price,sell_price,session_login_id)values('$item_id','$unit_id','$qty','$pur_price','$sell_price','".$_SESSION['login_id']."')";
					//echo $sql4;
					$rss=mysql_query($sqls);
					}
					
					if($pay_type=='Credit')
					{
					 $sql_ins="insert into tbl_account(mas_id,trans_date,actual_amt,Cr_Amt,sales_type,cash_type,discount, freight_charge, cst, grand_tot,session_login_id) values('$lastid','$order_date','$round_off','$round_off','Purchase','$pay_type','$discount','$freight_charg','$cst_amt','$result','".$_SESSION['login_id']."')";
					}
					else
					{
					 $sql_ins="insert into tbl_account(mas_id,trans_date,actual_amt,Dr_Amt,sales_type,cash_type,clear,discount, freight_charge, cst, grand_tot,session_login_id) values('$lastid','$order_date','$round_off','$round_off','Purchase','$pay_type',1,'$discount','$freight_charg','$cst_amt','$result','".$_SESSION['login_id']."')";
					}
				
				$res_ins=mysql_query($sql_ins);
				
				
				$count=$_POST["count"];
			
			for($w=1;$w<$count;$w++)
				{
				
				$tax_mstr_id=$_POST["checkboxtax".$w];
				
				if(isset($_POST["checkboxtax".$w]) and $lastid<>'')
					{
					$lastid1=$objIms->insert("tbl_purchase_tax",array($lastid,$tax_mstr_id),"pur_mstr_id,tax_id");
										 
					}
				}
				
					}
			    		
			
				$sql="delete from tmp_purchase_details where session_login_id = '".$_SESSION['login_id']."'";
				$rest=mysql_query($sql);
				
				
				
				header("location:purchase_view.php");	
			}
	}
	
}

?>

	 <?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...............................................................	
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

		
	<script type="text/javascript">
	$(document).ready(function() {                
	$("#form1").validate({
	rules: {
	delv_location: "required",
	supplier_name: "required",
	pay_type:"required",
	
	},
	messages: {
	delv_location:"",
	supplier_name:"",
	pay_type:"",
	},
	});                
	});
	
	
	
	
	function discountc(str)
		{ 
		var totalamt=document.getElementById("totamt").value;
		var totalnet=document.getElementById("grand_total").value;
		var ctr=document.getElementById("count").value;
		var cst=document.getElementById("cst_amt").value;
	    var fc=document.getElementById("freight_charg").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;
				}
			}
		
		var tottax_fc=eval(nettotal)+eval(cst)+eval(fc);
		document.getElementById("grand_total").value=nettotal.toFixed(2);
		document.getElementById("result").value=tottax_fc.toFixed(2);
		document.getElementById("round_off").value=Math.round(tottax_fc);
		//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 discount_amt=document.getElementById("discount_amt").value;
		var tax_percent=document.getElementById("tax_percent"+str).value;
		var cst=document.getElementById("cst_amt").value;
	    var fc=document.getElementById("freight_charg").value;
		
		var totamt=eval(sum_amt)-eval(discount_amt);
		var totaltax=eval(totamt)*(eval(tax_percent)/100);
		
		document.getElementById("taxamount"+str).value=totaltax.toFixed(2);
        if(terms.checked == true){
		//alert(totamt);
			var total_tax=eval(totalamt)+eval(totaltax);				
		}
		else{
			var total_tax=eval(totalamt)-eval(totaltax);			
			}
			var tottax_fc=eval(total_tax)+eval(cst)+eval(fc);	
			document.getElementById("grand_total").value=total_tax.toFixed(2);
			document.getElementById("result").value=tottax_fc.toFixed(2);
			document.getElementById("round_off").value=Math.round(tottax_fc);
		
        }
		
		function sumtotal()
{
var cst=document.getElementById("cst_amt").value;
	var grd=document.getElementById("grand_total").value;
	var fc=document.getElementById("freight_charg").value;
	
	
		if((cst == "") && (fc!=""))
		{	      
		   sum=eval(grd)+eval(fc);		   
		  }
		 else if((cst != "") && (fc!=""))
		 {
		 sum=eval(grd)+eval(fc)+eval(cst);
		 }	
		else if((fc == "") && (cst != ""))
		{	      
		   sum=eval(grd)+eval(cst);		   
		  }
		 else 
		 {
		 sum=eval(grd);
		 }
		 	 
		 //alert(sum);
		 
	 document.getElementById("result").value=sum.toFixed(2);
	document.getElementById("round_off").value=Math.round(sum);       
}
	</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;  }
         </style>
		 
        <script type="text/javascript"> 
 		jQuery(document).ready(function(){
			$('#item_nm').autocomplete({source:'../ProgramFile/auto/suggest_POitem.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.
			
		    }
			});

}); 
</script>

<script type="application/javascript">
	function isNumberKey(evt)
	{
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 46 || charCode > 57))
	return false;
	return 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>
</head>

<body>

<div class="span11" style=" width:83%;">



<div class="12" style=" margin-left:0px; ">


<a href="<?php echo $objIms->pageCaption($varFileName)?>_list.php?page=1&cmd=Clear" style="float:right">
<span class="btn" style="margin:20px 0px 20px 0px; font-weight:bold">Go Back</span></a>
<br />
<br />
<br />

<div class="12" style=" margin-left:0px;">
<div class="panel" style="border:<?php echo THEMECOLOR?> solid 1px; border-radius:0px;">
<div class="panel-heading" style="margin-bottom:15px; background:<?php echo THEMECOLOR?>; color:<?php echo THEMEFONRCOLOR?>; font-weight:bold; border-radius:0px;">
Add Purchase Details
</div>
<form id="form1" name="form1" method="post" action="">
<p>&nbsp;</p>
<table width="100%" cellpadding="4">
  <tr>
    <td height="38" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>Order   No</strong></td>
    <td nowrap="nowrap" bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td nowrap="nowrap" bgcolor="#FFFFFF" ><input name="order_no" type="text" class="required" id="order_no" value="<?php echo $_POST["order_no"];?>"  style="width:200px; background-color:#FFF"  /></td>
    <td width="8%" height="38" nowrap="nowrap"><strong>Supplier Name<span style="color:#F00; font-weight:bold;">*</span> </strong></td>
    <td width="2%"><strong>:</strong></td>
    <td width="31%"><select name="supplier_name" id="supplier_name" style="width:200px;" onchange="showadd(this.value)" class="required">
        <option value="">---Please Select---</option>
        <?php 
							$sqlc="select * from tbl_supplier 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["supplier_name"]){ ?> selected="selected" <?php }?>>
        <?=$cs["supplier_name"];?>
        </option>
        <?php }}?>
    </select></td>
    </tr>
  <tr>
    <td width="7%" height="34" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>Order Date </strong></td>
    <td width="1%" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td width="28%" nowrap="nowrap" bgcolor="#FFFFFF" ><?php if(($_POST["order_date"])=="") { $dt=date("d-m-Y");} else { $dt=$_POST["order_date"];}?>
        <input name="order_date" type="text" id="order_date"  style="width:185px; background-color:#FFF"  value="<?=$dt?>" class="tcal" readonly=""/></td>
    <td nowrap="nowrap"><strong>Cash Type<span style="color:#F00; font-weight:bold;">*</span></strong></td>
    <td><strong>:</strong></td>
    <td><select name="pay_type" id="pay_type" style="width:100px;"  >
      <option value="">---Please Select---</option>
      <option value="Credit"<?php if($_POST["pay_type"]=='Credit'){?> selected="selected"<?php }?>>Credit</option>
      <option value="Debit"<?php if($_POST["pay_type"]=='Debit'){?> selected="selected"<?php }?>>Cash</option>
    </select></td>
  </tr>
</table>
<br />
<div class="panel">
<div class="panel-heading"><strong>Add Item </strong></div>
            <p>&nbsp;</p>
			
			 <table width="100%">
            <tr height="32" align="left">
            <td width="6%" nowrap="nowrap">Item Name</td>
            <td width="1%" nowrap="nowrap"><strong>:</strong></td>
            <td width="19%" nowrap="nowrap"><input type="text" name="item_nm" id="item_nm" style="width:150px" autofocus="autofocus"  /><input type="hidden" name="item_id" id="item_id" style="width:350px" /></td>
            <td width="3%" nowrap="nowrap">Unit</td>
            <td width="1%" nowrap="nowrap"><strong>:</strong></td>
            <td width="11%" nowrap="nowrap"><select name="unit" id="unit" style="width:100px;" onchange="showadd(this.value)" >
              <option value="">Please Select</option>
              <?php 
							$sqlc="select * from tbl_unit 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["unit_name"];?>" >
              <?=$cs["unit_name"];?>
              </option>
              <?php }}?>
            </select></td>
            <td width="2%" nowrap="nowrap">Qty</td>
            <td width="1%" nowrap="nowrap"><strong>:</strong></td>
            <td width="11%" nowrap="nowrap"><input type="text" name="qty" id="qty" style="width:100px" onkeypress="return isNumberKey(event)"/></td>
            <td width="8%" nowrap="nowrap">Pur Price(Per)</td>
            <td width="1%" nowrap="nowrap"><strong>:</strong></td>
            <td width="8%" nowrap="nowrap"><input type="text" name="price" id="price" style="width:100px" /></td>
			<td width="7%" nowrap="nowrap">Sell Price(Per)</td>
            <td width="1%" nowrap="nowrap"><strong>:</strong></td>
            <td width="14%" nowrap="nowrap"><input type="text" name="sell_price" id="sell_price" style="width:100px" /></td>
            <td width="6%" nowrap="nowrap"><input type="submit" name="additems" id="additems" value="Add Items" class="btn btn-warning" style="margin-top::0px" /></td>
            </tr>
           </table>
			
</div>

     <div class="panel">
            <div class="panel-heading"><strong>Item List of Purchase </strong></div>
            <p>&nbsp;</p>
            <div align="right">
              <table width="100%" class="table table-striped">
                
                <?php 
				 $sql_viewtmp="select *  from tmp_purchase_details where session_login_id = '".$_SESSION['login_id']."'";
				$res_viewtmp=mysql_query($sql_viewtmp);
				if(mysql_num_rows($res_viewtmp)>0)
				{ 
					$i=1;
					$sums=0;
					?>
                
                <tr height="32" align="left">
                  <th nowrap="nowrap" width="7%">Si No</th>
              <th nowrap="nowrap" width="40%">Item Name</th>
             
            <th nowrap="nowrap" width="20%">Unit Name </th>
              <th nowrap="nowrap" width="20%">Order Qty</th>
              <th nowrap="nowrap" width="20%">Sell Price(Per) </th>
              <th nowrap="nowrap" width="20%">Pur Price(Per)</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" width="40%"><?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["sell_price"];?></td>
              <td nowrap="nowrap" width="20%"><?php echo $rows["pur_price"];?></td>
              <td nowrap="nowrap" width="20%"><?php echo $totprice=($rows["qty"]*$rows["pur_price"]);?></td>
              <td nowrap="nowrap" width="20%"><button type="submit" name="del" value="<?=$rows["id"]?>">Delete</button></td>
              </tr>  <?php $sums=$sums+($totprice);$i++;} ?>   
                <tr height="32">
                  <td nowrap="nowrap">&nbsp;</td>
                <td colspan="5" nowrap="nowrap"><div align="right"><strong>Total : </strong></div></td>
                <td nowrap="nowrap"><?php echo $sums;?>
                  <input type="hidden" name="totamt" id="totamt" value="<?php echo $sums;?>" /></td>
                <td nowrap="nowrap">&nbsp;</td>
              </tr>
                <tr height="32">
                  <td nowrap="nowrap">&nbsp;</td>
                <td colspan="5" nowrap="nowrap"><div align="right">Discount(%): 
                  <input type="text" name="discount" id="discount" onblur="discountc(this.value)"  value="0" style="width:50px;"  />
                </div></td>
                <td nowrap="nowrap"><input type="text" name="discount_amt" id="discount_amt" readonly="" value="0" s style="width:100px;"  /></td>
                <td nowrap="nowrap">&nbsp;</td>
              </tr>
                <tr height="32">
                  <td nowrap="nowrap">&nbsp;</td>
                <td colspan="5" nowrap="nowrap"><div align="right"></div></td>
				    <td nowrap="nowrap">&nbsp;</td>
                <td nowrap="nowrap">&nbsp;</td>
              </tr> 
                <?php }?>
              </table>
				 <table width="100%" class="table table-bordered">
          
          <?php 
		  $t_totald=0;
		 $sqltemptax="Select * from tbl_tax_mstr where session_login_id = '".$_SESSION['login_id']."' and tax_for='Purchase' order by id";
$exe_temptax=mysql_query($sqltemptax);
if(mysql_num_rows($exe_temptax)>0)
{$ctr=1;
 $totaltax=0;
  while($rstemptax=mysql_fetch_array($exe_temptax))
{
	
  ?>
            <tr>
              <td width="13%"><input type="checkbox" name="checkboxtax<?=$ctr?>" id="checkboxtax<?=$ctr?>" <?php if(isset($_POST["checkboxtax".$ctr])){?> checked="checked" <?php }?> value="<?=$rstemptax["id"];?>" onclick="check(<?=$ctr?>)" /></td>
              <td width="31%"><?=$rstemptax["tax_name"];?></td>
               <td width="41%"><?=$rstemptax["tax_percent"]; ?>
              <input type="hidden" name="tax_percent<?=$ctr?>" id="tax_percent<?=$ctr?>" value="<?=$rstemptax["tax_percent"];?>"></td>
             
              <td width="15%"><input type="text" name="taxamount<?=$ctr?>" id="taxamount<?=$ctr?>" style="width:100px; border:none; background:#FFFFFF;" readonly value="0"></td>
              
            </tr>
            <?php  $ctr++;}}?>
            <input type="hidden" name="count" id="count" value="<?=$ctr;?>">
    </table>
	
	<table width="100%" class="table table-bordered">
          <tr>
          <td width="36%">&nbsp;</td>
            <td width="49%"><div align="right"><strong>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 $nettot;?>"/> </td>
          </tr>
          <tr>
         
          <td>&nbsp;</td>
            <td><div align="right"><strong>Freight Charge</strong></div></td>
            <td><input type="text" name="freight_charg" id="freight_charg" style="width:100px;" onblur="sumtotal()" value="0"/></td>
          </tr>
          <tr>
          
            <td><div align="right"></div></td>
            <td><div align="right"><strong>CST Against Form C</strong></div></td>
            <td><input type="text" name="cst_amt" id="cst_amt" style="width:100px;" onblur="sumtotal()" value="0"/></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="result" id="result" style="width:100px; border:none; background:#FFFFFF;" readonly value="0"/></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="0"/></td>
          </tr>
          <tr>
            <td><div align="right"></div></td>
            <td>&nbsp;</td>
          </tr>
        </table>
            </div>
     </div>
	
		

   
<p></p>
		<br />
        <div align="center" style="color:#990000; font-weight:bold;">
          <?php   
		     echo $mas;
		  ?>
        </div>
    <table>
     </tr>
          <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>
</body>
</html>
