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

<link href="../css/select2.css" rel="stylesheet" />
<!-- 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">

<?php

if(isset($_GET["uid"]))
{
$uid=$_GET["uid"];
$rs=$objIms->getRows("view_purchase_supplier","md5(id)='$uid' and   session_login_id = '".$_SESSION['login_id']."'");
$pur_id=$rs["id"];
$order_no=$rs["order_no"];
$purchase_date=$objIms->IntToDate($rs["purchase_date"]);
$supplier_name=$rs["supplier_name"];
$supplier_id = $rs["supplier_id"];

			

				

}
 $sql_acc="select *  from tbl_account where  session_login_id = '".$_SESSION['login_id']."' and mas_id=$pur_id and sales_type='Purchase' or payment_mode='Cash Or Cheque' order by id asc";
$res_acc=mysql_query($sql_acc);
$rsacc=mysql_fetch_array($res_acc);
$payment=$rsacc['payment_mode'];

if(isset($_POST["Save"]))
{
	
	$stampdate=$objIms->DateToInt(date('d-m-Y'));
	$count=$_POST["count"];	
	$payment_mode=$_POST["payment_mode"];
	$r_date = date('d-m-Y', strtotime($_POST["ret_date"]));	
	
	$ret_date=$objIms->DateToInt($r_date);
		$user_id=$_SESSION["id"];

				$sql_insmas="insert into tbl_purchase_return_mstr(purchasemstr_id,stampdate,user_id,ret_date,session_login_id) values('$pur_id','$stampdate','$user_id','$ret_date','".$_SESSION['login_id']."')";
				
				$res_insmas=mysql_query($sql_insmas);
				$lastid=mysql_insert_id();
				
				$ret_no='PURRET/'.date('M').'/'.date('Y').'/'.$lastid;
				$sql_upmas="Update tbl_purchase_return_mstr set return_no='$ret_no' where id='$lastid' and session_login_id = '".$_SESSION['login_id']."'";
				$res_upmas=mysql_query($sql_upmas);
				$totalamount=$_POST["totalamount"];
					
					for($str=1;$str<$count;$str++)
					{
					$purdet_id=$_POST["purdet".$str];
					$item_id=$_POST["item_id".$str];
					$unit_id=$_POST["unit_id".$str];
					$ret_qty=$_POST["ret_qty".$str];
					$discount=$_POST["discount".$str];
					$pur_price=$_POST["pur_price".$str];					
					$cgst=$_POST["cgst".$str];
					$sgst=$_POST["sgst".$str];
					$igst=$_POST["igst".$str];
					$sell_price=$_POST["sell_price".$str];
						if($ret_qty>0 or $ret_qty<>'')
						{
						
						$sql4="insert into tbl_purchase_return_details(purretmas_id,item_id,ret_qty,unit_id,discount,pur_price,sell_price,cgst,sgst,igst,session_login_id)values('$lastid','$item_id','$ret_qty','$unit_id','$discount','$pur_price','$sell_price','$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='$sell_price'";
						$query=mysql_query($sel);
							if(mysql_num_rows($query)>0)
							{
							$rsq=mysql_fetch_array($query);
							$tot_qty=$rsq["tot_qty"]-$ret_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);
							}
						}
					}
			
					$totdiscount=$_POST["totdis"];
					$invoice_no=$objIms->trasaction_no();echo $payment_mode;
					if($payment='Cash' || $payment='Cheque'){
					if($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, session_login_id) values('$invoice_no','$lastid','$stampdate','$totalamount','$totalamount','Purchase Return','Cash',1,'$totdiscount','$totalamount','".$_SESSION['login_id']."')";
					 $res_ins=mysql_query($sql_ins);

					 $sql_cash="insert into cash_detail(sales_type, dr_amount, pur_ret_id, stampdate,session_login_id)  values('Purchase_return', '$totalamount', '$pur_id', '$stampdate','".$_SESSION['login_id']."');";
					 $res_cash=mysql_query($sql_cash);
					}
					 else{
					 $sql_ins1="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Cr_Amt,sales_type,cash_type,clear,discount, grand_tot, session_login_id) values('$invoice_no','$lastid','$stampdate','$totalamount','$totalamount','Purchase Return','Cheque',1,'$totdiscount','$totalamount', '".$_SESSION['login_id']."')";
					 $res_ins1=mysql_query($sql_ins1);

					 $sql_bank="insert into tbl_bank(head, debit, stampdate,session_login_id)  values('Purchase_return', '$totalamount', '$stampdate','".$_SESSION['login_id']."');";
					 $res_cash=mysql_query($sql_bank);
					 }
					}
					else{
						$sql_ret = "insert into supplier_details(name_id, dr_amount, sales_type, pur_mstr_id, stampdate, session_login_id) values('$supplier_id', '$totalamount', 'Purchase_return', '$pur_id','$stampdate','".$_SESSION['login_id']."' )";
					$res_ret = mysql_query($sql_ret);

						 $sql_ins2="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Cr_Amt,sales_type,cash_type,clear,discount, grand_tot, session_login_id) values('$invoice_no','$lastid','$stampdate','$totalamount','$totalamount','Purchase Return','due',1,'$totdiscount','$totalamount', '".$_SESSION['login_id']."')";
					 $res_ins2=mysql_query($sql_ins2);
					}
					
				
				
			    		
					
			
							
				
		     	header("location:purchasereturn_view.php?uid=".md5($lastid));	
			
	
}
	
