

<?php $__env->startSection('content'); ?>
<style>
  .lcslt {
   background-color: #cccccc1b !important;
}
.lcslt-placeholder {
    color: rgb(251, 251, 251) !important;
    line-height: normal;
    padding-bottom: 5px;
}
.lcslt > span:not(.lcslt-placeholder):not(.lcslt-multi-callout), #lc-select-dd li {
    color: #e9e9e9 !important;
}
#lc-select-dd li {
    width: 100%;
    margin: 0;
    background-color: #0f2242d1 !important;
}

.lcslt-search-li input[type=text], .lcslt-search-li input[type=text]:hover, .lcslt-search-li input[type=text]:active, .lcslt-search-li input[type=text]:focus, .lcslt-search-li input[type=text]:focus-visible {
    /* border: none; */
    background-color: #0f224284 !important;
    /* outline: none; */
}
.suggestion-list {
    display: none; /* Initially hidden */
    list-style: none;
    border: 1px solid #ccc;
    padding: 0; /* Remove default padding */
    margin: 0; /* Remove default margin */
    max-height: 200px; /* Limit height for scrollable area */
    overflow-y: auto; /* Enable vertical scrolling */
    background-color: #fff; /* White background */
    z-index: 1000; /* Ensure it's above other elements */
    position: absolute; /* Position relative to input */
    width: 100%; /* Match the input width */
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* Add a subtle shadow */
}

.suggestion-item {
    padding: 10px; /* Add some padding for clickability */
    cursor: pointer;
    border-bottom: 1px solid #ddd; /* Separator between items */
}

.suggestion-item:last-child {
    border-bottom: none; /* Remove border for the last item */
}

.suggestion-item:hover {
    background-color: #f1f1f1; /* Highlight on hover */
}


.card3 {
  /* max-width: 300px;
  min-height: 200px; */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border: 1px solid rgba(255, 255, 255, .25);
  /* background-color: rgb(0 147 478 / 66%); */
  /* background-color: rgba(255, 255, 255, 0.45) */
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.25);

  backdrop-filter: blur(15px);
}

.card2 {
  /* max-width: 300px;
  min-height: 200px; */
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  /* max-width: 500px;
  height: 300px; */
  /* padding: 35px; */

  border: 1px solid rgba(255, 255, 255, .25);
  /* border-radius: 20px; */
  /* background-color: rgba(255, 255, 255, 0.45); */
  /* background-color: rgb(110 42 255 / 66%); */
  /* background-color: rgb(52 0 164 / 66%); */
  background-color: rgb(24 24 24 / 22%);
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.25);

  backdrop-filter: blur(15px);
}

.formInputField::placeholder {
    color: white;
    
}
select.form-control,
select.asColorPicker-input,
.dataTables_wrapper select,
.jsgrid .jsgrid-table .jsgrid-filter-row select,
.select2-container--default select.select2-selection--single,
.select2-container--default
    .select2-selection--single
    select.select2-search__field,
select.typeahead,
select.tt-query,
select.tt-hint {
    padding: 0.4375rem 0.75rem;
    color: #f5f5f5 !important;
}

.form-control:focus, .asColorPicker-input:focus, .dataTables_wrapper select:focus, .jsgrid .jsgrid-table .jsgrid-filter-row input[type="text"]:focus, .jsgrid .jsgrid-table .jsgrid-filter-row select:focus, .jsgrid .jsgrid-table .jsgrid-filter-row input[type="number"]:focus, .select2-container--default .select2-selection--single:focus, .select2-container--default .select2-selection--single .select2-search__field:focus, .typeahead:focus, .tt-query:focus, .tt-hint:focus {
    color: #ffffff!important;
    background-color: #14141498 !important;
    border-color: #80bdff;
    outline: 0;
    box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}
.formInputField {
   
    background-color: #ffffff28;
    color: #f3f3f3;
}

.input-group-append .input-group-text, .input-group-prepend .input-group-text {
    border-color: #e0e0ef;
    padding: 0.175rem 0.75rem;
    color: #686868;
}



