<?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"];
	$whr1="md5(id)='$uid' and session_login_id = '".$_SESSION['login_id']."'";
$get=$objIms->getRows('view_sales_master',$whr1);
$salesmas_id=$get["id"];
$sale_no=$get["sale_no"];
$sales_type=$get["sales_type"];
$client_name=$get["client_name"];
$client_address=$get["client_address"];
$client_tin=$get["tin_no"];
$saledt=$objIms->IntToDate($get["stampdate"]);

	}
$sql_acc="SELECT * from tbl_account where session_login_id = '".$_SESSION['login_id']."' and mas_id='$salesmas_id' and sales_type='Sales' 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_sales_return_mstr(salesmas_id,stampdate,user_id,return_date,session_login_id) values('$salesmas_id','$stampdate','$user_id','$ret_date','".$_SESSION['login_id']."')";
				
				$res_insmas=mysql_query($sql_insmas);
				$lastid=mysql_insert_id();
				
				$ret_no='SELLRET/'.date('M').'/'.date('Y').'/'.$lastid;
				$sql_upmas="Update tbl_sales_return_mstr set salereturn_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++)
					{
					$item_id=$_POST["item_id".$str];
					$unit_id=$_POST["unit_id".$str];
					$ret_qty=$_POST["ret_qty".$str];
					$discount=$_POST["discount".$str];					
					$sell_price=$_POST["sell_price".$str];
					$cgst=$_POST["cgst".$str];
					$sgst=$_POST["sgst".$str];
					$igst=$_POST["igst".$str];
						if($ret_qty>0 or $ret_qty<>'')
						{
						
						$sql4="insert into tbl_sales_return_details(salesretmas_id,item_id,ret_qty,unit_id,discount,sell_price,cgst,sgst,igst,session_login_id)values('$lastid','$item_id','$ret_qty','$unit_id','$discount','$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 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 sell_price='$sell_price'";
							mysql_query($update);
							}
						}
					}
					
					$totdiscount=$_POST["totdis"];
					$invoice_no=$objIms->trasaction_no();
					if($payment='Cash' || $payment='Cheque'){
					  if($payment_mode=='cash'){

					 $sql_cash="insert into cash_detail(sales_type, cr_amount, sales_mas_id, stampdate, session_login_id)  values('Sale_Return', 'totalamount', '$lastid', '$stampdate', '".$_SESSION['login_id']."');";
					 $res_cash=mysql_query($sql_cash);

					 $sql_ins1="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Dr_Amt,sales_type,cash_type,clear,discount, grand_tot, session_login_id) values('$invoice_no','$lastid','$stampdate','$totalamount','$totalamount','Sales Return','Cash',1,'$totdiscount','$totalamount', '".$_SESSION['login_id']."')";
				
				     $res_ins1=mysql_query($sql_ins1);
				 }
					 else{
						$sql_bank="insert into tbl_bank(head, credit, stampdate, session_login_id)  values('Sale_Return', '$totalamount', '$stampdate', '".$_SESSION['login_id']."');";
					    $res_bank=mysql_query($sql_bank);
 
					    $sql_ins2="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Dr_Amt,sales_type,cash_type,clear,discount, grand_tot, session_login_id) values('$invoice_no','$lastid','$stampdate','$totalamount','$totalamount','Sales Return','Cash',1,'$totdiscount','$totalamount', '".$_SESSION['login_id']."')";
				
				        $res_ins2=mysql_query($sql_ins2);
				 }
					}
					else{

						$sql_ins3="insert into tbl_account(invoice_no,mas_id,trans_date,actual_amt,Dr_Amt,sales_type,cash_type,clear,discount, grand_tot, session_login_id) values('$invoice_no','$lastid','$stampdate','$totalamount','$totalamount','Sales Return','Cash',1,'$totdiscount','$totalamount', '".$_SESSION['login_id']."')";
				
				        $res_ins3=mysql_query($sql_ins3);
			      $sql_ret="insert into client_details(client_id, cr_amount, sell_mstr_id,head, stampdate, session_login_id) values('$salesmas_id','$totalamount', '$lastid','$stampdate', 'Sale_Return', '".$_SESSION['login_id']."')";
				$res_ret=mysql_query($sql_ret); 
			    		
			}
				?>
<script type="text/javascript">
	alert('Success');
