

<?php $__env->startSection('content'); ?>
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
    .autocomplete-active {
        background: #0d6efd !important;
        color: white !important;
    }
    table, th, td {
    border: 1px solid #444;
}
.input-focus {
    border: 2px solid #0d6efd !important;
}

#paidAmountWrapper {
    display: none;
}

</style>

<style>
/* Windows-like focus */
.input-focus:focus {
  box-shadow: 0 0 0 0.2rem rgba(13,110,253,.25);
  border-color: #0d6efd;
}
.card-windows {
  border-radius: 8px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.06);
  border: 1px solid #e6e9ee;
}
.suggestions {
  position: absolute; z-index: 2000; max-height: 220px; overflow:auto;
  background:white; border:1px solid #ddd; width:100%;
  border-radius: 4px;
}
.suggestion-item { padding:8px 10px; cursor:pointer; }
.suggestion-item:hover, .suggestion-item.active { background:#e9f2ff; }
.productRow { position:relative; }
.savedRow input { background:#f8fafc; }
.form-section { gap:1rem; display:flex; align-items:center; flex-wrap:wrap; }
.label-small { font-size:0.85rem; color:#3b3f45; }
.small-muted { font-size:0.85rem; color:#6b7280; }
</style>

<div class="container mt-0">
  <h2 class="fw-bold mb-1">Add Sales</h2>

  <div class="card card-windows p-3">
    <form id="salesForm" action="<?php echo e(route('user.sales.save')); ?>" method="POST">
      <?php echo csrf_field(); ?>

      
      <div class="row g-3 align-items-end form-section">

    <div class="col-md-2">
        <label class="label-small">Sales Date</label>
        <input type="date" name="sales_date" class="form-control input-focus" required value="<?php echo e(date('Y-m-d')); ?>">
    </div>

    <div class="col-md-2 position-relative">
        <label class="label-small">Line (type and press Enter)</label>
        <input type="text" id="lineInput" class="form-control input-focus" placeholder="Type line and press Enter" autocomplete="off">
        <div id="lineSuggestions" class="suggestions d-none"></div>
    </div>

    <div class="col-md-3 position-relative d-none" id="customerWrap">
        <label class="label-small">Customer (type and press Enter)</label>
        <input type="text" id="customerInput" class="form-control input-focus" placeholder="Type customer and press Enter" autocomplete="off" disabled>
        <div id="customerSuggestions" class="suggestions d-none"></div>
    </div>

 <div class="col-md-2" id="paidAmountWrapper">
    <label class="label-small">Pay Amount</label>
    <input type="number" id="paidAmount" name="paid_amount"
           class="form-control input-focus" placeholder="Enter paid amount">
</div>


<div class="col-md-2">
    <label class="label-small">&nbsp;</label>
    <button type="button" id="clearPageBtn" class="btn btn-outline-secondary w-100">
        Clear
    </button>
</div>


</div>

      
      <div id="productsSection" class="mt-2 d-none">
        <div class="row g-2 align-items-center mb-2 fw-semibold">
          
          <div class="col-4">Product Name</div>
          <!-- <div class="col-2">Stock</div> -->
          <div class="col-2">Qty</div>
          <div class="col-2">Price</div>
          <div class="col-2">Amount</div>
        </div>

        <div id="productsContainer">
          
        </div>

        <hr class="my-3">

        <div class="d-flex justify-content-end align-items-center">
          <h5 class="me-3">Grand Total: ₹ <span id="grandTotal">0.00</span></h5>
          <input type="hidden" name="total_amount" id="grandTotalInput" value="0">
        </div>
      </div>

      
      <input type="hidden" name="line_id" id="hdLineId" />
      <input type="hidden" name="customer_id" id="hdCustomerId" />
      <input type="hidden" name="customer_name" id="hdCustomerName" />
      <input type="hidden" name="customer_address" id="hdCustomerAddress" />
      <input type="hidden" name="customer_phone" id="hdCustomerPhone" />
      <input type="hidden" name="lines" id="hdLinesJson" />
    </form>

    <!-- ===================== LIVE PREVIEW SECTION ====================== -->
<!-- <div class="card mt-4 shadow-sm">
    <div class="card-header bg-primary text-white">
        <h5 class="mb-0">Live Preview</h5>
    </div>
    <div class="card-body">
        <div id="live_preview_empty" class="text-muted">Start selecting values to preview…</div>
        <div id="live_preview_content" style="display:none;">
            <p><strong>Line:</strong> <span id="preview_line"></span></p>
            <p><strong>customer:</strong> <span id="preview_customer"></span></p>

            <table class="table table-bordered mt-3">
                <thead class="table-light">
                    <tr>
                        <th>Product</th>
                        <th>Qty</th>
                        <th>Price</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody id="preview_products"></tbody>
            </table>
        </div>
    </div>
</div> -->


<!-- ===================== TODAY’S SAVED salesS ====================== -->
<div class="card mt-4 shadow-sm">
    <div class="card-header bg-success text-white">
        <h5 class="mb-0">Today’s Saved Sales</h5>
    </div>
    <div class="card-body">
        <table class="table table-striped table-bordered">
            <thead class="table-light">
                <tr>
                  <th>S.no</th>
                    <th>Line</th>
                    <th>Customer</th>
                    <th>Products</th>
                    <th>Total Amount</th>
                    <th>Paid Amount</th>
                    <th>Time</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody id="today_sales"></tbody>
        </table>
    </div>
</div>

  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>




    // ---- Universal keyboard navigation for dropdown lists ----
// REPLACE your old enableKeyboardNavigation with this
function enableKeyboardNavigation(inputSelector, listSelector, onSelectCallback = null) {

    $(document).on("keydown", inputSelector, function (e) {

        const $input = $(this);

        // Find the suggestion list that belongs to this input:
        // 1) If input is inside a productRow, prefer that productRow's list
        // 2) Otherwise, try siblings (common for #lineInput / #customerInput)
        // 3) Fallback to first matching listSelector on page
        let $list = $input.closest('.productRow').find(listSelector);
        if (!$list.length) {
            $list = $input.siblings(listSelector);
        }
        if (!$list.length) {
            $list = $(listSelector).first();
        }

        const $items = $list.find(".suggestion-item");
        const len = $items.length;
        if (!len) return;

        // read index stored on this input (per-input state)
        let currentIndex = parseInt($input.data('navIndex') ?? -1, 10);

        // handle keys
        if (e.key === "ArrowDown") {
            e.preventDefault();
            currentIndex = (currentIndex + 1) % len;
        } else if (e.key === "ArrowUp") {
            e.preventDefault();
            currentIndex = (currentIndex - 1 + len) % len;
        } else if (e.key === "Escape") {
            $list.addClass("d-none");
            $input.data('navIndex', -1);
            return;
        }  else if (e.key === "Enter") {
    e.preventDefault();

    // Only select if an item is actually highlighted
    if (currentIndex >= 0 && currentIndex < len) {
        $items.eq(currentIndex).click();
    }

    if (onSelectCallback) setTimeout(onSelectCallback, 1);

    $input.data('navIndex', -1);
    return;
}


        // update highlight classes
        $items.removeClass("autocomplete-active");
        if (currentIndex >= 0) {
            const $active = $items.eq(currentIndex);
            $active.addClass("autocomplete-active");

            // auto-scroll list to make active visible
            // guard against undefined position() when list scroll not needed
            const itemPos = $active.position();
            if (itemPos) {
                const scrollTop = $list.scrollTop();
                $list.scrollTop(itemPos.top + scrollTop - 6);
            }
        }

        // store index back on this input so each input has own cursor state
        $input.data('navIndex', currentIndex);
    });
}

// Keep your calls but they now work correctly with per-input state:
enableKeyboardNavigation("#lineInput", "#lineSuggestions");
enableKeyboardNavigation("#customerInput", "#customerSuggestions");
enableKeyboardNavigation(
    ".productInput",
    ".productSuggestions",
    function () {
        setTimeout(() => {
            $(".priceInput:visible").focus().select();
        }, 50);
    }
);

/*
  Final simplified sales view JS
  - searches use routes below (must exist server-side)
  - product rows saved client-side (linesSelected) until Save sales
*/

$(function () {
  // routes (Blade route names)
  const routes = {
    lines: "<?php echo e(route('user.search.saleslines')); ?>",
    customers: "<?php echo e(route('user.search.customer')); ?>",
products: "<?php echo e(route('user.search.sales.products')); ?>"

  };

  // setup CSRF header for AJAX (ensures session cookies used)
  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });

  // DOM refs
  const $lineInput = $('#lineInput'), $lineSuggestions = $('#lineSuggestions');
  const $customerWrap = $('#customerWrap'), $customerInput = $('#customerInput'), $customerSuggestions = $('#customerSuggestions');
  const $productsSection = $('#productsSection'), $productsContainer = $('#productsContainer');
  const $grandTotal = $('#grandTotal'), $grandTotalInput = $('#grandTotalInput');
  const $hdLinesJson = $('#hdLinesJson');

  // in-memory lines (client-side) until final save
  let linesSelected = [];

  function debounce(fn, t=200) {
    let to;
    return function(...args) {
      clearTimeout(to);
      to = setTimeout(()=>fn.apply(this,args), t);
    };
  }

  // helper: prefer multiple possible keys (flexible JSON)
  function getFirst(obj, keys) {
    for (let k of keys) {
      if (Object.prototype.hasOwnProperty.call(obj, k) && obj[k] !== undefined && obj[k] !== null) return obj[k];
    }
    return null;
  }

  // --- LINE search ---
  $lineInput.on('input', debounce(function(){
    const q = $(this).val().trim();
    if (!q) { $lineSuggestions.addClass('d-none').html(''); return; }
    $.getJSON(routes.lines, { q }, function(data){
      if (!Array.isArray(data) || data.length === 0) {
        $lineSuggestions.html('<div class="p-2 text-muted">No lines</div>').removeClass('d-none');
        return;
      }
      let html = '';
      data.forEach(d => {
        const id = getFirst(d, ['line_id','id']);
        const name = getFirst(d, ['line_name','line_name']);
        html += `<div class="suggestion-item" data-id="${id}" data-name="${escapeHtml(name)}">${escapeHtml(name)}</div>`;
      });
      $lineSuggestions.html(html).removeClass('d-none');
    }).fail(()=> {
      $lineSuggestions.html('<div class="p-2 text-muted">No lines (server)</div>').removeClass('d-none');
    });
  }));

  // click or Enter to select line
  $lineSuggestions.on('click', '.suggestion-item', function(){ selectLine($(this).data('id'), $(this).data('name')); });
  // ENTER handler for both lineInput & customerInput
$(document).on('keydown', '#lineInput, #customerInput', function(e){
    if (e.key !== 'Enter') return;

    e.preventDefault();
    const $input = $(this);

    // detect correct list
    let $list = ($input.attr('id') === 'lineInput') 
        ? $('#lineSuggestions') 
        : $('#customerSuggestions');

    // highlighted item (keyboard navigation)
    let $highlight = $list.find('.autocomplete-active');

    if ($highlight.length) {
        let id = $highlight.data('id');
        let name = $highlight.data('name');

        if ($input.attr('id') === 'lineInput') {
            selectLine(id, name);
        } else {
            selectCustomer(
                id, 
                name, 
                $highlight.data('address') || '', 
                $highlight.data('phone') || ''
            );
        }
        return;
    }

    // if NO highlight — do NOTHING (no auto-first anymore)
    return;
});


  function selectLine(id, name) {
    $('#hdLineId').val(id);
    $lineInput.val(name);
    $lineSuggestions.addClass('d-none').html('');
    // show customer input and enable it
    $customerWrap.removeClass('d-none');
    $customerInput.prop('disabled', false).focus();
  }

  // --- customer search (only after line selected) ---
  $customerInput.on('input', debounce(function(){
    const q = $(this).val().trim();
    if (!q) { $customerSuggestions.addClass('d-none').html(''); return; }
    $.getJSON(routes.customers, { q }, function(data){
      if (!Array.isArray(data) || data.length === 0) {
        $customerSuggestions.html('<div class="p-2 text-muted">No customers</div>').removeClass('d-none');
        return;
      }
      let html = '';
      data.forEach(d => {
        const id = getFirst(d, ['member_id','id']);
        const name = getFirst(d, ['member_name','name']);
        // address & phone returned but not shown
        html += `<div class="suggestion-item" data-id="${id}" data-name="${escapeHtml(name)}" data-address="${escapeHtml(getFirst(d,['address','addr'])||'')}" data-phone="${escapeHtml(getFirst(d,['phone','mobile'])||'')}">${escapeHtml(name)}</div>`;
      });
      $customerSuggestions.html(html).removeClass('d-none');
    }).fail(()=> {
      $customerSuggestions.html('<div class="p-2 text-muted">No customers (server)</div>').removeClass('d-none');
    });
  }));

  $customerSuggestions.on('click', '.suggestion-item', function(){
    const $it = $(this);
    selectCustomer($it.data('id'), $it.data('name'), $it.data('address'), $it.data('phone'));
  });
  

  function selectCustomer(id, name, address, phone) {
    $('#hdCustomerId').val(id);
    $('#hdCustomerName').val(name);
    $('#hdCustomerAddress').val(address || '');
    $('#hdCustomerPhone').val(phone || '');
    $customerInput.val(name);
    $customerSuggestions.addClass('d-none').html('');
    // show products area (products saved client-side until final save)
    $productsSection.removeClass('d-none');
    $productsContainer.empty();
    $productsContainer.append(createActiveRow());
    setTimeout(()=> $productsContainer.find('.productInput').first().focus(), 50);
  }

  // --- PRODUCTS: active row creation and behavior ---
  function createActiveRow() {
    const $row = $(`
      <div class="row g-2 align-items-end productRow">
        <div class="col-4 position-relative">
          <input type="text" class="form-control productInput input-focus" placeholder="Type product and press Enter" autocomplete="off">
          <div class="suggestions d-none productSuggestions"></div>
        </div>
       
        <div class="col-2">
          <input type="number" class="form-control qtyInput" value="1" min="0">
        </div>
        <div class="col-2">
          <input type="number" class="form-control priceInput" step="0.01" value="0.00">
        </div>
        <div class="col-2">
          <input type="number" class="form-control amountInput" readonly>
        </div>
      </div>
    `);
    attachRowEvents($row);
    return $row;
  }

  function attachRowEvents($row) {
    const $prod = $row.find('.productInput');
    const $suggest = $row.find('.productSuggestions');

    const $qty = $row.find('.qtyInput');
    const $price = $row.find('.priceInput');
    const $amt = $row.find('.amountInput');

    // product typing -> search
    $prod.on('input', debounce(function(){
      const q = $(this).val().trim();
      if (!q) { $suggest.addClass('d-none').html(''); return; }
      $.getJSON(routes.products, { q }, function(data){
        if (!Array.isArray(data) || data.length === 0) {
          $suggest.html('<div class="p-2 text-muted">No products</div>').removeClass('d-none');
          return;
        }
        let html = '';
        data.forEach(d => {
          const id = getFirst(d, ['product_id','id']);
          const name = getFirst(d, ['product_name','name']);
          const stock = getFirst(d, ['qty','quantity']) || 0;
          const price = getFirst(d, ['price','selling_price','mrp']) || 0;
          html += `<div class="suggestion-item" data-id="${id}" data-name="${escapeHtml(name)}" data-stock="${stock}" data-price="${price}">${escapeHtml(name)}</div>`;
        });
        $suggest.html(html).removeClass('d-none');
      }).fail(()=> {
        $suggest.html('<div class="p-2 text-muted">No products (server)</div>').removeClass('d-none');
      });
    }, 140));

    // click suggestion picks product
    $suggest.on('click', '.suggestion-item', function(){
      const $it = $(this);
      acceptProduct($row, $it.data('id'), $it.data('name'), $it.data('quantity'), $it.data('price'));
    });

    // Enter on product picks first suggestion or goes to qty
//    $prod.on('keydown', function(e){
//     if (e.key === 'Enter') {
//         e.preventDefault();
//         const first = $suggest.find('.suggestion-item').first();
//         if (first.length) {
//             acceptProduct($row, first.data('id'), first.data('name'), first.data('stock'), first.data('price'));
//         } else {
//             $price.focus().select();  // go to price
//         }
//     }
// });

// $prod.on('keydown', function(e){
//     if (e.key === 'Enter') {
//         e.preventDefault();

//         // Only select if highlighted by keyboard navigation
//         const highlighted = $suggest.find(".autocomplete-active");

//         if (highlighted.length) {
//             highlighted.click();
//         } else {
//             // No auto-pick. User manually chooses.
//             $price.focus().select();  
//         }
//     }
// });
$prod.on('keydown', function(e){
    if (e.key !== 'Enter') return;
    e.preventDefault();

    const highlighted = $suggest.find(".autocomplete-active");
    const prodVal = $(this).val().trim();

    if (highlighted.length) {
        // normal flow: accept highlighted product
        highlighted.click();
        return;
    }

    // If product name is empty AND there is at least one saved product, jump to paidAmount
    if (prodVal === "" && Array.isArray(linesSelected) && linesSelected.length > 0) {
        $('#paidAmount').focus().select();
        return;
    }

    // Otherwise, go to price (existing behavior)
    $price.focus().select();
});


    // compute amount
    function computeAmount(){
      const q = parseFloat($qty.val() || 0);
      const p = parseFloat($price.val() || 0);
      $amt.val((q * p).toFixed(2));
    }
    $qty.on('input', computeAmount);
    $price.on('input', computeAmount);
$qty.on('keydown', function(e){
    if (e.key === 'Enter') {
        e.preventDefault();
        $price.focus().select();   // move to price
    }
});

    // Enter on price finalizes row: push to linesSelected, show summary, clear active row, focus product
    $price.on('keydown', function(e){
      if (e.key === 'Enter') {
        e.preventDefault();
        finalizeRow($row);
      }
    });

    // hide suggestions clicking outside row
    $(document).on('click.sales', function(ev){
      if (!$(ev.target).closest($row).length) {
        $suggest.addClass('d-none');
      }
    });
  }

  // function acceptProduct($row, id, name, qty, price) {
  //   $row.find('.productInput').val(name);
 
  //   if (price !== undefined && price !== null) $row.find('.priceInput').val(parseFloat(price).toFixed(2));
  //   $row.find('.productSuggestions').addClass('d-none').html('');
  //   $row.find('.qtyInput').focus().select();
  //   //  $row.find('.priceInput').focus().select();
  //   $row.find('.amountInput').val( (parseFloat($row.find('.qtyInput').val()||0) * parseFloat($row.find('.priceInput').val()||0)).toFixed(2) );
  //   $row.data('product-id', id);
  // }
  function acceptProduct($row, id, name, qty, price) {
    $row.find('.productInput').val(name);


    if (price !== undefined && price !== null)
        $row.find('.priceInput').val(parseFloat(price).toFixed(2));

    $row.find('.productSuggestions').addClass('d-none').html('');

    // After selecting product → go to QUANTITY
    $row.find('.qtyInput').focus().select();

    $row.find('.amountInput').val(
        (parseFloat($row.find('.qtyInput').val()||0) *
         parseFloat($row.find('.priceInput').val()||0)).toFixed(2)
    );

    $row.data('product-id', id);
}


  function finalizeRow($row) {
    const productId = $row.data('product-id') || null;
    const productName = $row.find('.productInput').val().trim();
    if (!productName) { $row.find('.productInput').focus(); return; }
  
    const quantity = parseFloat($row.find('.qtyInput').val() || 0);
    const price = parseFloat($row.find('.priceInput').val() || 0);
    const amount = parseFloat($row.find('.amountInput').val() || (quantity * price));
   if (linesSelected.length === 0) {
        document.getElementById("paidAmountWrapper").style.display = "block";
    }
    // push into client-side array (not saved server-side yet)
    linesSelected.push({
      product_id: productId,
      product_name: productName,
   
      quantity: quantity,
      price: price,
      amount: amount
    });

    // show a simple read-only summary row (so user sees what they added)
    const $summary = $(`
      <div class="row g-2 align-items-center savedRow mt-2">
        <div class="col-4"><input class="form-control" readonly value="${escapeHtml(productName)}"></div>
       
        <div class="col-2"><input class="form-control" readonly value="${quantity.toFixed(2)}"></div>
        <div class="col-2"><input class="form-control" readonly value="${price.toFixed(2)}"></div>
        <div class="col-2"><input class="form-control" readonly value="${amount.toFixed(2)}"></div>
      </div>
    `);

    // remove active row, append summary, then create new active row and focus product
    $row.after($summary);
    $row.remove();

    $productsContainer.append(createActiveRow());
    $productsContainer.find('.productInput').last().focus();

    // update grand total
    updateGrand();
  }

  function updateGrand() {
    const total = linesSelected.reduce((s, l) => s + (parseFloat(l.amount||0)), 0);
    $grandTotal.text(total.toFixed(2));
    $grandTotalInput.val(total.toFixed(2));
    $hdLinesJson.val(JSON.stringify(linesSelected));
  }

  // init / clear
  function init() {
    $productsContainer.empty();
    linesSelected = [];
    $grandTotal.text('0.00');
    $grandTotalInput.val('0');
    $hdLinesJson.val('');
    $customerWrap.addClass('d-none');
    $customerInput.prop('disabled', true);
    $productsSection.addClass('d-none');
  }
  init();
// When user presses Enter inside Paid Amount → Save all data
// Prevent entire form from submitting on "Enter" anywhere
document.getElementById("paidAmount").addEventListener("keydown", function (e) {
    if (e.key === "Enter") {
        e.preventDefault();
        document.getElementById("salesForm").submit(); 
    }
});

$('#salesForm').on('keydown', function(e) {
    if (e.key === "Enter" && e.target.id !== "paidAmount") {
        e.preventDefault();
    }
});

// Paid amount → press Enter → Save
$("#paidAmount").on("keydown", function(e) {
    if (e.key === "Enter") {
        e.preventDefault();
        submitForm();
    }
});

function submitForm() {
      $("#hdPaidAmount").val($("#paidAmount").val());
    $("#salesForm").submit();
}

  // Save submit: validates and sends current lines array via hidden input
  $('#salesForm').on('submit', function(e){
    if (!$('#hdLineId').val()) { e.preventDefault(); alert('Please select a Line first.'); $lineInput.focus(); return; }
    if (!$('#hdCustomerId').val()) { e.preventDefault(); alert('Please select a customer.'); $customerInput.focus(); return; }
    if (linesSelected.length < 1) { e.preventDefault(); alert('Please add at least one product.'); $productsContainer.find('.productInput').first().focus(); return; }

    // set customer_name just in case
    $('#hdCustomerName').val($('#customerInput').val());
    // set lines JSON
    $('#hdLinesJson').val(JSON.stringify(linesSelected));
    // allow submit to server
  });

  // Clear page
  $('#clearPageBtn').on('click', function(){
    if (!confirm('Clear the form and all entered data?')) return;
    $('#salesForm')[0].reset();
    $('#hdLineId,#hdCustomerId,#hdCustomerName,#hdCustomerAddress,#hdCustomerPhone,#hdLinesJson').val('');
    $lineSuggestions.addClass('d-none').html('');
    $customerSuggestions.addClass('d-none').html('');
    init();
  });

  // escape helper
  function escapeHtml(s) {
    if (s === null || s === undefined) return '';
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
  }
});
</script>
<script>
function loadTodayData() {
    $.ajax({
        url: "<?php echo e(route('user.sales.todaysales')); ?>",
        method: "GET",
        success: function (res) {
            
            let tbody = $("#today_sales");
            tbody.empty();

            if (!res.data.length) {
                tbody.append(`<tr><td colspan="7" class="text-center">No sales today</td></tr>`);
                return;
            }

            res.data.forEach((p, index)=> {
                let items = p.items
                    .map(i => `${i.price} | ${i.product_name} | ${i.qty}`)
                    .join("<br>");

                tbody.append(`
                           <tr data-id="${p.id}">
                        <td>${index + 1}</td>
                        <td>${p.line}</td>
                        <td>${p.customer}</td>
                        <td>${items}</td>
                        <td>₹ ${p.total_amount}</td>
                        <td>₹ ${p.paid_amount}</td>
                        <td>${p.time}</td>
                          <td>
                            <button class="btn btn-sm btn-danger deleteRow">
                                <i class="bi bi-trash"></i>
                            </button>
                    </tr>
                    </tr>
                `);
            });
        }
    });
}

$(document).ready(function () {
    loadTodayData();
});
</script>


<script>
  
const SOFT_DELETE_URL = "<?php echo e(route('user.sales.softDelete', ['sale' => '__ID__'])); ?>";
$(document).on('click', '.deleteRow', function () {
    if (!confirm('Delete this sale?')) return;

    const $row = $(this).closest('tr');
    const id = $row.data('id');

    if (!id) {
        alert('Invalid ID');
        return;
    }

    const url = SOFT_DELETE_URL.replace('__ID__', id);

    $.ajax({
        url: url,
        type: 'DELETE',
        data: {
            _token: "<?php echo e(csrf_token()); ?>"
        },
        success: function (res) {
            console.log(res.message);
            $row.fadeOut(300, function () {
                $(this).remove();
            });
        },
        error: function (xhr) {
            console.error(xhr.responseText);
            alert('Delete failed');
        }
    });
});

</script>

<script>
document.addEventListener("DOMContentLoaded", function () {

    let input = document.getElementById("tamilInput");

    // Disable Windows IME popup suggestions
    input.setAttribute("autocomplete", "off");
    input.setAttribute("autocorrect", "off");
    input.setAttribute("autocapitalize", "off");
    input.setAttribute("spellcheck", "false");

    // Disable IME for this specific field
    input.style.imeMode = "disabled";

    // Prevent IME suggestion popup completely
    input.addEventListener("compositionstart", function(e) {
        e.preventDefault();  
    });

    input.addEventListener("compositionupdate", function(e) {
        e.preventDefault();
    });

    input.addEventListener("compositionend", function(e) {
        e.preventDefault();
    });

});
</script>
<script>
document.addEventListener("keydown", function(e) {

    // If user is typing inside input, textarea — ignore backspace
    const active = document.activeElement;
    const typingTags = ["INPUT", "TEXTAREA"];

    if (typingTags.includes(active.tagName)) return;

    // Backspace = go back
    if (e.key === "Backspace") {
        e.preventDefault();
        window.location.href = "<?php echo e(route('user.dashboard')); ?>";
    }
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layout.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\mandi\resources\views/user/sales/create.blade.php ENDPATH**/ ?>