
<?php $__env->startSection('content'); ?>
<style>
  button.dt-button, div.dt-button, a.dt-button, input.dt-button {
    border-radius: 5px;
    color: white;
    background-color: rgb(197, 7, 178);
    box-shadow: rgba(50, 50, 93, 0.25) 0px 50px 100px -20px, rgba(0, 0, 0, 0.3) 0px 30px 60px -30px, rgba(10, 37, 64, 0.35) 0px -2px 6px 0px inset;
}

button.dt-button:hover:not(.disabled), div.dt-button:hover:not(.disabled), a.dt-button:hover:not(.disabled), input.dt-button:hover:not(.disabled) {
    border: 1px solid #666;
    background-color: rgb(29, 29, 29);
}
.content form {
        border: 12px solid #f8f8f8;
        background: #f4f4f4;
        padding: 30px 45px 45px;
        margin: 70px 25px 40px;
        border-radius: 5px;
        max-width: 900px;
        box-shadow: 0 1px 7px rgba(0,0,0,0.2);
    }
    .content label {
        display: block;
        font-weight: bold;
        letter-spacing: 0.02em; 
        color: #666;
        text-shadow: 0 0 0 #666;
        padding: 5px 0 8px;
    }
    .content label:not(:first-of-type) {
        margin-top: 30px;
    }
    .content select {   
        width: 100%;
        max-width: 300px;
    }

    /* LC Select - Light theme - by LCweb */


/* container */

/* .lcslt {
    display: flex
;
    align-items: center;
    flex-direction: row;
    flex-wrap: wrap;
    width: 100%;
    min-height: 15px;
    padding: 5px 30px 5px 5px;
    position: relative;
    overflow: hidden;
    font-size: 1rem;
} */

/* images */


