<?php
session_start();
include 'load.php';
$oid = 0;
if(isset($_POST['save'])){
    if(isset($_SESSION['order_id'])){
        $ooid = $_SESSION['order_id'];
       
        if(mysqli_num_rows(mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$ooid' AND add_to_return='1'"))>0){
                  $orderitemss = mysqli_query($conn, "SELECT * FROM temp_return_qty,mobileproducts WHERE temp_return_qty.product_id=mobileproducts.prid AND temp_return_qty.order_id='$ooid'");
                    if ($orderitemss->num_rows > 0) {
                        while($rw = $orderitemss->fetch_assoc()) {
                            $orderdetails = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobileorders WHERE order_id ='$ooid'"));
                            $datetime = date("Y-m-d H:i:s");
                            $oid = $orderdetails['orid'];
                            $amountdetails = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(return_amount) as returnamount,order_id,add_to_return FROM temp_return_qty WHERE order_id='$ooid' AND add_to_return='1'"));
                            $amount = $amountdetails['returnamount'];
                            $sql1 = "INSERT INTO tbl_return (order_id, return_datetime, return_amount)VALUES ('$oid', '$datetime', '$amount')";
                            if ($conn->query($sql1) === TRUE) {
                                $last_id = $conn->insert_id;
                               $returnitemlist = mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$ooid' AND add_to_return='1'");
                               if ($returnitemlist->num_rows > 0) {
                                    while($rw1 = $returnitemlist->fetch_assoc()) {
                                        $pid = $rw1['product_id'];
                                        $return_qty = $rw1['return_qty'];
                                        $orderr_id = $rw1['order_id'];
                                        $return_type = $rw1['return_type'];
                                        $return_reson = $rw1['return_reson'];
                                        $order_item_id = $rw1['order_item_id'];
                                        $sql2 = "INSERT INTO tbl_return_items (return_id, prid, qty,order_id,return_type,return_reson,item_id)VALUES ('$last_id', '$pid', '$return_qty', '$orderr_id','$return_type','$return_reson','$order_item_id')";
                                        if ($conn->query($sql2) === TRUE) {
                                            $last_id2 = $conn->insert_id;
                                            if($return_type==1){
                                                $stockresult = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$pid'"));
                                                $stock = $stockresult['qty'];
                                                $stock = $stock - $return_qty;
                                                $sql3 = "UPDATE tbl_stock SET qty='$stock' WHERE prid='$pid'";
                                                $conn->query($sql3);
                                                

                                               // $sql6 = "INSERT INTO tbl_stock_return (prid, return_item_id, return_qty)VALUES ('$pid', '$last_id2', '$return_qty')";
                                               // $conn->query($sql6);
                                            }else if($return_type==2){
                                                $stockresult = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$pid'"));
                                                $stock = $stockresult['qty'];
                                                $stock = $stock + $return_qty;
                                                $sql3 = "UPDATE tbl_stock SET qty='$stock' WHERE prid='$pid'";
                                                $conn->query($sql3);
                                                

                                               // $sql6 = "INSERT INTO tbl_stock_return (prid, return_item_id, return_qty)VALUES ('$pid', '$last_id2', '$return_qty')";
                                               // $conn->query($sql6);
                                            }else if($return_type==3){
                                               
                                            }
                                          //  $stockresult = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM tbl_stock WHERE prid='$pid'"));
    	
                                          
                                            //$stock = $stockresult['qty'];
                                           // $stock =+ $return_qty;
                                           // $sql3 = "UPDATE tbl_stock SET qty='$stock' WHERE prid='$pid'";

                                            

				                           // header("refresh:2;return-list.php"); 

                                        }


                                    }
                                            $sql5 = "DELETE FROM temp_return_qty";
                                            $conn->query($sql5);
                                            unset($_SESSION['order_id']);
                                            $successMSG = "Successfully! Genarate Return....";


                               }
                                

                            }
                        }
                    }
        }else{
            $errMSG = "Please Select Return Products.";
        }
    }else{
        $errMSG = "Please Select Order.";
    }
}


?>
<?php /*
    $getReturnetailsQuery=$conn->query("SELECT COUNT(*) FROM tbl_return WHERE stat='0' ORDER BY return_id DESC");
    if ($GgrnQ=$getReturnetailsQuery->fetch_array()) {
        $ReturnOngoingCount=$GgrnQ[0];
    }
	*/
?>
<!-- new added -->

<!--  -->
<?php /* if($ReturnOngoingCount=='0'){ */?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
	<meta name="description" content="POS - Eat More Resturant   | Pos & Invetory System | Dashboard">
	<meta name="keywords" content="Eat More Resturant   | Pos & Invetory System | Dashboard">
	<meta name="author" content="Eat More Resturant   | Pos & Invetory System | Dashboard">
	<meta name="robots" content="noindex, nofollow">

	<title>Home | Eat More Resturant   | Pos & Invetory System | Dashboard</title>


	<?php
	require_once 'headercss.php';
	?>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
				<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.1.0-rc.0/js/select2.min.js"></script>
</head>
<body>
	<div id="global-loader">
		<div class="whirly-loader"> </div>
	</div>

	<div class="main-wrapper">
		<?php
		require_once 'header.php';
		?>

		<?php
		require_once 'navbar.php';
		?>
		<div class="page-wrapper">
			<div class="content">
				<div class="page-header">
					<div class="page-title">
						<h4>Create Sales Return</h4>
						<h6>Add/Update Sales Return</h6>
					</div>
				</div>

                <div class="card">
					<div class="card-body">
                    <div class="page-title">
						<h6>Select Order ID</h6>
                    </div>
                    <hr>
                        <div class="col-md-4">
                                <label>Bill No/Order No.</label>
								<select name="orderid" class="form-control" id="orderid">
									<option value="">Select Order No</option>
										<?php 
                                         $orders = mysqli_query($conn, "SELECT * FROM mobileorders");
                                         $orderidlist = array();
                                         if ($orders && mysqli_num_rows($orders) > 0) {
                                             while ($row1 = mysqli_fetch_assoc($orders)) {
                                                 $oid = $row1['order_id'];
                                                 $cart = mysqli_query($conn, "SELECT * FROM mobiletemporarycart WHERE orderid='$oid'");
                                                 
                                                 if ($cart && mysqli_num_rows($cart) > 0) {
                                                     while ($row2 = mysqli_fetch_assoc($cart)) {
                                                         $itemid = $row2['tempid'];
                                                         $qty = $row2['pro_qty'];
                                         
                                                         $returnCheck = mysqli_query($conn, "SELECT * FROM tbl_return_items WHERE order_id='$oid' AND item_id='$itemid' AND qty<'$qty'");
                                                         if ($returnCheck && mysqli_num_rows($returnCheck) == 1) {
                                                            array_push($orderidlist,$oid);
                                                         }

                                                        if(mysqli_num_rows(mysqli_query($conn, "SELECT * FROM tbl_return_items WHERE order_id='$oid'"))==0){
                                                            array_push($orderidlist,$oid);
                                                        }
                                                     }
                                                 }



                                             }
                                         }

                                        $qry_new = mysqli_query($conn, "SELECT * FROM mobileorders WHERE order_id IN (" . implode(',', $orderidlist) . ")");  
										if ($qry_new->num_rows > 0) {
                                           
											while($row = $qry_new->fetch_assoc()) { 
                                               $customerid =  $row['customer'];
                                              
                                               $qry = mysqli_query($conn, "SELECT * FROM mobilecustomers WHERE coid='$customerid'");
    	                                        $rw = mysqli_fetch_array($qry);
                                                if(!empty($rw)){
                                                   $cname =  $rw['cname'];
                                                }else{
                                                    $cname = "";
                                                }
                                                if($_SESSION['order_id']==$row['order_id']){
                                                    echo "<option selected value='".$row['order_id']."'>".$row['orid']." / ".$row['pay_option']." / Rs.".$row['amount']." / ".$row['create_at']." / ".$cname."</option>";
                                                }else{
                                                    echo "<option value='".$row['order_id']."'>".$row['orid']." / ".$row['pay_option']." / Rs.".$row['amount']." / ".$row['create_at']." / ".$cname."</option>";
                                                }
												
											} 
											
										} ?>
								</select>

                        </div>
                       
                        <div class="page-title mt-5">
						    <h6>Return Item List</h6>
                         </div>
                         <hr>  
                         
                         <div class="col-md-12">
                         <div class="table-responsive">
							<table class="table  datanew">
								<thead>
									<tr>
							
										<th>#ID</th>
										
										<th>Product</th>
										<th>Order Qty</th>
										<th>Return Qty</th>
										<th>Return Type</th>
                                        <th>Return Reason</th>
                                        <th>Amount</th>
										<th>Action</th>
										
									</tr>
								</thead>
								<tbody>
                                        <?php 
                                        if(isset($_SESSION['order_id'])){
                                           
                                            $order_id = $_SESSION['order_id'];
                                           
                                            $orderitems = mysqli_query($conn, "SELECT * FROM temp_return_qty,mobileproducts WHERE temp_return_qty.product_id=mobileproducts.prid AND temp_return_qty.order_id='$order_id'");
                                            if ($orderitems->num_rows > 0) {
                                                while($row = $orderitems->fetch_assoc()) { 
                                                    $tempid = $row['order_item_id'];
                                                    $cart1 = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM mobiletemporarycart WHERE tempid ='$tempid'"));
                                                    $return1 = mysqli_fetch_array(mysqli_query($conn, "SELECT SUM(qty) as qt FROM tbl_return_items WHERE item_id ='$tempid'"));

                                                    if(!empty($return1)){
                                                       $rqty =  $return1['qt'];
                                                    }else{
                                                        $rqty = 0;
                                                    }
                                                    ?>
                                                <tr>
                                                    <td><?php echo $row['order_item_id']; ?></td>
                                                    <td><?php echo $row['proname']; ?></td>
                                                    <td><?php echo $cart1['pro_qty'] - $rqty; ?></td>
                                                    <td><input type="number" min="1" step="0.1" style="width: 60px;" class="rq_<?php echo $row['order_item_id']; ?>" id="edit_r_qty" onchange="setItemReturnQuantity(<?php echo $row['order_item_id']; ?>, this.value);" value="<?php echo $row['return_qty']; ?>"></td>
                                                    <td>
                                                        <select name="return_type" id="return_type" onchange="setItemReturnType(<?php echo $row['order_item_id']; ?>, this.value);">
                                                            <option value="1" <?php if($row['return_type']==1){ echo "selected"; } ?>>Return</option>
                                                            <option value="2" <?php if($row['return_type']==2){ echo "selected"; } ?>>Good Return</option> 
                                                            <option value="3" <?php if($row['return_type']==3){ echo "selected"; } ?>>Market Return</option> 
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input name="return_reson" type="text" id="return_reson" onchange="setItemReturnReson(<?php echo $row['order_item_id']; ?>, this.value);" value="<?php echo $row['return_reson']; ?>">    
                                                    
                                                    </td>
                                                    <td id="p_<?php echo $row['order_item_id']; ?>">Rs.<?php echo $row['return_amount']; ?></td>
                                                    <td>
                                                        <?php if($row['add_to_return']==0){ ?>
                                                            <button type="button" class="btn btn-success" onclick="setItemReturnStatus(<?php echo $row['order_item_id']; ?>, 1);">Add To Return</button>
                                                        <?php  }else{ ?>
                                                            <button type="button" class="btn btn-danger" onclick="setItemReturnStatus(<?php echo $row['order_item_id']; ?>, 0);" value="<?php echo $row['return_qty']; ?>">Remove From Return</button>
                                                        <?php } ?>
                                                       
                                                        
                                                    </td>
                                            <?php }
                                            }
                                    }
                                        ?>
                                        </tr>
                                </tbody>
                            </table>
                         </div>

                         </div>


                         <div class="col-md-12 mt-5">
                         <?php

if(isset($errMSG)){

?>
									
<div class="alert alert-danger border-0 bg-danger alert-dismissible fade show py-2">
<div class="d-flex align-items-center">
<div class="font-35 text-white"><i class="bx bxs-message-square-x"></i>
</div>
<div class="ms-3">
<h6 class="mb-0 text-white">Error Alerts</h6>
<div class="text-white"> <?php echo $errMSG; ?>!</div>
</div>
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
									
<?php

}
	
else if(isset($successMSG)){

?>
									
<div class="alert alert-success border-0 bg-success alert-dismissible fade show py-2">
<div class="d-flex align-items-center">
<div class="font-35 text-white"><i class="bx bxs-check-circle"></i>
</div>
<div class="ms-3">
<h6 class="mb-0 text-white">Success Alerts</h6>
<div class="text-white"><?php echo $successMSG; ?>!</div>
</div>
</div>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
									
<?php

}

?>    
                                    <?php 
                                       
                             //   if(isset($_SESSION['order_id'])){       
                                 //   if(mysqli_num_rows(mysqli_query($conn, "SELECT * FROM temp_return_qty WHERE order_id='$order_id' AND return_type='1'") )> 0){ ?>
                                    <!-- <a href="pos-panel.php?oid=<?php // echo $order_id; ?>" class="btn btn-primary">Genarate Return</a> -->
                                       
                                   <?php // }else{ ?>
                                    <form action="" method="post"> 
                                            <button type="submit" class="btn btn-primary" name="save">Genarate Return</button>
                                        </form>

                                       
                                     <!--   <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                            <div class="modal-dialog modal-lg">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="exampleModalLabel">Add New Products</h5>
                                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                                <span aria-hidden="true">&times;</span>
                                                            </button>
                                                    </div>
                                                    <div class="modal-body">
                                                        
                                                    </div>
                                                </div>
                                            </div>
                                        </div>   -->

                                  <?php //}
                                  
                                 //  } ?>

                                      
                         </div>




                    </div>
                </div>
















            </div>
        </div>















    	</div>
	<script>
	
	// Initialize Select2 plugin with typing search functionality

	
</script>

	<script src="assets/js/jquery-3.6.0.min.js"></script>

	<script src="assets/js/feather.min.js"></script>

	<script src="assets/js/jquery.slimscroll.min.js"></script>

	<script src="assets/js/jquery.dataTables.min.js"></script>
	<script src="assets/js/dataTables.bootstrap4.min.js"></script>

	<script src="assets/js/bootstrap.bundle.min.js"></script>

	<script src="assets/plugins/select2/js/select2.min.js"></script>

	<script src="assets/js/moment.min.js"></script>
	<script src="assets/js/bootstrap-datetimepicker.min.js"></script>

	<script src="assets/plugins/sweetalert/sweetalert2.all.min.js"></script>
	<script src="assets/plugins/sweetalert/sweetalerts.min.js"></script>
	<script src="assets/alertify/alertify.js"></script>
		<script src="assets/alertify/alertify.min.js"></script>

	<script src="assets/js/script.js"></script>
	<!-- <script src="process.js"></script> -->
	<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
<script>
    $(document).ready(function(){

        $('.openmodal').on('click', function() {
            $(".bd-example-modal-lg").modal('show');
        });
        $('.close').on('click', function() {
            $(".bd-example-modal-lg").modal('hide');
        });
        
        $('#orderid').select2();
        $('#orderid').on('change', function() {
            let orderid = $(this).val();
            $.ajax({
                type: "POST",
                data: {orderid:orderid}, 
                url: "return-orderid.php",
                    success: function(data){
                        location.reload();
                    }
                });
        });
    });

    function setItemReturnQuantity(order_item_id, qty){
            $.ajax({
                type: "POST",
                data: {order_item_id:order_item_id,qty:qty}, 
                url: "return-orderid.php",
                    success: function(data){
                      //  location.reload();
                        if(data==0){
                            alert("Return quantity should be less than order quantity!");
                            $(".rq_"+order_item_id).val("1");
                        }else{
                            $("#p_"+order_item_id).html("Rs."+data);
                        }
                        
                    }
                });
    }

    function setItemReturnType(order_item_id, return_type){
        $.ajax({
                type: "POST",
                data: {order_item_id:order_item_id,return_type:return_type}, 
                url: "return-orderid.php",
                    success: function(data){
                      //  location.reload();
                    }
                });
    }
    function setItemReturnReson(order_item_id, return_reson){
        $.ajax({
                type: "POST",
                data: {order_item_id:order_item_id,return_reson:return_reson}, 
                url: "return-orderid.php",
                    success: function(data){
                      //  location.reload();
                    }
                });
    }
    function setItemReturnStatus(order_item_id, return_status){
        $.ajax({
                type: "POST",
                data: {order_item_id:order_item_id,return_status:return_status}, 
                url: "return-orderid.php",
                    success: function(data){
                        location.reload();
                    }
                });
    }
</script>
	<!-- <script>
        
        $(document).on('submit', '#Create-Return', function(e){
        e.preventDefault(); //stop default form submission
        var formData = new FormData($(this)[0]);

        $.ajax({

                beforeSend : function() {

                    Swal.fire({
                      title:'Info !',
                      icon:'info',
                      text:'Details is being sending...Please wait.',
                      showConfirmButton:false,
                      showCancelButton:false,
                      allowOutsideClick: false,
                    });

                },

                url:"post/create_return.php",
                type: 'POST',
                data: formData,
                //async: false,
                cache: false,
                contentType: false,
                processData: false,

                success: function (data) {

                    var json=JSON.parse(data);
                    if(json.result){
                        var j_id = json.j_id;

                        setTimeout(function () {
                        
                        window.location.href = "create_return_invoice?g="+j_id;
                       //location.reload();
                    },1000);

                    }else{
                        Swal.fire({
                        title:'Warning !',
                        icon:'warning',
                        text:'Something went wrong, please try again.'
                        });
                    }

                    

                }

            });

        return false;
        });
    </script> -->


</body>
</html>