<?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_itemdamage_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"];*/
	$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"];
	
	
	if(($item_id>0) and ($qty>0) and ($price>0) and ($unit_id>0))
	{
	

	
	 $sqlchk="select * from tmp_itemdamage_details where session_login_id = '".$_SESSION['login_id']."' and item_id='$item_id' and unit_id='$unit_id' and pur_price='$unit_price' and sell_price='$price'";
	$exechk=mysql_query($sqlchk);
	if(mysql_num_rows($exechk)==0){
							$sql2="insert into tmp_itemdamage_details(item_id,item_name,qty,sell_price,unit_id,unit_name,pur_price,session_login_id) values('$item_id','$item_nm','$qty','$price','$unit_id','$unit_name','$unit_price', '".$_SESSION['login_id']."')";
				  			$final2=mysql_query($sql2);
						
						
	 	}
		else
		{
		$msg='<span style="color:#FF0000">Item Already Exists...</span>';
		}
	
		
	}
}

if(isset($_POST["Save"]))
{
	
	$stampdate=$objIms->DateToInt(date('d-m-Y'));
	$user_id=$_SESSION["id"];	
	
	 $sql_1="select * from tmp_itemdamage_details where session_login_id = '".$_SESSION['login_id']."'";
	$res_1=mysql_query($sql_1);
	if((mysql_num_rows($res_1)>0))
	{
		
					while($result=mysql_fetch_array($res_1))
					{
					$item_id=$result["item_id"];
					$qty=$result["qty"];
					$unit_price=$result["sell_price"];
					$pur_price=$result["pur_price"];
					$unit_id=$result["unit_id"];
					
					$sql4="insert into tbl_itemdamage_details(damage_date,item_id,dem_qty,sell_price,unit_id,pur_price,stampdate,user_id,session_login_id)values('$stampdate','$item_id','$qty','$unit_price','$unit_id','$pur_price','$stampdate','$user_id','".$_SESSION['login_id']."')";
					//echo $sql4;
					$rs1=mysql_query($sql4);

					$sql_bank="insert into tbl_account(trans_date, Dr_Amt, sales_type, mas_id,session_login_id)values('$stampdate','$pur_price','bad debts','$user_id','".$_SESSION['login_id']."');";
					$res_bank=mysql_query($sql_bank);

					$sql_purchase="insert into tbl_account(trans_date, Cr_Amt, sales_type, mas_id,session_login_id)values('$stampdate','$pur_price','Purchase','$user_id','".$_SESSION['login_id']."');";
					$res_purchase=mysql_query($sql_purchase);
					
					$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_itemdamage_details where session_login_id = '".$_SESSION['login_id']."'";
				$rest=mysql_query($sql);
				
				$msg='<span style="color:#FF0000">Item Inserted Successfully...</span>';
				?>
<script type="text/javascript">
	alert('Success');
</script>
				<?php
				header("location:damage_list.php");
					
			
	}
	
}

?>




		
	<script type="text/javascript">
	$(document).ready(function() {                
	$("#form1").validate({
	rules: {
	delv_location: "required",
	client_name: "required",
	sales_type: "required",
	
	},
	messages: {
	delv_location:"",
	client_name:"",
	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;  }
         </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);
		    }
			});

}); */
</script>

<script type="application/javascript">
 function isNumberKey(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("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);
		
        }
		
		
	</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">
            <!-- Bread crumb -->
            <div class="row page-titles">
                <div class="col-md-5 align-self-center">
                    <h3 class="text-primary"></h3> </div>
                <div class="col-md-7 align-self-center">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="javascript:void(0)">Home</a></li>
                        <li class="breadcrumb-item active">Add Damage Items</li>
                    </ol>
                </div>
            </div>
            <!-- End Bread crumb -->
            <!-- Container fluid  -->
            <div class="container-fluid">
                <!-- Start Page Content -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">
							<h4>Add Damage Items <span style="float:right"><button onclick="goBack()" class="btn btn-info btn-sm">Go Back</button><script>
function goBack() {
    window.history.back();
}
</script></span></h4>
						<hr />
<form id="form1" name="form1" method="post" action="">

<div class="panel">
<div class="panel-heading"><strong>Add Item </strong></div>
           
			
			 <table width="100%">
            <tr >
            <td >Item Name</td>
            
            <td ><select name="item_nm" id="item_nm" onchange="fun()" class="form-control" style="width:300px;">
			<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 >Unit</td>
            
            <td ><input name="unit" id="unit" class="form-control" style="width:75px;" readonly="" />
              <input type="hidden" name="unit_id" id="unit_id" style="width:200px;">             </td>
			<td >Unit Price</td>
            
            <td ><input type="hidden" name="unit_price" id="unit_price"  /><input type="text" name="price" class="form-control" id="price" style="width:75px" readonly="" /></td>
			<td>Avail Qty </td>
			
           
            <td ><input type="text" name="av_qty" id="av_qty" class="form-control" style="width:75px" readonly="" /></td>
            <td>Qty</td>
            
            <td ><input type="text" name="qty" id="qty" class="form-control" style="width:75px" onblur="maxqty(this.value)" onkeypress="return isNumberKey(event)"/></td>
            <td ><input type="submit" name="additems" id="additems" value="Add Items" class="btn btn-success" style="margin-top::0px" /></td>
            </tr>
           </table>
			
</div>

     <div class="panel">
            <div class="panel-heading"><strong>Item List of Damage <?=@$msg?></strong></div>
            <p>&nbsp;</p>
            <table width="100%" class="table table-striped">
		
            <?php 
				 $sql_viewtmp="select *  from tmp_itemdamage_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;
					$totdis=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%">Pur Price(Per)</th>
			<th nowrap="nowrap" width="20%">Sell Price(Per)</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"]; $item_n=$rows["item_name"];?></td>
            
            <td nowrap="nowrap" width="20%"><?php echo $rows["unit_name"]; $unit_n=$rows["unit_name"];?></td>
            <td nowrap="nowrap" width="20%"><?php echo $rows["qty"]; $qty=$rows["qty"];?></td>
            <td nowrap="nowrap" width="20%"><?php echo $rows["pur_price"]; $pur_pri=$rows["pur_price"];?></td>
			<td nowrap="nowrap" width="20%"><?php echo $rows["sell_price"]; $sql_pri=$rows["sell_price"];?></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+($totprice);$i++;
			$totdis=$totdis+$discount;
			}} ?>   
                  
           </table>
           <?php
$sql_bad="insert into bad_debts(dr_amount, under, item_id, quantity, pur_price, session_login_id) values('$pur_pri', 'purchase_baddebts', '".$row_itm["item_id"]."', '$qty', '$pur_pri', '".$_SESSION['login_id']."' );";
$res_bad=mysql_query($sql_bad);

$sql_account="insert into tbl_account(actual_amt, Cr_Amt, sales_type, session_login_id) values('$pur_pri', '$pur_pri', 'purchase_baddebts','".$_SESSION['login_id']."');";
$res_account=mysql_query($sql_account);
?>

    </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>
                        </div>
                    </div>
                </div>
                <!-- End PAge Content -->
            </div>
            <!-- End Container fluid  -->
			
      <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">
		
			$(document).ready(function() {
				var country = [];
				$("#item_nm").select2({
				  data: country
				});
			});
			function fun(){
			var item_name =$("#item_nm").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];
				
				$('#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);
				
				
			}
			});
   
			
			}
		</script>

</body>

</html>