:root{
    --file-container-bg:  #eeeeee;
    --file-bg:  #f8f8f8;
    --file-border-color: #606060;
    --file-rounded: 15px;
    --file-color: #2b2b2b;
    --table-border-color: #dbdbdb;
    --delete-button-bg: #f53636;
    --delete-button-color: #ffffff;
    --font-size: 0.875em;
    --font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    --shadow: 0px 8px 15px -8px rgba(0, 0, 0, 0.5);
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.file-container {
    width: 100%;
    font-family: var(--font-family);

    .file-upload {
        width: 100%;
        display: flex;
        background-color: var(--file-container-bg);
        border-radius: var(--file-rounded);
        transition: all 0.3s;

        &:hover {
            box-shadow: var(--shadow);
        }

        >div {
            width: 100%;
            background-color: var(--file-bg);
            padding: 25px;
            margin: 25px;
            border-radius: 10px;
            border: 1px dashed var(--file-border-color);
            text-align: center;
            cursor: pointer;

            >i {
                font-size: 3.125em;
                color: var(--file-color);
            }

            >p,
            span,
            div {
                font-size: var(--font-size);
                line-height: 30px;
                color: var(--file-color);
            }

            >div {
                width: max-content;
                padding: 0 10px;
                margin: 0 auto;
                border: 1px solid var(--file-border-color);
                border-radius: 8px;
            }
        }
    }

    >table {
        width: 100%;
        border-collapse: collapse;
        font-size: var(--font-size);
        margin-top: 20px;

        & th,
        td {
            border-bottom: 1px solid var(--table-border-color);
            padding: 8px;
            text-align: left;
        }

        >tbody {
            >tr {
                >td {
                    &:nth-child(1) {
                        font-weight: bold;
                    }

                    &:nth-child(2) {
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        overflow: hidden;
                        max-width: 1px;
                    }

                    &:nth-child(3) {
                        text-align: center;
                    }

                    >img {
                        border-radius: 5px;
                        box-shadow: var(--shadow);
                    }

                    &.no-file {
                        text-align: center;
                        font-weight: normal;
                    }

                    > i{
                        font-size: 1.125em;
                    }
                }
            }
        }

        & button {
            background-color: var(--delete-button-bg);
            width: 30px;
            height: 30px;
            border: none;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;

            &:hover {
                box-shadow: var(--shadow);
            }

            >i {
                color: var(--delete-button-color);
                font-size: 1.125em;
            }
        }
    }
}

</style>
      <!-- partial -->
      <div class="main-panel">
        <div class="content-wrapper">
          <div class="page-header">
            <h3 class="page-title">
              Dashboard
            </h3>
          </div>
          
          <div class="row grid-margin">
            <div class="col-12">
              <div class="card card-statistics">
                <div class="card-body">
                  <div class="d-flex flex-column flex-md-row align-items-center justify-content-between">
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fa fa-user mr-2"></i>
                            Customer
                        </p>
                        <h5><?php echo e($sale->name); ?></h5>
                    </div>
                   
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                            Sale References
                        </p>
                        <h5><?php echo e($sale->sale_reference); ?></h5>
                    </div>
                    <div class="statistics-item">
                      <p>
                          <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                          Total Cost
                      </p>
                      <h5><?php echo e(number_format($sale->total_cost, 2)); ?></h5>
                  </div>
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                            Total Quantity
                        </p>
                        <h5><?php echo e($sale->quantity); ?></h5>
                        
                    </div>
                   
                    
                      
                  </div>
                 
                  <hr>
                  <div class="d-flex flex-column flex-md-row align-items-center justify-content-between">
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fa fa-user mr-2"></i>
                            Other Charges
                        </p>
                        <h5><?php echo e($sale->total_other_charge); ?></h5>
                    </div>
                   
                    <div class="statistics-item">
                      <?php if(!is_null($sale->discount_amount) && $sale->discount_amount > 0): ?>
                      <p>
                          <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                          Discount Amount
                      </p>
                      <h5><?php echo e($sale->discount_amount); ?></h5> <!-- Should be discount_amount -->
                  <?php elseif(!is_null($sale->discount_percentage) && $sale->discount_percentage > 0): ?>
                      <p>
                          <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                          Discount Percentage
                      </p>
                      <h5><?php echo e($sale->discount_percentage); ?>%</h5>
                  <?php else: ?>
                  <p>
                    <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                    No Discount
                </p>
                  <?php endif; ?>
                  
                    </div>
                    <div class="statistics-item">
                      <p>
                          <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                          Total Price
                      </p>
                      <h5><?php echo e(number_format($sale->final_total_price, 2)); ?></h5>
                  </div>
                    <div class="statistics-item">
                        <p>
                            <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                            Total Profit
                        </p>
                        
                        <h5><?php echo e(number_format($sale->final_total_price - $sale->total_cost, 2)); ?></h5>
                   
                        
                    </div>
                   
                    
                      
                  </div>
                </div>
              </div>
            </div>
          </div>
         
          <div class="row grid-margin">
            <div class="col-12">
              <div class="card ">
                
                <div class="card-body">
                  <h5>Return Items</h5>
                <div class="alert">
                 
                </div>
                  <br>
                  <div class="d-flex flex-column flex-md-row align-items-center justify-content-between">
                    
                    <div class="container">
                      <div class="row">
                        <div class="col-md-6">
                          <p>
                            <i class="icon-sm fa fa-user mr-2"></i>
                            Product
                        </p>
                        <div class="search-bar">
                            <input 
                                type="text" 
                                id="searchInput" 
                                class="form-control w-100 formInputField" 
                                placeholder="Search by name or code..." 
                                autocomplete="off"
                            />
                            <ul id="suggestionList" class="suggestion-list" style="width:92%; display: none; list-style: none; border: 1px solid #ccc; padding: 5px; max-height: 200px; overflow-y: auto;">
                                <!-- Suggestions will appear here -->
                            </ul>
                        </div>
                        </div>
                        <div class="col-md-4">
                          <p>
                            <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                           Quantity
                        </p>
                          <div class="form-group">
                          
                            <input type="number" class="form-control" id="quantity" placeholder=" Quantity"  >
                          </div>
                        </div>
                       
                        <div class="col-md-2">
                            <p>
                              <i class="icon-sm fas fa-hourglass-half mr-2"></i>
                              UPDATE
                          </p>
                            <div class="form-group">
                            
                                <h2><button type="button" class="btn btn-danger btn-sm" id="adToTable">UPDATE 😊 <i class="fa fa-play-circle ml-1"></i></button></h2>
                                <label class="badge badge-outline-success badge-pill"></label>
                            </div>
                          </div>
                        
                          <div class="col-md-12">
                            <br><br>
                            <p>
                              
                             
                          </p>
                            <div class="form-group">
                                <table id="itemTable" class="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>Item Name</th>
                                            <th>Return Quantity</th>
                                            <th>Sale Quantity</th>
                                            <th>Total<br>Price</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Rows will be dynamically added here -->
                                    </tbody>
                                </table>
                            </div>
                            <div class="container">
                              <div class="row">
                                  <div class="col-sm">
                                    <label>Retun Type</label>
                                    <select name="RetunType" id="RetunType" class="form-control">
											                  <option value=" ">Select Return Type</option>
											                  <option value="Cash Return">Cash Return</option>
                                        <option value="Products Return">Products Return</option>
										                </select>
                                  </div>
                                  <div class="col-sm">
                                    <label></label>
                                    <h2><button type="button" class="btn btn-success btn-sm" id="sumbitData">SUBMIT 😊 <i class="fa fa-play-circle ml-1"></i></button></h2>
                                  </div>
    
                                </div>
                            </div>
                          
                          </div> 
                        
                        
                      </div>
                    </div>
                   
                   
                </div>
                
                </div>
              </div>
            </div>
          </div>
          <div class="content-wrapper">
           
            <div class="card">
              <div class="card-body">
                <h4 class="card-title">Data table</h4>
                <div class="row">
                  <div class="col-12">
                    <div class="table-responsive" style="overflow-x: auto; -webkit-overflow-x: auto;">
                        <table id="example" class="table table-striped table-hover table-product  nowrap" style="width: 100%; ">
                        <thead>
                          <tr>
                            
                            <th >Name</th>
                            <th >Quantity</th>
                            <th>Price</th>
                            <th>Subtotal</th>
                            <th>Warranty Period</th> 
                            <th>Days Left</th> 
                          </tr>
                        </thead>
                        <tbody>
												
                            <?php $__currentLoopData = $saleProduct; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <tr data-id="<?php echo e($product->badgstock_id); ?>"   data-badgstock_id="<?php echo e($product->badgstock_id); ?>" data-item_id="<?php echo e($product->itemId); ?>"  data-each_cost="<?php echo e($product->cost); ?>"   data-type="<?php echo e($product->type); ?>"  data-warrantystatus="<?php echo e($product->warranty_status); ?>" data-Warrantyperiod="<?php echo e($product->warranty_period); ?>"  style="box-shadow: rgba(17, 17, 26, 0.1) 0px 1px 0px;">
                                <td  ><?php echo e($product->product_name); ?>

                                    
                                    <br> (<?php echo e($product->code); ?>)</td>
                             
                                <td style="padding:5px; margin:15px;"><?php echo e($product->quantity); ?></td>
                                <td style="padding:5px; margin:15px;"><?php echo e($product->price); ?></td> <!-- Assuming 'price' is a column in your sale_products table -->
                                <td class="total-value" style="padding:5px; margin:15px;"> <?php echo e($product->quantity * $product->price); ?></td> <!-- Calculate subtotal -->
                               
                                <td> <?php echo e($product->warranty_period); ?></td>  
                                <td>
                                    
                                        <?php
                                            $warranty_end_date = null;
            
                                            switch ($product->warranty_period) {
                                                case '01 Month':
                                                    $warranty_end_date = \Carbon\Carbon::parse($product->date)->addMonth();
                                                    break;
                                                case '03 Months':
                                                    $warranty_end_date = \Carbon\Carbon::parse($product->date)->addMonths(3);
                                                    break;
                                                case '06 Months':
                                                    $warranty_end_date = \Carbon\Carbon::parse($product->date)->addMonths(6);
                                                    break;
                                                case '01 Year':
                                                    $warranty_end_date = \Carbon\Carbon::parse($product->date)->addYear();
                                                    break;
                                            }
            
                                            $days_left = $warranty_end_date ? now()->diffInDays($warranty_end_date, false) : 0;
                                        ?>
            
                                        <?php echo e($days_left > 0 ? "$days_left days left" : 'Warranty expired'); ?>

                                    
                                </td>
                              
                                
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        
                        
                        </tbody>
                      </table>
                    </div>
                    
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-12">
              <div class="card">
                <div class="card-body">
                  <div class="d-md-flex justify-content-between align-items-center">
                    <div class="d-flex align-items-center mb-3 mb-md-0">
                      <button class="btn btn-social-icon btn-facebook btn-rounded">
                        <i class="fab fa-facebook-f"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Facebook</h5>
                        <p class="mb-0">813 friends</p>
                      </div>
                    </div>
                    <div class="d-flex align-items-center mb-3 mb-md-0">
                      <button class="btn btn-social-icon btn-twitter btn-rounded">
                        <i class="fab fa-twitter"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Twitter</h5>
                        <p class="mb-0">9000 followers</p>
                      </div>
                    </div>
                    <div class="d-flex align-items-center mb-3 mb-md-0">
                      <button class="btn btn-social-icon btn-google btn-rounded">
                        <i class="fab fa-google-plus-g"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Google plus</h5>
                        <p class="mb-0">780 friends</p>
                      </div>
                    </div>
                    <div class="d-flex align-items-center">
                      <button class="btn btn-social-icon btn-linkedin btn-rounded">
                        <i class="fab fa-linkedin-in"></i>
                      </button>
                      <div class="ml-4">
                        <h5 class="mb-0">Linkedin</h5>
                        <p class="mb-0">1090 connections</p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- content-wrapper ends -->
        <!-- partial:../../partials/_footer.html -->
        <footer class="footer">
          <div class="d-sm-flex justify-content-center justify-content-sm-between">
            <span class="text-muted text-center text-sm-left d-block d-sm-inline-block">Copyright © 2025  <a href="https://www.urbanui.com/" target="_blank">Urbanui</a>. All rights reserved.</span>
            <span class="float-none float-sm-right d-block mt-1 mt-sm-0 text-center">Hand-crafted & made with <i class="far fa-heart text-danger"></i></span>
          </div>
        </footer>
        <!-- partial -->
      </div>
      <div class="modal fade" id="exampleModal-2" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel-2" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header" style="background-color: rgb(44, 3, 114)">
              <h5 class="modal-title" id="exampleModalLabel-2" style="color: white">Modal title</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"  style="color: white">
                <span aria-hidden="true"  style="color: white; ">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form class="forms-sample">
                <div class="form-group">
                  <label for="exampleInputUsername1">Category</label>
                  <input type="text" class="form-control" id="Category" placeholder="Ad Category">
                </div>
                
                  
                <div class="form-group">
                  <label for="description">Description</label>
                  <textarea id="description" name="" rows="4" cols="50"></textarea>
                </div>
            
                <div class="form-group">
                  <div class="form-check form-check-flat form-check-primary">
                    <label class="form-check-label">
                      <input type="checkbox" class="form-check-input">
                      Remember me
                    </label>
                  </div>
                </div>
                
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary store">Submit</button>
              <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
            </div>
          </div>
        </div>
      </div>

    <script>
const urlParams = new URLSearchParams(window.location.search);

const sale_id = urlParams.get('id');
$( document ).ready(function() {

    var productExsistingQuantity;
var productID;

$('#searchInput').on('input', function () {
    var id = sale_id; 
    const searchTerm = $(this).val().trim();

    if (searchTerm.length >= 2) {
        $.ajax({
            url: `/search-sale-product-for-return/${id}`, // Endpoint to handle search requests
            method: 'GET',
            data: { query: searchTerm }, // Send the search term to the server
            success: function (data) {
    console.log(data);

    $('#suggestionList').hide();
    $('.SalesCreate').show();
    $('.productDivBox').hide();

    const suggestions = Object.values(data.suggestions); // Convert to array
    const suggestionList = $('#suggestionList');
    suggestionList.empty(); // Clear existing suggestions

    if (suggestions.length === 1) {
        const item = suggestions[0];

        $('#searchInput')
            .val(`${item.name.trim()} (${item.imu_number.trim()}) (${item.each_cost.trim()})`)
            .attr('data-id', item.id)
            .attr('data-quantity', item.quantity)
            .attr('data-badgstock_id', item.badgstock_id)
            .attr('data-each_cost', item.each_cost)
            .attr('data-type', item.type)
            .attr('data-imu_number', item.imu_number)
            .attr('data-item_id', item.itemId)
            .attr('data-price', item.price)
            .attr('data-name', item.name);

        suggestionList.hide();
        productExsistingQuantity = item.quantity;
        productID = item.id;

    } else if (suggestions.length > 1) {
        suggestions.forEach(item => {
            suggestionList.append(
                `<li data-id="${item.id}" data-price="${item.price}" 
                data-quantity="${item.quantity}"
                data-badgstock_id="${item.badgstock_id}"
                data-each_cost="${item.each_cost}"
                data-type="${item.type}" 
                data-imu_number="${item.imu_number}" 
                data-item_id="${item.itemId}"
                data-name="${item.name}" 
                class="suggestion-item">
                ${item.name.trim()} (${item.imu_number.trim()}) cost : (${item.each_cost.trim()})  
            </li>`
            );
            productExsistingQuantity = item.quantity;
        });
        suggestionList.show();
    } else {
        suggestionList.hide();
    }
},
            error: function (error) {
                console.error('Error fetching suggestions:', error);
            }
        });
    } else {
        $('#suggestionList').hide();
		 // Hide suggestions if input is less than 2 characters
    }
});



$(document).on('click', '.suggestion-item', function () {
    const selectedId = $(this).data('id'); // Get data-id from clicked item
    const selectedText = $(this).text().trim(); // Get the text of the clicked item
	const quantity = $(this).data('quantity'); 
	const price = $(this).data('price'); 
	const name = $(this).data('name'); 
	const badgstock_id = $(this).data('badgstock_id'); 
	
	const each_cost = $(this).data('each_cost');
	const type = $(this).data('type');
	const imu_number = $(this).data('imu_number'); 
	const itemId = parseInt($(this).data('item_id'));

    $('#searchInput')
        .val(selectedText) // Set the input value to the selected text
        .attr('data-id', selectedId)
		.attr('data-quantity', quantity)
		.attr('data-badgstock_id', badgstock_id)
		.attr('data-each_cost', each_cost)
		.attr('data-type', type)
		.attr('data-imu_number', imu_number)
		.attr('data-item_id', itemId)
		.attr('data-price', price)
		.attr('data-name', name);	
		
		// Set the data-id to the input field
		$("#quantity").attr("max", quantity);
	

    $('#suggestionList').hide(); // Hide the suggestion list

	$("#amount").val(price);


});

    // Hide the suggestion list when the input field loses focus
    $('#searchInput').on('blur', function () {
        setTimeout(() => {
            $('#suggestionList').hide();
        }, 200); // Delay to allow click events on suggestions to be registered
    });



    var table = $('#itemTable').DataTable({
        dom: "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],
        processing: true,
        info: true,
        responsive: true,
        lengthMenu: [
            [10, 25, 50, 100, 200, -1],
            [10, 25, 50, 100, 200, "All"]
        ]
    });

    var mortgageDataArray = []; // Create an empty array to store the data
    var totalSum ;
    var totalCost ;
    var totalQuantity ;
    // var saleAmount = parseFloat('{$salesList->total}');

    // function calculateTotals() {
    // totalQuantity = 0;
    // totalCost = 0;
    // mortgageDataArray.forEach(function (data) {
    //     totalQuantity += data.quantity;
    //     totalSum += data.totalPrice;
    // });
// }
    
$("#adToTable").click(function () {
    // Get values from the selected product
    let saleQuantity = parseInt($("#searchInput").attr("data-quantity"));
    let each_cost = $("#searchInput").attr("data-each_cost");
    let price = parseFloat($("#searchInput").attr("data-price"));
    let name = $("#searchInput").attr("data-name");
    let item_id = $("#searchInput").attr("data-item_id");
    let imu_number = $("#searchInput").attr("data-imu_number");
    let badgstock_id = $("#searchInput").attr("data-badgstock_id");
    let type = $("#searchInput").attr("data-type");
    
    let subtotal = saleQuantity * price;
    let quantity = parseInt($("#quantity").val());
    let productid = parseFloat($("#searchInput").attr("data-id"));
    
    // Entered quantity

    let totalPrice = price * quantity;
    let actualSubtotal = parseFloat(subtotal - totalPrice);
    let actualQuantity = saleQuantity - quantity;

    // Validation: Check if quantity is valid
    if (!quantity || quantity <= 0) {
        alert("Please enter a valid quantity.");
        return;
    }

    // Validation: Check if entered quantity exceeds sale stock
    if (parseInt(quantity) > saleQuantity) {
        $(".alert").html(`
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                Entered quantity exceeds the available sale stock (${saleQuantity})!
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        `);
        return;
    }

    $(".alert").hide().html("");

    // Check if type == "product"
    if (type === "product") {
        let exists = false;
        $("#itemTable tbody tr").each(function () {
            if ($(this).attr("data-badgstock_id") === badgstock_id) {
                exists = true;
                return false; // Break loop
            }
        });

        if (exists) {
          $("#searchInput").val("");
          $("#quantity").val("");
            alert("This product already exists in the table.");
            return;
        }
    }

    // Check if type == "product item" and check if imu_number exists
    if (type === "product item") {
        let exists = false;
        $("#itemTable tbody tr").each(function () {
            if ($(this).attr("data-imu_number") === imu_number) {
                exists = true;
                return false; // Break loop
            }
        });

        if (exists) {
          $("#searchInput").val("");
          $("#quantity").val("");
            alert("This product item with IMU number already exists in the table.");
            return;
        }
    }

    alert(each_cost);
    // Prepare row data
    var rowData = {
        item_id: item_id,
        type: type,
        name :name,
        imu_number :imu_number,
        badgstock_id: badgstock_id,
        saleQuantity: saleQuantity,
        quantity: quantity,
        each_cost:each_cost,
        totalPrice: totalPrice,
        productid: productid,
        actualSubtotal: actualSubtotal,
        actualQuantity: actualQuantity,
    };

    // Add to data array
    mortgageDataArray.push(rowData);
    console.log(mortgageDataArray);

    // Append data to the DataTable
    var rowNode = table.row.add([
        name + " " + imu_number,
        quantity,
        saleQuantity,
        totalPrice,
        "<button type='button' class='btn-remove-row btn btn-danger btn-sm'><i class='fa fa-trash'></i></button>"
    ]).draw().node();

    $(rowNode).attr("data-type", type);
    $(rowNode).attr("data-badgstock_id", badgstock_id);
    $(rowNode).attr("data-item_id", item_id);
    $(rowNode).attr("data-imu_number", imu_number);
    $(rowNode).attr("data-productid", productid);
    // Calculate totals
    totalSum = mortgageDataArray.reduce((sum, item) => sum + parseFloat(item.totalPrice), 0);
    totalQuantity = mortgageDataArray.reduce((sum, item) => sum + parseFloat(item.quantity), 0);
    totalCost = mortgageDataArray.reduce((sum, item) => sum + parseFloat(item.each_cost), 0);

    console.log("Total Sum of Prices: ", totalSum.toFixed(2));
    console.log("Total Sum of quantity: ", totalQuantity.toFixed(2));
    console.log("Updated Total cost : ", totalCost.toFixed(2));

    // Reset the dropdowns and fields
    $("#searchInput").val("");
    $("#quantity").val("");
});


   
    // Handle row removal dynamically
    $('#itemTable tbody').on('click', '.btn-remove-row', function () {
    // var row = table.row($(this).parents('tr'));
    var row = $(this).closest('tr'); // Get the parent row
    var type = row.attr("data-type");
    var badgstock_id = row.attr("data-badgstock_id");
    var item_id = row.attr("data-item_id");
    var productid = row.attr("data-productid");
 
    

    // Find and remove the corresponding entry in mortgageDataArray
    if(item_id !=null){
		var index = mortgageDataArray.findIndex(item => item.item_id === item_id);
		if (index !== -1) {
			mortgageDataArray.splice(index, 1); // Remove the item from the array
		
			console.log(mortgageDataArray)
		}
	}
	else if(productid != null){
		var index = mortgageDataArray.findIndex(item => item.badgstock_id === productid);
		if (index !== -1) {
				mortgageDataArray.splice(index, 1); // Remove the item from the array
			
				console.log(mortgageDataArray)
		}
	}
	
    // Remove the row containing the clicked delete button
    // row.remove();
    // Remove row from table
    row.remove();

    // Recalculate the total sum
    totalSum = mortgageDataArray.reduce(function (sum, item) {
        return sum + parseFloat(item.totalPrice);
    }, 0);

    // Recalculate the total quantity
    totalQuantity = mortgageDataArray.reduce(function (sum, item) {
        return sum + parseInt(item.quantity);
    }, 0);

    totalCost = mortgageDataArray.reduce(function (sum, item) {
        return sum + parseInt(item.each_cost);
    }, 0);

    // Log the updated total sum and quantity
    console.log("Updated Total Sum of Prices: ", totalSum.toFixed(2));
    console.log("Updated Total Sum of Quantity: ", totalQuantity.toFixed(2));
    console.log("Updated Total cost : ", totalCost.toFixed(2));
});


    var saleId = sale_id;
 
    $(document).on('change','#Category', function(){
        company = $('#company').val();
    });

    $(document).on('click', '#sumbitData', function () {   
      
    var RetunType  = $('#RetunType').val();



        var isValid = true;
            var errorMessage = '';

            // Perform individual validation checks for each input field
        if (!RetunType || RetunType.length === 0) {
            errorMessage += 'Retun Type is required.<br>';
            isValid = false;
        }
        
        if (!isValid) {
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    html: errorMessage,
                    showCloseButton: true,
                    showCancelButton: false,
                    focusConfirm: false,
                    confirmButtonText: 'OK',
                });
                return;
      }else{

        
    var form_data = new FormData();
    form_data.append('_token', $('meta[name="csrf-token"]').attr('content')); 
    form_data.append('saleId', saleId);    
    form_data.append('totalSum', totalSum); 
    form_data.append('totalQuantity', totalQuantity); 
    form_data.append('totalCost', totalCost); 
    form_data.append('RetunType', RetunType); 
    
    
    

    $.each(mortgageDataArray, function(i, rowData) {
              form_data.append('mortgageData[' + i + '][type]', rowData.type);
              form_data.append('mortgageData[' + i + '][saleQuantity]', rowData.saleQuantity);
              form_data.append('mortgageData[' + i + '][quantity]', rowData.quantity);
              form_data.append('mortgageData[' + i + '][name]', rowData.name);
              form_data.append('mortgageData[' + i + '][imu_number]', rowData.imu_number);
              form_data.append('mortgageData[' + i + '][item_id]', rowData.item_id); 
              form_data.append('mortgageData[' + i + '][totalPrice]', rowData.totalPrice);
              form_data.append('mortgageData[' + i + '][badgstock_id]', rowData.badgstock_id);
              form_data.append('mortgageData[' + i + '][productid]', rowData.productid);
              form_data.append('mortgageData[' + i + '][actualSubtotal]', rowData.actualSubtotal); 
              form_data.append('mortgageData[' + i + '][actualQuantity]', rowData.actualQuantity);
              form_data.append('mortgageData[' + i + '][each_cost]', rowData.each_cost);
     
    });

   
    $.ajax({
      url: '<?php echo e(route('return_sale_product')); ?>',
        method: 'POST',
        data: form_data,
        contentType: false,
        processData: false,
        success: function (response) {
        Swal.fire(
            'Good job!',
            response.message,
            'success'
        ).then((result) => {
            if (result.isConfirmed) {
                window.location.reload(); 
            }
        });
    },
    error: function (xhr, status, error) {
        console.error('Error:', error);
        Swal.fire(
            'Error!',
            'Something went wrong. Please try again later.',
            'error'
        );
    }
});
      }



});
 
  $('#example').DataTable({
            dom: "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-4'B><'col-sm-12 col-md-4'f>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
           
            buttons: [
        'copy', 'csv', 'excel','pdf',
       
        
        'print'
    ],

    processing: true,
    info: true,
    responsive: true,
    lengthMenu: [
        [10, 25, 50, 100, 200, -1],
        [10, 25, 50, 100, 200, "All"]
    ],
           

           
            createdRow: function(row, data, dataIndex) {
            
                $(row).css('font-size', '15px');
           
        }
        });

        $(document).on('click', '.view', function() {
            var id = $(this).data('id');
            

            var url = '/purchases_data?id=' + id;
            window.location.href = url;
        });

        // $(document).on('click', '.delete', function() {
        // var id = $(this).data('id');

        //     const swalWithBootstrapButtons = Swal.mixin({
        //         customClass: {
        //             confirmButton: 'btn btn-success',
        //             cancelButton: 'btn btn-danger'
        //         },
        //         buttonsStyling: false
        //     })

        //     swalWithBootstrapButtons.fire({
        //         title: 'Are you sure?',
        //         text: "You won't be able to revert this!",
        //         icon: 'warning',
        //         showCancelButton: true,
        //         confirmButtonText: 'Yes, Do it!',
        //         cancelButtonText: 'No, cancel!',
        //         reverseButtons: true
        //     }).then((result) => {
        //         if (result.isConfirmed) {
        //             $.ajax({
        //                 url: "/delete-expenses-category",
        //                 headers: {
        //                     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        //                 },
        //                 type: "POST",
        //                 data: JSON.stringify({
        //                     'id': id
        //                 }),
        //                 contentType: "application/json",
        //                 success: function(response) {
        //                     window.location.reload();
        //                 },
        //             });
        //             swalWithBootstrapButtons.fire(
        //                 'Payment Deleted!',
        //                 'Your Payment has been Deleted.',
        //                 'success'
        //             )
        //         } else if (
        //             /* Read more about handling dismissals below */
        //             result.dismiss === Swal.DismissReason.cancel
        //         ) {
        //             swalWithBootstrapButtons.fire(
        //                 'Cancelled',
        //                 'Your imaginary file is safe  😇 ',
        //                 'error'
        //             )
        //         }
        //     })

        // });

        new lc_select(document.querySelector('#product'), {
        wrap_width: '100%',
        min_for_search: 2,
        pre_placeh_opt: true,
    });

    document.querySelector('#product').addEventListener('change', function () {
    const selectedOption = this.options[this.selectedIndex]; // Get selected option
    const maxQuantity = parseInt(selectedOption.getAttribute('data-quantity')); // Convert to integer
    
    const quantityInput = document.querySelector('#quantity');
    quantityInput.max = maxQuantity; // Set max value
    quantityInput.value = ''; // Clear any previously entered value
    quantityInput.placeholder = `Max: ${maxQuantity}`; // Update placeholder with max value
});

   
});
      
      </script>
<?php $__env->stopSection(); ?>
      <!-- main-panel ends -->
    
<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\Users\USER\Desktop\laravel Chat\Sunsmart pety cash\susmart\resources\views/Section/POS/Sale/saleDataReturn.blade.php ENDPATH**/ ?>