.button-62 {
  background: linear-gradient(to bottom right, #EF4765, #FF9A5A);
  border: 0;
  border-radius: 12px;
  color: #FFFFFF;
  cursor: pointer;
  display: inline-block;
  font-family: -apple-system,system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
  font-size: 16px;
  font-weight: 500;
  line-height: 2.5;
  outline: transparent;
  padding: 0 1rem;
  text-align: center;
  text-decoration: none;
  transition: box-shadow .2s ease-in-out;
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  white-space: nowrap;
}

.button-62:not([disabled]):focus {
  box-shadow: 0 0 .25rem rgba(0, 0, 0, 0.5), -.125rem -.125rem 1rem rgba(239, 71, 101, 0.5), .125rem .125rem 1rem rgba(255, 154, 90, 0.5);
}

.button-62:not([disabled]):hover {
  box-shadow: 0 0 .25rem rgba(0, 0, 0, 0.5), -.125rem -.125rem 1rem rgba(239, 71, 101, 0.5), .125rem .125rem 1rem rgba(255, 154, 90, 0.5);
}



/* CSS */
.button-61 {
  align-items: center;
  appearance: none;
  border-radius: 4px;
  border-style: none;
  box-shadow: rgba(0, 0, 0, .2) 0 3px 1px -2px,rgba(0, 0, 0, .14) 0 2px 2px 0,rgba(0, 0, 0, .12) 0 1px 5px 0;
  box-sizing: border-box;
  color: #fff;
  cursor: pointer;
  display: inline-flex;
  font-family: Roboto,sans-serif;
  font-size: .875rem;
  font-weight: 500;
  height: 36px;
  justify-content: center;
  letter-spacing: .0892857em;
  line-height: normal;
  min-width: 64px;
  outline: none;
  overflow: visible;
  padding: 0 16px;
  position: relative;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
  transition: box-shadow 280ms cubic-bezier(.4, 0, .2, 1);
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  vertical-align: middle;
  will-change: transform,opacity;
}

.button-61:hover {
  box-shadow: rgba(0, 0, 0, .2) 0 2px 4px -1px, rgba(0, 0, 0, .14) 0 4px 5px 0, rgba(0, 0, 0, .12) 0 1px 10px 0;
}

.button-61:disabled {
  background-color: rgba(0, 0, 0, .12);
  box-shadow: rgba(0, 0, 0, .2) 0 0 0 0, rgba(0, 0, 0, .14) 0 0 0 0, rgba(0, 0, 0, .12) 0 0 0 0;
  color: rgba(0, 0, 0, .37);
  cursor: default;
  pointer-events: none;
}

.button-61:not(:disabled) {
  background-color: #6200ee;
}

.button-61:focus {
  box-shadow: rgba(0, 0, 0, .2) 0 2px 4px -1px, rgba(0, 0, 0, .14) 0 4px 5px 0, rgba(0, 0, 0, .12) 0 1px 10px 0;
}

.button-61:active {
  box-shadow: rgba(0, 0, 0, .2) 0 5px 5px -3px, rgba(0, 0, 0, .14) 0 8px 10px 1px, rgba(0, 0, 0, .12) 0 3px 14px 2px;
  background: #A46BF5;
}
.modal-content {
  border: none;
  position: relative;
  padding: 50px !important;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  background: #c859ff;
  background: -moz-linear-gradient(45deg, #c859ff 0%, #ffab8c 100%);
  background: -webkit-gradient(left bottom, right top, color-stop(0%, #c859ff), color-stop(100%, #ffab8c));
  background: -webkit-linear-gradient(45deg, #c859ff 0%, #ffab8c 100%);
  background: -o-linear-gradient(45deg, #c859ff 0%, #ffab8c 100%);
  background: -ms-linear-gradient(45deg, #c859ff 0%, #ffab8c 100%);
  background: linear-gradient(45deg, #640494 0%, #ffaf3e 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#c859ff', endColorstr='#ffab8c', GradientType=1 );
  -webkit-box-shadow: 0px 10px 34px -15px rgba(0, 0, 0, 0.24);
  -moz-box-shadow: 0px 10px 34px -15px rgba(0, 0, 0, 0.24);
  box-shadow: 0px 10px 34px -15px rgba(0, 0, 0, 0.24); }
  .modal-content h3 {
    color: #fff;
    font-weight: 300; }
  .modal-content .modal-header {
    padding: 0;
    border: none; }
  .modal-content button.close {
    position: absolute;
    top: 0;
    right: 0;
    padding: 0;
    margin: 0;
    width: 40px;
    height: 40px;
    z-index: 1;
    text-shadow: none;
    background: rgba(0, 0, 0, 0.1); }
  .modal-content .modal-body {
    border: none; }
  .modal-content .modal-footer {
    border: none;
    background: #f8f8f8; }
  .modal-content .form-control {
    background: transparent;
    border: none;
    padding: 0;
    height: 40px;
    color: rgba(255, 255, 255, 0.8);
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 0; }
    .modal-content .form-control::-webkit-input-placeholder {
      /* Chrome/Opera/Safari */
      color: rgba(255, 255, 255, 0.8) !important; }
    .modal-content .form-control::-moz-placeholder {
      /* Firefox 19+ */
      color: rgba(255, 255, 255, 0.8) !important; }
    .modal-content .form-control:-ms-input-placeholder {
      /* IE 10+ */
      color: rgba(255, 255, 255, 0.8) !important; }
    .modal-content .form-control:-moz-placeholder {
      /* Firefox 18- */
      color: rgba(255, 255, 255, 0.8) !important; }
  .modal-content .btn {
    font-weight: 500;
    height: 52px; }
    .modal-content .btn .btn-primary {
      background: #f9e090 !important; }
  .modal-content .social {
    width: 100%; }
    .modal-content .social a {
      width: 100%;
      display: block;
      border: 1px solid rgba(255, 255, 255, 0.4);
      color: #000;
      background: #fff; }
      .modal-content .social a:hover {
        background: transparent;
        color: #fff; }

.divider {
  position: relative; }
  .divider:after {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    content: '';
    width: 1px;
    height: 100%;
    background: rgba(255, 255, 255, 0.2);
    margin: 0 auto; }

.form-check {
  padding: 0; }

.fill-checkbox {
  --color: #f9e090; }
  .fill-checkbox .fill-control-input {
    display: none; }
    .fill-checkbox .fill-control-input:checked ~ .fill-control-indicator {
      background-color: var(--color);
      border-color: var(--color);
      background-size: 80%; }
    .fill-checkbox .fill-control-input:checked ~ .fill-control-description {
      color: #fff; }
  .fill-checkbox .fill-control-indicator {
    border-radius: 3px;
    display: inline-block;
    position: absolute;
    top: 5px;
    left: 0;
    width: 16px;
    height: 16px;
    border: 1px solid rgba(255, 255, 255, 0.4);
    -webkit-transition: .1s;
    -o-transition: .1s;
    transition: .1s;
    background: transperent;
    background-size: 0%;
    background-position: center;
    background-repeat: no-repeat;
    content: 'hey';
    background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3E%3Cpath fill='%23fff' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26 2.974 7.25 8 2.193z'/%3E%3C/svg%3E"); }
  .fill-checkbox .fill-control-description {
    color: rgba(255, 255, 255, 0.6); }

.form-check.disabled .fill-checkbox {
  --color: rgba(255,255,255,.4); }
  .form-check.disabled .fill-checkbox .fill-control-description {
    color: rgba(255, 255, 255, 0.4); }

</style>
  
<div class="main-panel">
  <div class="content-wrapper">
    <div class="email-wrapper wrapper">
      <div class="row align-items-stretch">
   
          <div class="mail-list-container col-md-4  border-right bg-white site-container" style="background-image: url('../images/3cb3f92177d709bffe2bb21a2c376da4.jpg'); background-size: cover; box-shadow: rgba(0, 0, 0, 0.4) 0px 2px 4px, rgba(0, 0, 0, 0.3) 0px 7px 13px -3px, rgba(0, 0, 0, 0.2) 0px -3px 0px inset;">
          <div class="card2 pt-4 pb-4">



            
            <div class="border-bottom mb-3 px-3">
              
            
              
          </div>
          
          <div class="border-bottom px-3">
              <div class="form-group">
                  <label for="searchInput" style="font-size: 0.85rem; color: #e6e6e6;">SELECT PRODUCT <span class="text-danger" style="font-size: 1.5rem;">*</span></label>
                  <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="form-group">
                <label for="exampleSelectGender" style="font-size: 0.85rem; color: #e6e6e6;">SELECT PRODUCT SUPPLIER<span class="text-danger" style="font-size: 1.5rem;">*</span></label>
                <select name="simple" data-placeholder="Select something please .." class="formInputField" id="supplier" disabled>
                    <?php
                    $supplierId = $purchaseProducts->isNotEmpty() ? $purchaseProducts->first()->supplier_id : null;
                ?>
                
                <?php $__currentLoopData = $suppliers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $supplier): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($supplier->id); ?>" 
                        <?php if($supplier->id == $supplierId): ?> selected <?php endif; ?>>
                        <?php echo e($supplier->name); ?> (<?php echo e($supplier->company); ?>)
                    </option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
              </select>
              </div>
              <div class="form-group">
                <label for="itemCost" style="font-size: 0.85rem; color: #e6e6e6;">ITEM COST<span class="text-danger" style="font-size: 1.5rem;">*</span></label>
                <input class="form-control w-100 formInputField" type="number" placeholder="Item Cost" id="itemCost" >
            </div>
            <div class="form-group">
                <label for="Quantity" style="font-size: 0.85rem; color: #e6e6e6;">TOTAL QUANTITY<span class="text-danger" style="font-size: 1.5rem;">*</span></label>
                <input class="form-control w-100 formInputField" type="number" placeholder="Quantity" id="Quantity">
            </div>
          </div>
      
          
      
        
      
          
      
         
          <div class="border-bottom mb-3 px-3" style="position: relative; top:20px;" id="adProductToTableDiv">
            <div class="form-group">

             
              <button type="button" class="button-62" id="adProductToTable" style="width: 100%">Add Items</button>
            </div>
        </div>

          
          </div>
      </div>
      
        
        <div class="mail-view d-none d-md-block col-md-9 col-lg-8 bg-white card3" >
          <div id="errorAlert" class="alert alert-danger alert-dismissible fade show d-none" role="alert" style="position: relative; top: 10px;">
            <strong>Warning!</strong> <span id="alertMessage"></span>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
          
          <div class="message-body " >
            <div class="sender-details ">
              <div class="attachments-sections ">
                
                <div class="btn-group">
                  <button type="button" class="btn btn-sm btn-outline-secondary btn-icon-text"><i class="fas fa-address-card  btn-icon-prepend" style="color: white"></i>PURCHASE REFERENCE :&nbsp;<span id="purchase_id"></span></button>
                 
                </div>
                <div class="btn-group">
                  <input type="date" class="form-control w-100 formInputField" id="dateInput" style="padding: 7px 12.95px;">
                    <div class="input-group-append">
                      <span class="input-group-text">
                        <i class="fa fa-calendar" style="cursor: pointer;"></i>
                      </span>
                  </div>
                </div>
                <ul>
                  <li>
                    <div class="thumb"><i class="fa fa-dollar"></i></div>
                    <div class="details">
                      <p class="file-name">Total Cost</p>
                      <div class="buttons">
                        <p class="file-size" id="totalCost" style="color: wheat">0</p>
                      
                      </div>
                    </div>
                  </li>
                  <li>
                    <div class="thumb"><i class="fa fa-dollar"></i></div>
                    <div class="details">
                      <p class="file-name">Total Quantity</p>
                      <div class="buttons">
                        <p class="file-size" id="totQuantity" style="color: wheat">0</p>
                        
                      </div>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="message-content">
              <div class="form-group">
                <table id="itemTable" class="table table-striped table-bordered">
                    <thead>
                        <tr>
                            <th>IMU Barcode</th>
                            <th>Quantity</th>
                            <th>Cost</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Rows will be dynamically added here -->
                    </tbody>
                </table>
            </div>
            <button class="button-61 SubmitPurchase"   role="button" style="width: 100%" id="submit" >SUBMIT</button>

            </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>Id #</th>
                      <th>Product Name</th>
                      <th>Brand</th>
                      <th>Quantity</th>
                      <th>Cost</th>
                      <th>total Cost</th>
               
                      
                  </tr>
                </thead>
                <tbody>
                    <?php $__currentLoopData = $purchaseProducts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $purchaseProduct): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <tr>
                      <td><?php echo e($purchaseProduct->id); ?></td>
                      <td><?php echo e($purchaseProduct->product_name); ?></td>
                      <td><?php echo e($purchaseProduct->product_brand_name); ?></td>
                      <td><?php echo e($purchaseProduct->quantity); ?></td>
                      <td><?php echo e($purchaseProduct->each_cost); ?></td>
                      <td><?php echo e($purchaseProduct->total_cost); ?></td>
                    </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
              
                </tbody>
              </table>
            </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 © 2018 <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>
<script>
  function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

function validateInputs(itemBarcode, itemQuantity, itemCost) {
        let messages = [];

        if (isNaN(itemBarcode) || isNaN(itemQuantity)) {
            messages.push("Please enter valid barcode and quantity");
        }
        if (isNaN(itemCost)) {
            messages.push("Please enter cost amount");
        }

        if (messages.length > 0) {
            // Show Bootstrap Alert with messages
            $("#alertMessage").html(messages.join("<br>")); // Update the alert message
            $("#errorAlert").removeClass("d-none"); // Show the alert
            return false; // Prevent further execution
        }

        // Hide the alert if there are no errors
        $("#errorAlert").addClass("d-none");
        return true; // Proceed with further execution
    }

    // Example Usage
    const itemBarcode = "invalid"; // Example input
    const itemQuantity = "invalid";
    const itemCost = NaN;



    const dateInput = document.getElementById("dateInput");
  const today = new Date().toISOString().split('T')[0]; // Format: YYYY-MM-DD
  dateInput.value = today;

$(document).ready(function () {


    var currentUrl = window.location.href;

// Create a URL object to parse the query parameters
var url = new URL(currentUrl);

// Get the 'id' query parameter from the URL
var id = url.searchParams.get("id");

var productExsistingQuantity;

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

    if (searchTerm.length >= 2) {
        $.ajax({
            url: `/search-product-for-return/${id}` , // Endpoint to handle search requests
            method: 'GET',
            data: { query: searchTerm }, // Send the search term to the server
            success: function (data) {
                const suggestions = data.suggestions; // Assuming `data.suggestions` is the list
                const suggestionList = $('#suggestionList');
                suggestionList.empty(); // Clear existing suggestions

                if (suggestions.length === 1) {
                    // If there's only one suggestion, populate the input and hide the list
                    const item = suggestions[0];
                    $('#searchInput')
                        .val(`${item.name.trim()} (${item.code.trim()})`)
                        .attr('data-id', item.id)
                        .attr('data-quantity', item.quantity); // Populate the input field
                    suggestionList.hide();
                    productExsistingQuantity = item.quantity // Hide suggestions
                
                    $("#itemCost").val(item.each_cost);
               
                } else if (suggestions.length > 1) {
                    // If there are multiple suggestions, display them
                    suggestions.forEach(item => {
                        suggestionList.append(
                            `<li data-id="${item.id}" data-quantity="${item.quantity}" class="suggestion-item">
                        ${item.name.trim()} (${item.code.trim()})
                    </li>`
                        );
                    productExsistingQuantity = item.quantity // Hide suggestions
                
                    $("#itemCost").val(item.each_cost);
                    });
                    suggestionList.show(); // Show suggestions
                } else {
                    // If no suggestions are found, hide the list
                    suggestionList.hide();
                }
            },
            error: function (error) {
                console.error('Error fetching suggestions:', error);
            }
        });
    } else {
        $('#suggestionList').hide(); // Hide suggestions if input is less than 2 characters
    }
});

// Handle click event on the suggestion items
$(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

    $('#searchInput')
        .val(selectedText) // Set the input value to the selected text
        .attr('data-id', selectedId); // Set the data-id to the input field

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

    // 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
    });





    $('#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"]
            ],
            columns: [
                { data: 'id' },
                { data: 'product_name' },
                { data: 'product_brand_name' },
                { data: 'quantity' },
                { data: 'each_cost' },
                { data: 'total_cost' }
            ]
        });



  var purchaseNo = '<?php echo e($purchase->purchases_id ?? ''); ?>';
    if (purchaseNo) {
      var lastSixCharacters = purchaseNo.slice(-6);
      var incrementedValue = parseInt(lastSixCharacters) + 1;
      $('#purchase_id').html(purchaseNo.slice(0, -6) + incrementedValue);
    } else {
        
      $("#purchase_id").html('PO-202510000')
    }
  

    
  
    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: [
             '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 totalQuantity = 0;
var totalCost = 0;

function addToproductTable() {
    

    var barcode = $("#searchInput").val();
    var itemQuantity = parseFloat($("#Quantity").val());
    var itemCost = parseFloat($("#itemCost").val());
    var match = barcode.match(/\((\d+)\)/);
    var itemBarcode;

    if (parseInt(itemQuantity) > productExsistingQuantity) {
      
            alert("Entered quantity exceeds the available stock (" + productExsistingQuantity + ").");
            return;
        }

    var itemDataId = $("#searchInput").attr("data-id");
  
// Check if the match is successful and extract the barcode
    if (match && match[1]) {
      itemBarcode = match[1]; // This will be the extracted barcode
      
    } else {
       
    }
    
    validateInputs(itemBarcode, itemQuantity, itemCost);
 
    // Check if itemBarcode and itemQuantity are valid
    if (isNaN(itemBarcode) || isNaN(itemQuantity)) {
        
        return;
    }
    if (isNaN(itemCost)) {
        
        return;
    }

    var totItemCost = itemCost * itemQuantity;

    // Prepare row data
    var rowData = {
        itemBarcode: itemBarcode,
        itemCost:itemCost,
        itemDataId:itemDataId,
        itemQuantity: itemQuantity,
        totItemCost: totItemCost,
    };

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

    // Append data to the DataTable
    table.row.add([
      barcode,
        itemQuantity,
        totItemCost,
        "<button type='button' class='btn-remove-row btn btn-danger btn-sm'><i class='fa fa-trash'></i></button>"
    ]).draw();

    
    calculateTotals();

    // Log the total sum to the console
    console.log("Total Quantity: ", totalQuantity.toFixed(2));
    // $("#totalCost").html(totalCost);
    let formattedCost = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD', // Still needed for formatting, but we will remove the symbol
    minimumFractionDigits: 2, // Ensures two decimal places
}).format(totalCost).replace(/[^\d.,-]/g, ''); // Remove non-numeric symbols

$("#totalCost").html(formattedCost);

    
    $("#totQuantity").html(totalQuantity);



    
    // Reset the input fields
    $("#Quantity").val("");
    $("#itemCost").val("");
    $("#searchInput").val("");
    
    
    // $("#itemQuantity").val("");
}

// Function to recalculate totals
function calculateTotals() {
    totalQuantity = 0;
    totalCost = 0;
    mortgageDataArray.forEach(function (data) {
        totalQuantity += data.itemQuantity;
        totalCost += data.totItemCost;
    });
}





// Function to remove row from the table and update totals
$(document).on('click', '.btn-remove-row', function () {
    var row = $(this).closest('tr');
    var rowIndex = table.row(row).index(); // Get the row index
    var itemBarcode = mortgageDataArray[rowIndex].itemBarcode;
    var itemQuantity = mortgageDataArray[rowIndex].itemQuantity;
    var totItemCost = mortgageDataArray[rowIndex].totItemCost;

    // Remove the row from the data array
    mortgageDataArray.splice(rowIndex, 1);

    // Remove the row from the DataTable
    table.row(row).remove().draw();

    // Recalculate totals
    totalQuantity -= itemQuantity;
    totalCost -= totItemCost;

    // Update the totals in the HTML
    let formattedCost = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD', // Still needed for formatting, but we will remove the symbol
    minimumFractionDigits: 2, // Ensures two decimal places
}).format(totalCost).replace(/[^\d.,-]/g, ''); // Remove non-numeric symbols

$("#totalCost").html(formattedCost);
    $("#totQuantity").html(totalQuantity.toFixed(2));

    console.log("Row removed. Updated Total Quantity: ", totalQuantity.toFixed(2));
});

// Trigger adding to the table on button click
$("#adProductToTable").click(function () {
    addToproductTable();
});






// Trigger adding to the table on Enter key press
$("#itemBarcode, #itemQuantity").on("keydown", function (event) {
    if (event.key === "Enter") { // Check if the pressed key is Enter
        addToTable();
    }
});



    const supplierList = $('#supplier');  // Use jQuery selector instead of querySelector

// Initialize lc_select
new lc_select(supplierList[0], {
    wrap_width: '100%',
    min_for_search: 2,
    pre_placeh_opt: true,
});


const branchList = $('#branch');  // Use jQuery selector instead of querySelector

// Initialize lc_select
new lc_select(branchList[0], {
    wrap_width: '100%',
    min_for_search: 2,
    pre_placeh_opt: true,
});





    $(document).on('change', '#PurchaseType', function () {
    const PurchaseType = $('#PurchaseType').val(); 
    if (PurchaseType === "Add Product By Items") {
        $('.productItem').show(); 
        $('#adProductToTableDiv').hide(); 
        
         // Display the productItem div
    } else {
        $('.productItem').hide(); 
        $('#adProductToTableDiv').show();  // Hide the productItem div
    }
});


$(document).on('click', '.SubmitPurchase', function () {

  alert("hi")
  var PurchaseType = $("#PurchaseType").val();
  var itemCost= $("#itemCost").val();
  var itemDataId = $("#searchInput").attr("data-id");
  var purchaseNo = $("#purchase_id").html();
  var dateInput = $("#dateInput").val();
  var supplier = $("#supplier").val();
  var PurchaseStatus = $("#PurchaseStatus").val();
  var branch = $("#branch").val();
  var paidAmount = $("#paidAmount").val();
  
  
  var isValid = true;
  var errorMessage = '';

  if (!supplier || supplier.length == 0) {
        errorMessage += 'Please Add Supplier.<br>';
        isValid = false;
    }
    if (!Array.isArray(mortgageDataArray) || mortgageDataArray.length === 0) {
            errorMessage += 'Please add products to purchase.<br>';
            isValid = false;
        }

    if (!totalQuantity || totalQuantity == 0 || !totalCost || totalCost.length == 0) {
        errorMessage += 'Please Purchase Product.<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', '<?php echo e(csrf_token()); ?>');
            form_data.append('PurchaseType', "product");
            form_data.append('dateInput', dateInput);
            form_data.append('purchaseNo', purchaseNo);
            form_data.append('supplier', supplier);
            form_data.append('id', id);
            form_data.append('totalQuantity', totalQuantity);
            form_data.append('totalCost', totalCost);


            $.each(mortgageDataArray, function(i, rowData) {
              form_data.append('mortgageData[' + i + '][itemBarcode]', rowData.itemBarcode);
              form_data.append('mortgageData[' + i + '][itemCost]', rowData.itemCost);
              form_data.append('mortgageData[' + i + '][itemQuantity]', rowData.itemQuantity);
              form_data.append('mortgageData[' + i + '][itemDataId]', rowData.itemDataId);
              form_data.append('mortgageData[' + i + '][totItemCost]', rowData.totItemCost); // Append mortgageSubType
            });
            

            $.ajax({
                url: '/return-purchase', // Replace with your backend URL
                type: 'POST',
                data: form_data,
                contentType: false,
                processData: false,
                success: function (response) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Your data has been submitted successfully!',
                        confirmButtonText: 'OK',
                    }).then((result) => {
                      if (result.isConfirmed) {
                         window.location.reload();
                      }
                    });
                },
                error: function (response) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'There was an error submitting your data.',
                        confirmButtonText: 'OK',
                    });
                }
            });
      }

 
 

});
  
});


  </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/Purchase/returnPurchase/returntPurchaceProduct.blade.php ENDPATH**/ ?>