?>



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


<style type="text/css">
<!--
.table_bg{ border:#CCCCCC solid 1px; border-radius:5px; height:auto; width:auto; padding:20px; margin-bottom:10px;}


-->
</style>

<script language="javascript" type="text/javascript">
function chkqty(str)
{
var orderqty=$('#rest_qty'+str).val();
var stock=$('#stock'+str).val();
var ret_qty=$('#ret_qty'+str).val();
//alert(ret_qty);
var show=0;
	if(eval(orderqty)<eval(ret_qty))
	{
	alert("Return Qty Should Not Be greater than Rest Qty");
	$('#ret_qty'+str).val('0');
	show=1;
	}
	else
	{
		if(eval(stock)<eval(ret_qty))
		{
		alert("Return Qty Should Not Be greater than Stock");
		$('#ret_qty'+str).val('0');
		show=1;
		}
	}
	if(show==0)
	{
	$(':input[type="submit"]').prop('disabled',false);
	}
}


function amtsum(value,ctr)
{
var discount=$("#discount"+ctr).val();
var pur_price=$("#pur_price"+ctr).val();


var price=eval(value)*eval(pur_price);
var totalp=eval(price)-(eval(discount)*eval(price))/100;
var cgst=eval(totalp)*eval($("#cgst"+ctr).val())/100;
var sgst=eval(totalp)*eval($("#sgst"+ctr).val())/100;
var igst=eval(totalp)*eval($("#igst"+ctr).val())/100;


var total=totalp+cgst+sgst+igst;
$("#totprice"+ctr).val(total.toFixed(2));
var count=$("#count").val();
var sum=0;
for(var sh=1;sh<count;sh++)
{
sum=eval(sum)+eval($("#totprice"+sh).val());
}
$("#totamt").val(sum);
$("#totalamount").val(Math.round(sum));
}
</script>

							<h4>Purchase Return <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="">
<p>&nbsp;</p>
<table width="100%" cellpadding="4">
  <tr>
    <td height="38"  bgcolor="#FFFFFF" ><strong>Order   No</strong></td>
    <td  bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td  bgcolor="#FFFFFF" ><?php echo $order_no;?></td>
    <td width="8%" height="38" ><strong>Supplier Name<span style="color:#F00; font-weight:bold;">*</span> </strong></td>
    <td width="2%"><strong>:</strong></td>
    <td width="31%" style="text-align:left"><?php echo $supplier_name;?></td>
    </tr>
  <tr>
    <td width="7%" height="34"  bgcolor="#FFFFFF" ><strong>Order Date </strong></td>
    <td width="1%"  bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td width="28%"  bgcolor="#FFFFFF" >
       <?php echo $purchase_date;?></td>
    <td ><strong>Return Date</strong></td>
    <td><strong>:</strong></td>
    <td><?php if(($_POST["ret_date"])=="") { $dt=date("d-m-Y");} else { $dt=$_POST["ret_date"];}?>
        <input name="ret_date" type="date" id="ret_date"  style="width:185px; background-color:#FFF"  value="<?=$dt?>" class="tcal form-control" required /></td>
    </tr>
</table>
<br />


     <div class="panel">
            <div class="panel-heading"><strong>Item List of Purchase </strong></div>
            <p>&nbsp;</p>
            <table width="100%" class="table table-striped">
		
            <?php 
				 $sql_viewtmp="select *  from view_purchase_det where purmas_id=$pur_id and session_login_id = '".$_SESSION['login_id']."'";
				$res_viewtmp=mysql_query($sql_viewtmp);
				if(mysql_num_rows($res_viewtmp)>0)
				{ 
					$i=1;
					$sums=0;

					?>
                     
                     <tr  align="left">
           <!-- <th >Si No</th>-->
            <th>Item Name</th>
           
            <!--<th >Unit Name </th>-->
            <th >Order Qty</th>
            
            <th  >Sell Price(Per) </th>
            <th >Pur Price(Per)</th>
            <th  >Total</th>
            <th  >Discount(in %)</th>
            <th  >CGST(%)</th>
           <!-- <th width="20%" >CGST </th>-->
            <th  >SGST(%)</th>
          <!--  <th width="20%" >SGST</th>-->
            <th  >IGST(%)</th>
            <!--<th width="20%" >IGST</th>-->
            <th  >Total Price</th>
            <th  >Rest qty </th>
            <th >Stock</th>
            <th >Return Qty </th>
              <th  >Total Price </th>
              </tr>
            <?php
			$totdis=0;
				while($rows=mysql_fetch_assoc($res_viewtmp))
					{
						
				$sumretsql="select sum(ret_qty) as ret_qty from view_purret_mstrdet where session_login_id = '".$_SESSION['login_id']."' and purchasemstr_id=".$rows["purmas_id"]." and item_id=".$rows["item_id"];	
				$sumretexe=mysql_query($sumretsql);
				$sumretrw=mysql_fetch_array($sumretexe);
				$sumret=0;
				$sumret=$sumretrw["ret_qty"];
				if($sumret<>''){$sumret=$sumret;}else{$sumret=0;}		
				
			$sumstocksql="select sum(tot_qty) as stoct_qty from tbl_stock where session_login_id = '".$_SESSION['login_id']."' and unit_id=".$rows["unit_id"]." and item_id=".$rows["item_id"]." and unit_price=".$rows["pur_price"]." and sell_price=".$rows["sell_price"];	
				$sumstockexe=mysql_query($sumstocksql);
				$sumstockrw=mysql_fetch_assoc($sumstockexe);
				$sumstock=$sumstockrw["stoct_qty"];
				if($sumstock<>''){$sumstock=$sumstock;}else{$sumstock=0;}		
							
							
			?>
           
            <tr >
          <!--  <td  ><?php echo $i;?></td>-->
           
		    <td ><input type="hidden" name="purdet<?=$i?>" id="purdet<?=$i?>"  value="<?php echo $rows["id"];?>"  />
		      <input type="hidden" name="item_id<?=$i?>" id="item_id<?=$i?>"  value="<?php echo $rows["item_id"];?>"  /><?php echo $rows["item_name"];?></td>
		    <input type="hidden" name="unit_id<?=$i?>" id="unit_id<?=$i?>"  value="<?php echo $rows["unit_id"];?>"  /><?php //echo $rows["unit_name"];?><input type="hidden" name="discount<?=$i?>" id="discount<?=$i?>"  value="<?php echo $rows["discount"];?>"  />
            <td ><?php echo $rows["pur_qty"];?></td>
            
            <td ><input type="hidden" name="sell_price<?=$i?>" id="sell_price<?=$i?>"  value="<?php echo $rows["sell_price"];?>"  /><?php echo $rows["sell_price"];?></td>
            <td  ><input type="hidden" name="pur_price<?=$i?>" id="pur_price<?=$i?>"  value="<?php echo $rows["pur_price"];?>"  /><?php echo $rows["pur_price"];?></td>
            <td ><?php  $totsum=($rows["pur_qty"]*$rows["pur_price"]); echo number_format($totsum,2);?></td>
            <td ><?php  $discount=$totsum*($rows["discount"]/100); $totprice=$totsum-$discount; echo number_format($rows["discount"],2); $totdis=$totdis+$discount;?></td>
            <td  ><input type="hidden" name="cgst<?=$i?>" id="cgst<?=$i?>"  value="<?php echo $rows["cgst"];?>"  />
              <?php echo $rows["cgst"];?><?php  $cgst=$totprice*($rows["cgst"]/100); echo number_format($cgst,2);?></td>
            <td ><input type="hidden" name="sgst<?=$i?>" id="sgst<?=$i?>"  value="<?php echo $rows["sgst"];?>"  /><?php echo $rows["sgst"];?><?php  $sgst=$totprice*($rows["sgst"]/100); echo number_format($sgst,2);?></td>
            <td  ><input type="hidden" name="igst<?=$i?>" id="igst<?=$i?>"  value="<?php echo $rows["igst"];?>"  /><?php echo $rows["igst"];?><?php  $igst=$totprice*($rows["igst"]/100); echo number_format($igst,2);?></td>
            <td ><?php   $totamt=$totprice+$cgst+$sgst+$igst; echo number_format($totamt,2);?></td>
            <td ><input type="text" name="rest_qty<?=$i?>" id="rest_qty<?=$i?>"  readonly="" value="<?=$rows["pur_qty"]-$sumret?>" style="width:40px;" /></td>
            <td ><input type="text" name="stock<?=$i?>" id="stock<?=$i?>" style="width:40px;" readonly="" value="<?=$rows["pur_qty"]-$sumret?>" /></td>
            <td ><input type="text" name="ret_qty<?=$i?>" id="ret_qty<?=$i?>" onkeypress="return isNumberKey(event)" style="width:40px;" onblur="chkqty(<?=$i?>);amtsum(this.value,<?=$i?>)" /></td>
            <td ><input type="text" name="totprice<?=$i?>" id="totprice<?=$i?>" style="width:75px;" readonly="" value="0" /></td>
            </tr>
<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 showpay(str)
	{
		if(str=='Cheque')
		{
			document.getElementById("showdiv").style.display='block';
		}
		else
		{
			document.getElementById("showdiv").style.display='none';
		}
	}
   
</script>
            <?php $sums=$sums+($totprice);$i++;} ?>
			<tr height="32">
              
              
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td >&nbsp;</td>
              <td ><input type="hidden" name="totdis" id="totdis" style="width:75px;"  value="<?=$totdis?>" /></td>
              <td >Total</td>
              <td ><input type="text" name="totamt" id="totamt" style="width:75px;" readonly="" value="0" /></td>
            </tr>    
            <tr height="32">
              <td ><input type="hidden" name="count" id="count"  value="<?=$i?>" style="width:75px;" /></td>
              <td colspan="18" ><div align="right"></div></td>
              </tr> 
            <?php }?>
           </table>
		   
		  <table width="100%" class="table table-bordered"> 
            <tr>
              <td>&nbsp;</td>
              <td><div align="right"><strong>Total Amount : </strong></div></td>
              <td><input type="text" name="totalamount" id="totalamount" style="width:100px;" readonly value="0"></td>
            </tr>

			  <tr>
			  <td>&nbsp;</td>
			  <td width="50%" height="34"  bgcolor="#FFFFFF" align="right"><strong>Payment Mode </strong></td>
              
              <td width="10%" height="34" bgcolor="#FFFFFF" ><select name="payment_mode" id="payment_mode"  class=" form-control" onchange="showpay(this.value)">
              	<option value="$payment"<?php if($_POST["payment"]=='$payment'){?> selected='selected'<?php } ?>> <?php echo $payment;?></option>
              	<option value="cash"<?php if($_POST["payment_mode"]=='Cash'){?> selected="selected"<?php }?>>Cash</option>
              	<option  value="cheque"<?php if($_POST["payment_mode"]=='Cheque'){?> selected='selected'<?php } ?>>Cheque</option>
              </select>
              </td>
              </tr>
<!--           <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr> -->
          </table>

		<div id="showdiv" style="display:none;">
		<table width="100%" class="table table-bordered">
  <tr>
    <td>Cheque No. </td>
    <td><strong>:</strong></td>
    <td><input type="text" name="cheque_no" id="cheque_no" /></td>
    <td>Cheque Date </td>
    <td><strong>:</strong></td>
    <td><input type="date" name="cheque_date" id="cheque_date" /></td>
  </tr>
  <tr>
    <td>Bank Name </td>
    <td><strong>:</strong></td>
    <td><input type="text" name="bank_name" id="bank_name" /></td>
    <td>Branch Name </td>
    <td><strong>:</strong></td>
    <td><input type="text" name="branch_name" id="branch_name" /></td>
  </tr>
</table>
</div>
     <table class="table">
              <tr>
              <td>&nbsp;</td>
			    <td align="center"><input type="submit" id="Save" name="Save" value="Save" class="btn btn-info"  disabled="disabled" style="margin:inherit; width:100px"/></td>
			    <td>&nbsp;</td>
		    </tr>
    </table>

   </div>
       

</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 type="text/javascript">
    		function showpay(str)
	{
		if(str=='cheque')
		{
			document.getElementById("showdiv").style.display='block';
		}
		else
		{
			document.getElementById("showdiv").style.display='none';
		}
	}
    </script>

</body>

</html>