</script>
				<?php
			header("location:salereturn_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;}
.text_style1 {font-family:Arial, Helvetica, sans-serif; font-weight:bold; font-size:12px;}


-->
</style>

<script language="javascript" type="text/javascript">
function chkqty(str)
{
var orderqty=$('#rest_qty'+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;
	}
	if(show==0)
	{
	$(':input[type="submit"]').prop('disabled',false);
	}
}


function amtsum(value,ctr)
{
var discount=$("#discount"+ctr).val();
var sell_price=$("#sell_price"+ctr).val();
var price=eval(value)*eval(sell_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>

							<h3>Sale 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></h3>
<form id="form1" name="form1" method="post" action="">
<table width="100%" class="table table-bordered" cellpadding="4">
  <tr>
    <td height="38" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>Sale   No</strong></td>
    <td nowrap="nowrap" bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td nowrap="nowrap" bgcolor="#FFFFFF" ><?php echo $sale_no;?></td>
    <td width="8%" height="38" nowrap="nowrap"><strong>Client Name<span style="color:#F00; font-weight:bold;">*</span> </strong></td>
    <td width="2%"><strong>:</strong></td>
    <td width="31%"><?php echo $client_name;?></td>
    </tr>
  <tr>
    <td width="7%" height="34" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>Sales Date </strong></td>
    <td width="1%" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td width="28%" nowrap="nowrap" bgcolor="#FFFFFF" >
       <?php echo $saledt;?></td>
    <td nowrap="nowrap"><span class="text_style1">Client Address </span></td>
    <td><strong>:</strong></td>
    <td><?=$client_address?></td>
    </tr>
  <tr>
    <td height="34" nowrap="nowrap" bgcolor="#FFFFFF" ><strong>Return Date</strong></td>
    <td nowrap="nowrap" bgcolor="#FFFFFF" ><strong>:</strong></td>
    <td nowrap="nowrap" bgcolor="#FFFFFF" ><?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" /></td>
    <td nowrap="nowrap">&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>

     <div class="panel">
            <div class="panel-heading"><strong>Item List of Sale </strong></div>
            <p>&nbsp;</p>
            <table width="100%" class="table table-striped">
		
            <?php
  $sql_viewtmp="select *  from view_sales_detail where salesmas_id=$salesmas_id and session_login_id = '".$_SESSION['login_id']."'";
				$res_viewtmp=mysql_query($sql_viewtmp);
				if(mysql_num_rows($res_viewtmp)>0)
				{ 
					$i=1;
					$sum=0;
  ?>
  <tr>
   
    <td width="13%"><span class="text_style1">Item Name</span></td>
   
    <td width="8%"><span class="text_style1">Order Qty</span></td>
    <td width="11%"><span class="text_style1">Price(Pc)</span></td>
    <td width="10%"><strong>Total</strong></td>
    <td width="16%"><strong>Discount(in %)</strong></td>
    <th width="20%" align="left" nowrap="nowrap">CGST(%)</th>
    
    <th width="20%" align="left" nowrap="nowrap">SGST(%)</th>
   
    <th width="20%" align="left" nowrap="nowrap">IGST(%)</th>
    
    <th width="20%" align="left" nowrap="nowrap">Total Price</th>
    <th width="6%" align="left" nowrap="nowrap">Rest qty </th>
    <th width="6%" align="left" nowrap="nowrap">Stock</th>
    <th width="6%" align="left" nowrap="nowrap">Return Qty </th>
    <th width="9%" align="left" nowrap="nowrap">Total </th>
  </tr>
  <?php
  $sum=0;
  $totdis=0;
  while($rows=mysql_fetch_assoc($res_viewtmp))
					{
					
					$sumretsql="select sum(ret_qty) as ret_qty from view_saleret_masdet where session_login_id = '".$_SESSION['login_id']."' and salesmas_id=".$rows["salesmas_id"]." and item_id=".$rows["item_id"]." and unit_id=".$rows["unit_id"]." and sell_price=".$rows["unit_price"];	
				$sumretexe=mysql_query($sumretsql);
				$sumretrw=mysql_fetch_array($sumretexe);
				$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 sell_price=".$rows["unit_price"];	
				$sumstockexe=mysql_query($sumstocksql);
				$sumstockrw=mysql_fetch_array($sumstockexe);
				$sumstock=$sumstockrw["stoct_qty"];
				if($sumstock<>''){$sumstock=$sumstock;}else{$sumstock=0;}
  ?>
  <tr>
    
    <td><?=$rows["item_name"]?><input type="hidden" name="item_id<?=$i?>" id="item_id<?=$i?>"  value="<?php echo $rows["item_id"];?>"  />
    <input type="hidden" name="unit_id<?=$i?>" id="unit_id<?=$i?>"  value="<?php echo $rows["unit_id"];?>"  /></td>
    <td><?=$rows["qty"]?></td>
    <td><span class="text_style"><input type="hidden" name="sell_price<?=$i?>" id="sell_price<?=$i?>"  value="<?php echo $rows["unit_price"];?>"  />
      <?=$rows["unit_price"]?>
    </span></td>
    <td><?php echo $totsum=($rows["unit_price"]*$rows["qty"]);?></td>
    <td><?php $discount=$totsum*($rows["discount"]/100); echo $rows["discount"]; $totdis=$totdis+$discount; $totprice=$totsum-$discount;?><input type="hidden" name="discount<?=$i?>" id="discount<?=$i?>"  value="<?php echo $rows["discount"];?>"  /></td>
    
    <td width="20%" nowrap="nowrap"><input type="hidden" name="cgst<?=$i?>" id="cgst<?=$i?>"  value="<?php echo $rows["cgst"];?>">
        <?php echo $rows["cgst"];?><?php  $cgst=$totprice*($rows["cgst"]/100);  number_format($cgst,2);?></td>
  
    <td width="20%" nowrap="nowrap"><input type="hidden" name="sgst<?=$i?>" id="sgst<?=$i?>"  value="<?php echo $rows["sgst"];?>">
        <?php echo $rows["sgst"];?><?php  $sgst=$totprice*($rows["sgst"]/100);  number_format($sgst,2);?></td>
    
    <td width="20%" nowrap="nowrap"><input type="hidden" name="igst<?=$i?>" id="igst<?=$i?>"  value="<?php echo $rows["igst"];?>">
        <?php echo $rows["igst"];?><?php  $igst=$totprice*($rows["igst"]/100);  number_format($igst,2);?></td>
   
    <td nowrap="nowrap"><?php   $totamt=$totprice+$cgst+$sgst+$igst; echo number_format($totamt,2);?></td>
	<td nowrap="nowrap"><input type="text" name="rest_qty<?=$i?>" id="rest_qty<?=$i?>" readonly="" value="<?=$rows["qty"]-$sumret?>" style="width:55px;" /></td>
    <td nowrap="nowrap"><input type="text" name="stock<?=$i?>" id="stock<?=$i?>" style="width:65px;" readonly="" value="<?=$rows["qty"]-$sumret?>" /></td>
    <td nowrap="nowrap"><input type="text" name="ret_qty<?=$i?>" id="ret_qty<?=$i?>" onkeypress="return isNumber(event)" style="width:55px;" onblur="chkqty(<?=$i?>);amtsum(this.value,<?=$i?>)" /></td>
    <td nowrap="nowrap"><input type="text" name="totprice<?=$i?>" id="totprice<?=$i?>" style="width:65px;" readonly="" value="0" /></td>
  </tr>
  <?php $sum=$sum+$totprice; $i++;}}?>
  <tr>
    <td height="27" colspan="12" align="right" class="text_style1">Total:</td>
	<td nowrap="nowrap"><input type="hidden" name="totdis" id="totdis" style="width:75px;"  value="<?=$totdis?>" /><input type="text" name="totamt" id="totamt" style="width:75px;" readonly="" value="0" /><input type="hidden" name="count" id="count"  value="<?=$i?>" style="width:75px;" /></td>
  </tr>
           </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_mode"]=='$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 src="../js/select2.js"></script>
		<script type="text/javascript"></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>
		<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];
				var cgst = data[6];
				var sgst = data[7];
				var igst = data[8];
				
				$('#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 type="text/javascript">
		 function isNumber(evt){
	    var charCode = (evt.which) ? evt.which : event.keyCode
	    if (charCode > 31 && (charCode < 48 || charCode > 57))
	    return false;
	    return true;
}
		</script>


</script>
</body>

</html>
