@include('header')

       <!--start content-->
       <main class="page-content">
        <!--breadcrumb-->
        <div class="page-breadcrumb d-none d-sm-flex align-items-center mb-3">
          <div class="breadcrumb-title pe-3">Dashboard</div>
          <div class="ps-3">
            <nav aria-label="breadcrumb">
              <ol class="breadcrumb mb-0 p-0">
                <li class="breadcrumb-item"><a href="javascript:;"><i class="bx bx-home-alt"></i></a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">Sales</li>
                <li class="breadcrumb-item">
                    
                </li>
              </ol>
            </nav>
          </div>

          
        </div>
        <!--end breadcrumb-->

           <div class="card">
             <div class="card-body">
               <div class="d-flex align-items-center">
                  <h5 class="mb-0">Sales Details</h5>
                   <form class="ms-auto position-relative">
                     <div class="position-absolute top-50 translate-middle-y search-icon px-3"><i class="bi bi-search"></i></div>
                     <input class="form-control ps-5" type="text" placeholder="search">
                   </form>
               </div>
                    <form class="ms-auto" id="addForm">
                      <div class="btn-group">
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleVerticallycenteredModal">Add Sales</button>
                        <div class="modal fade" id="exampleVerticallycenteredModal" tabindex="-1" aria-hidden="true">
                          <div class="modal-dialog modal-dialog-centered modal-xl">
                            <div class="modal-content">
                              <div class="modal-header border border-0">
                                <h5 class="modal-title">Add Sales</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                              </div>
                              <div class="modal-body">
                                
                                <div class="col-md-12 mb-3">
                                  <label for="validationDefault01" class="form-label">Customer's name</label>
                                  <select class="form-control" id="customer_list">
                                    @foreach($customers as $customer)
                                      <option value="{{$customer->id}}">{{$customer->name}}</option>
                                    @endforeach
                                  </select>
                                  <div class="accordion" id="accordionExample">
                                    <div class="accordion-item p-0">
                                      <div class="accordion-header" id="headingThree">
                                        <button class="accordion-button p-2 collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
                                          Add Customer
                                        </button>
                                      </div>
                                      <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample">
                                        <div class="accordion-body">
                                          <div class="row">
                                            <div class="col-md-6">
                                              <label for="validationDefault01" class="form-label">Full name</label>
                                              <input type="text" id="new_name" class="form-control" id="validationDefault02" value="">
                                            </div>
                                            <div class="col-md-6">
                                              <label for="validationDefault01" class="form-label">Email</label>
                                              <input type="text" id="new_email" class="form-control" id="validationDefault02" value="">
                                            </div>
                                          </div>
                                          <div class="row">
                                            <div class="col-md-6">
                                              <label for="validationDefault01" class="form-label">Phone</label>
                                              <input type="text" id="new_phone" class="form-control" id="validationDefault02" value="">
                                            </div>
                      
                                            <div class="col-md-6">
                                              <label for="validationDefault01" class="form-label">Address</label>
                                              <input type="text" id="new_address" class="form-control" id="validationDefault02" value="">
                                            </div>
                                          </div>

                                          <div class="col-12 mt-2">
                                            <button type="button" data-bs-dismiss="modal" class="btn btn-primary btn-sm" id="addCustomerButton">
                                              Add Customer
                                            </button>
                                          </div>
                                          
                                        </div>
                                      </div>
                                    </div>
                                  </div>

                                </div>

                                <div class="row">
                                  <div class="col-6">
                                      <div class="col-md-12 mb-3">
                                        <label for="validationDefault01" class="form-label">Product name</label>
                                        <select class="form-control" id="product_list">
                                          @foreach($products as $product)
                                            <option value="{{$product->id}}">{{$product->name}}</option>
                                          @endforeach
                                        </select>
                                      </div>
                                  </div>
                                  <div class="col-6">
                                    <div class="col-md-12 mb-3">
                                      <label for="validationDefault02" class="form-label">Quantity</label>
                                      <input type="number" id="quantity" value="1" class="form-control" id="validationDefault02" required>
                                    </div>
                                  </div>
                                  <div class="col-3">
                                    <button type="button" class="btn btn-primary btn-sm mb-2" id="add_button">Add Product</button>
                                  </div>
                                </div>

                                <div class="col-md-12 mb-3">
                                  <label for="validationDefault01" class="form-label">Items Summary</label>
                                  <table class="table table-striped w-50" style="font-weight: bold;">
                                      <thead>
                                        <tr>
                                          <th>Product</th>
                                          <th>Quantity</th>
                                          <th>Price</th>
                                          <th>Amount</th>
                                        </tr>
                                      </thead>

                                      <tbody id="item_list" >
                                          
                                      </tbody>
                                  </table>
                                  
                                </div>

                      
                                <div class="col-md-12 mb-3">
                                  <input type="hidden" id="jsonOutput" name="jsonOutput" class="form-control" id="validationDefault02"  required>
                                </div>

                                <div class="col-md-12 mb-3">
                                  <label for="validationDefault02" class="form-label">Amount</label>
                                  <input type="number" id="amount" name="amount" class="form-control" id="validationDefault02"  required>
                                </div>

                                <div class="col-md-12 mb-3">
                                  <label for="validationDefault02" class="form-label">Paid</label>
                                  <input type="number" id="paid" name="paid" class="form-control" id="validationDefault02" required>
                                </div>

                                <div class="col-md-12 mb-3">
                                  <label for="validationDefault02" class="form-label">Balance</label>
                                  <input type="number" id="balance" name="balance" class="form-control" id="validationDefault02" required>
                                </div>

                              </div>
                              <div class="modal-footer border border-0">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <button type="submit" data-bs-dismiss="modal" class="btn btn-primary">Save changes</button>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </form>
               <div class="table-responsive mt-3">
                 <table class="table align-middle">
                   <thead class="table-secondary">
                     <tr>
                      <th>#</th>
                      <th>Customer's Name</th>
                      <th>Products Purchased</th>
                      <th>Amount</th>
                      <th>Paid</th>
                      <th>Balance</th>
                      <th>Date/Time</th>
                      <th>Actions</th>
                     </tr>
                   </thead>
                   <tbody id="tableBody">
                        @foreach($sales as $sale)
                        <tr>
                              <td>#</td>
                             <td>{{$sale->customer->name}}</td>
                             <td>
                                  @php
                                      $products2 = json_decode($sale->products);
                                  @endphp
                                  <ul>
                                    @foreach($products2 as $item)
                                    <li>Purchased {{$item->quantity}} unit(s) of {{$item->name}} for &#x20A6;{{ number_format($item->amount, 2)}} (&#x20A6;{{ number_format($item->price, 2) }} each)</li>
                                    @endforeach
                                  </ul>
                                  

                             </td>  
                             <td>&#x20A6;{{number_format($sale->amount,2)}}</td>
                             <td>&#x20A6;{{number_format($sale->paid,2)}}</td>
                             <td>&#x20A6;{{number_format($sale->balance,2)}}</td> 
                             <td>{{$sale->date}}</td>
                             <td></td> 
                        </tr>
                             
                        @endforeach
                   </tbody>
                 </table>
               </div>
             </div>
           </div>

       </main>
       <!--end page main-->

       <!--start overlay-->
        <div class="overlay nav-toggle-icon"></div>
       <!--end overlay-->

       <!--start footer-->
       <footer class="footer">
        <div class="footer-text">
           Copyright © 2022. All right reserved.
        </div>
        </footer>
        <!--end footer-->

       <!--Start Back To Top Button-->
		     <a href="javaScript:;" class="back-to-top"><i class='bx bxs-up-arrow-alt'></i></a>
       <!--End Back To Top Button-->

       <!--start switcher-->
       <div class="switcher-body">
        <button class="btn btn-primary btn-switcher shadow-sm" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasScrolling" aria-controls="offcanvasScrolling"><i class="bi bi-paint-bucket me-0"></i></button>
        <div class="offcanvas offcanvas-end shadow border-start-0 p-2" data-bs-scroll="true" data-bs-backdrop="false" tabindex="-1" id="offcanvasScrolling">
          <div class="offcanvas-header border-bottom">
            <h5 class="offcanvas-title" id="offcanvasScrollingLabel">Theme Customizer</h5>
            <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas"></button>
          </div>
          <div class="offcanvas-body">
            <h6 class="mb-0">Theme Variation</h6>
            <hr>
            <div class="form-check form-check-inline">
              <input class="form-check-input" type="radio" name="inlineRadioOptions" id="LightTheme" value="option1">
              <label class="form-check-label" for="LightTheme">Light</label>
            </div>
            <div class="form-check form-check-inline">
              <input class="form-check-input" type="radio" name="inlineRadioOptions" id="DarkTheme" value="option2">
              <label class="form-check-label" for="DarkTheme">Dark</label>
            </div>
            <div class="form-check form-check-inline">
              <input class="form-check-input" type="radio" name="inlineRadioOptions" id="SemiDarkTheme" value="option3">
              <label class="form-check-label" for="SemiDarkTheme">Semi Dark</label>
            </div>
            <hr>
            <div class="form-check form-check-inline">
              <input class="form-check-input" type="radio" name="inlineRadioOptions" id="MinimalTheme" value="option3" checked>
              <label class="form-check-label" for="MinimalTheme">Minimal Theme</label>
            </div>
            <hr/>
            <h6 class="mb-0">Header Colors</h6>
            <hr/>
            <div class="header-colors-indigators">
              <div class="row row-cols-auto g-3">
                <div class="col">
                  <div class="indigator headercolor1" id="headercolor1"></div>
                </div>
                <div class="col">
                  <div class="indigator headercolor2" id="headercolor2"></div>
                </div>
                <div class="col">
                  <div class="indigator headercolor3" id="headercolor3"></div>
                </div>
                <div class="col">
                  <div class="indigator headercolor4" id="headercolor4"></div>
                </div>
                <div class="col">
                  <div class="indigator headercolor5" id="headercolor5"></div>
                </div>
                <div class="col">
                  <div class="indigator headercolor6" id="headercolor6"></div>
                </div>
                <div class="col">
                  <div class="indigator headercolor7" id="headercolor7"></div>
                </div>
                <div class="col">
                  <div class="indigator headercolor8" id="headercolor8"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
       </div>
       <!--end switcher-->

  </div>
  <!--end wrapper-->


  <!-- Bootstrap bundle JS -->
  <script src="assets/js/bootstrap.bundle.min.js"></script>
  <!--plugins-->
    <script src="assets/js/jquery.min.js"></script>
  <script src="js/session_check.js"></script>
  <script src="assets/plugins/simplebar/js/simplebar.min.js"></script>
  <script src="assets/plugins/metismenu/js/metisMenu.min.js"></script>
  <script src="assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
  <script src="assets/plugins/vectormap/jquery-jvectormap-2.0.2.min.js"></script>
  <script src="assets/plugins/vectormap/jquery-jvectormap-world-mill-en.js"></script>
  <script src="assets/js/pace.min.js"></script>
  <script src="assets/plugins/chartjs/js/Chart.min.js"></script>
  <script src="assets/plugins/chartjs/js/Chart.extension.js"></script>
  <script src="assets/plugins/select2/js/select2.min.js"></script>
  <script src="assets/js/form-select2.js"></script>
  <!--app-->
  <script src="assets/js/app.js"></script>
  <script src="assets/js/index4.js"></script>
 

</body>

</html>

<script>
  const productsArray = [];
let total = 0;
    // Call functions
    function attachDeleteHandlers() {
        const buttons = document.querySelectorAll('.delete-btn');
        buttons.forEach((button, index) => {
          button.addEventListener('click', function() {
            console.log('Button index: ', index);
            deleteProduct(index)
            const row = this.closest('tr');  // Find the closest <tr> (the row that contains the button)
            row.remove();  // Remove the row
          });
        });
    }

    function deleteProduct(index) {
        productsArray.splice(index, 1);  // Remove the product at the given index

        updateJsonOutput();
    }
   
    function updateJsonOutput() {
        document.getElementById('jsonOutput').value = JSON.stringify(productsArray, null, 2);
        // Summing up the quantity of all products
        const totalQuantity = productsArray.reduce((accumulator, product) => {
            return accumulator + product.amount;
        }, 0);  // Start the accumulator at 0

        console.log('Total Quantity:', totalQuantity);

        document.getElementById('amount').value = totalQuantity


    }
    $(document).ready(function() {

        var currentPage = 1;
        var pageSize = 20; // Number of items per page
        var allproducts=[];
        
    // Initial data load
       fetchPaginatedData(currentPage, pageSize);
       

        // Fetch Page with Pagination
        function fetchPaginatedData(page, limit) {
            $.ajax({
                url: '',
                type: 'GET',
                data: { page: page, limit: limit},
                dataType: 'json',
                success: function(response) {
                    console.log(response)
                    allproducts=response.product_data;
                    displayData(response.page_data.items,response.customer_data,response.product_data);
                    renderPagination(response.page_data.totalPages);
                    fetchCustomers(response.customer_data)
                    fetchProducts(response.product_data)
                
                },
                error: function(xhr, status, error) {
                    console.error();
                }
            });
        }

        function fetchCustomers(items) {
            var selectEl = $('#customer_list');
            selectEl.empty(); // Clear existing data
            $.each(items, function(index, item) {
                var option = '<option value="'+item.id+'">';
                option += item.name + '</option>';
                selectEl.append(option);
            });

            var selectEl2 = $('.customer_list2');
            selectEl2.empty(); // Clear existing data
            $.each(items, function(index, item) {
                var option = '<option value="'+item.id+'">';
                option += item.name + '</option>';
                selectEl2.append(option);
            });
        }

        function fetchProducts(items) {
            

            var selectEl = $('#product_list');
            selectEl.empty(); // Clear existing data
            $.each(items, function(index, item) {
                var option = '<option value="'+item.id+'">';
                option += item.name + '</option>';
                selectEl.append(option);
            });

            var selectEl2 = $('.product_list2');
            selectEl2.empty(); // Clear existing data
            $.each(items, function(index, item) {
                var option = '<option value="'+item.id+'">';
                option += item.name + '</option>';
                selectEl2.append(option);
            });
        }


        function hasValue(obj, value) {
            for (let key in obj) {
                console.log("id"+obj[key]["id"])
                if (obj[key]["id"] === value) {
                    
                    return obj[key]["name"];
                }
            }
            return "Not Available";
        }

        function displayProducts(items) {
            const itemArray = JSON.parse(items);
            let obj = '';
            itemArray.forEach(product => {
                // const p = document.createElement('p');
                obj += `Purchased ${product.quantity} unit(s) of ${product.name} at  &#x20A6;${product.price} <br>`;
                // return p;
                // document.write(product.name)
              }); 
            return obj
              
        }
        
        // Display data on Table
        // function displayData(items,customers,products) {
        //     var tableBody = $('#tableBody');
        //     tableBody.empty(); // Clear existing data

        //     $.each(items, function(index, item) {
        //         var row = '<tr>';
        //         row += '<td>' + (index + 1) + '</td>';
        //         row += '<td>' +hasValue(customers,item.customer_id) + '</td>';
        //         row += '<td id="display_products">' +displayProducts(item.products) + '</td>';
        //         row += '<td> &#x20A6;' + item.amount + '</td>';
        //         row += '<td> &#x20A6;' + item.paid + '</td>';
        //         row += '<td> &#x20A6;' + item.balance + '</td>';
        //         row += '<td>' + item.created_at + '</td>';
        //         row += '<td><div class="table-actions d-flex align-items-center gap-3 fs-6">' + '<input class="id" type="hidden" value="'+item.id+'">' + '<form action="php/sales.php"><input type="hidden" name="method" value="delete"><input type="hidden" name="id" value="'+item.id+'"><button type="submit" id="deleteButton" class="text-danger border-0 bg-white" title="Delete"><i class="bi bi-trash-fill"></i></button></form>'
        //         // '<a class="text-primary" data-bs-toggle="modal" data-bs-target="#updateModal'+item.id+'" title="Edit"><i class="bi bi-pencil-fill"></i></a>'+'<div class="modal fade" id="updateModal'+item.id+'" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-dialog-centered modal-xl"><form action="php/sales.php" class="modal-content"><div class="modal-header border border-0"><h5 class="modal-title">Update Sales</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><input type="hidden" name="update" value="update"><input type="hidden" name="id" value="'+item.id+'"><div class="col-md-12 mb-3"><label for="validationDefault01" class="form-label">customer name</label><select name="customer_name" class="form-control customer_list2" id="customer_list2"></select></div><div class="row"><div class="col-6"><div class="col-md-12 mb-3"><label for="validationDefault01" class="form-label">product name</label><select name="product_name" class="form-control product_list2" id="product_list2"></select></div></div><div class="col-6"><div class="col-md-12 mb-3"><label for="validationDefault02" class="form-label">Quantity</label><input type="number" name="quantity2" id="quantity2" value="'+item.quantity+'" class="form-control" id="validationDefault02" value="" required></div></div><div class="col-3"><button type="button" class="btn btn-primary btn-sm mb-2" id="add_button2">Add Product</button></div></div><div class="col-md-12 mb-3"><label for="validationDefault01" class="form-label">Items Summary</label><table class="table table-striped w-50" style="font-weight: bold;"><thead><tr><th>Product</th><th>Quantity</th><th>Price</th><th>Amount</th></tr></thead><tbody id="item_list2" ></tbody></table></div><div class="col-md-12 mb-3"><input type="hidden" id="jsonOutput2" value="'+item.products+'" class="form-control" id="validationDefault02"  required></div><div class="col-md-12 mb-3"><label for="validationDefault02" class="form-label">Amount</label><input type="number" id="amount" name="amount" class="form-control" id="validationDefault02" value="'+item.amount+'" required></div><div class="col-md-12 mb-3"><label for="validationDefault02" class="form-label">Paid</label><input type="number" name="paid" id="paid" value="'+item.paid+'" class="form-control" id="validationDefault02" value="" required></div><div class="col-md-12 mb-3"><label for="validationDefault02" class="form-label">Balance</label><input type="number" name="balance" id="balance" value="'+item.balance+'" class="form-control" id="validationDefault02" value="" required></div></div><div class="modal-footer border border-0"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button type="submit" class="btn btn-primary">Save changes</button></div></form></div></div>'+'<form action="php/sales.php"><input type="hidden" name="method" value="delete"><input type="hidden" name="id" value="'+item.id+'"><button type="submit" id="deleteButton" class="text-danger border-0 bg-white" title="Delete"><i class="bi bi-trash-fill"></i></button></form>'+
        //         '</div></td>';
        
        //         row += '</tr>';
        //         tableBody.append(row);
        //     });
        // }

        // Render Pagnation
        function renderPagination(totalPages) {
        var pagination = $('#pagination');
        pagination.empty(); // Clear existing pagination controls

        var startPage = 1;
        var endPage = Math.min(totalPages, 10); // Limit to 10 visible pages

        // Previous link
        var prevLink = $('<a>').addClass('page-link').text('Previous');
        prevLink.click(function() {
            if (currentPage > 1) {
                currentPage--;
                renderPagination(totalPages); // Re-render pagination
                fetchPaginatedData(currentPage, pageSize);
            }
        });
        pagination.append(prevLink);

        for (var i = startPage; i <= endPage; i++) {
            var pageLink = $('<a>').addClass('page-link').text(i);
            
            // Add active class to the current page
            if (i === currentPage) {
                pageLink.addClass('active');
            }

            pageLink.click(function() {
                currentPage = parseInt($(this).text());
                renderPagination(totalPages); // Re-render pagination
                fetchPaginatedData(currentPage, pageSize);
            });
            pagination.append(pageLink);
        }

        // Next link
        var nextLink = $('<a>').addClass('page-link').text('Next');
        nextLink.click(function() {
            if (currentPage < totalPages) {
                currentPage++;
                renderPagination(totalPages); // Re-render pagination
                fetchPaginatedData(currentPage, pageSize);
            }
        });
        pagination.append(nextLink);
        }



$('#addCustomerButton').click(function() {
    var name = $('#new_name').val().trim();
    var email = $('#new_email').val().trim();
    var phone = $('#new_phone').val().trim();
    var address = $('#new_address').val().trim();
    $.ajax({
        url: 'php/customers.php',
        type: 'POST',
        data: { name: name, email: email,phone:phone,address:address},
        success: function(response) {       
            console.log(response)
            fetchPaginatedData(currentPage, pageSize);
        }
    });
});



// Show modal when "Add" button is clicked
 $('#add_button').click(function() {

    

    let product_listing  = document.getElementById('product_list');
    let table  = document.getElementById('item_list');
    let qty = document.getElementById('quantity')

    let products = document.getElementById('products')

    let product_array = @json($products);
    const product = product_array.find(item => item.id === Number(product_listing.value));
    const row = document.createElement('tr');
    const product_cell = document.createElement('td');
    const quantity_cell = document.createElement('td');
    const price_cell = document.createElement('td');
    const amount_cell = document.createElement('td');
    const trash_cell = document.createElement('td');
    const trash = document.createElement('button');
    trash.setAttribute('class','text-danger bi bi-trash-fill delete-btn border-0');
    trash.setAttribute('type','button');
    trash.setAttribute('onclick','attachDeleteHandlers()');
    trash_cell.appendChild(trash)
    product_cell.innerText = product.name;
    quantity_cell.innerText = qty.value;
    price_cell.innerText = product.price;
    amount_cell.innerText = product.price * qty.value;


    

    const newProduct = {id: product.id,name: product.name,price: product.price,quantity: qty.value,amount: product.price * qty.value};
    
    productsArray.push(newProduct);
    updateJsonOutput();

    // Clear the form fields for the next product entry

    row.appendChild(product_cell);
    row.appendChild(quantity_cell);
    row.appendChild(price_cell);
    row.appendChild(amount_cell);
    row.appendChild(trash_cell);
    table.appendChild(row);
 });

 $('#add_button2').click(function() {


    let product_listing  = document.getElementById('product_list2');
    let table  = document.getElementById('item_list2');
    let qty = document.getElementById('quantity2')

    let products = document.getElementById('products')


    const product = allproducts.find(item => item.id === Number(product_listing.value));
    const row = document.createElement('tr');
    const product_cell = document.createElement('td');
    const quantity_cell = document.createElement('td');
    const price_cell = document.createElement('td');
    const amount_cell = document.createElement('td');
    const trash_cell = document.createElement('td');
    const trash = document.createElement('button');
    trash.setAttribute('class','text-danger bi bi-trash-fill delete-btn border-0');
    trash.setAttribute('type','button');
    trash.setAttribute('onclick','attachDeleteHandlers()');
    trash_cell.appendChild(trash)
    product_cell.innerText = product.name;
    quantity_cell.innerText = qty.value;
    price_cell.innerText = product.price;
    amount_cell.innerText = product.price * qty.value;


    

    const newProduct = {id: product.id,name: product.name,price: product.price,quantity: qty.value,amount: product.price * qty.value};
    
    productsArray.push(newProduct);
    updateJsonOutput();

    // Clear the form fields for the next product entry

    row.appendChild(product_cell);
    row.appendChild(quantity_cell);
    row.appendChild(price_cell);
    row.appendChild(amount_cell);
    row.appendChild(trash_cell);
    table.appendChild(row);
 });

 // Close the modal when close button is clicked
 $('.btn-close').click(function() {
    // $('#myModal').css('display', 'none');
    $('#addModal').hide();
    
 });

 // Add new user when form is submitted
 $('#addForm').submit(function(e) {
     e.preventDefault();
     var customer = $('#customer_list').val().trim();
     var productjson = $('#jsonOutput').val().trim();
     var product = JSON.stringify(productjson);
     var amount = $('#amount').val().trim();
     var paid = $('#paid').val().trim();
     var balance = $('#balance').val().trim();

     $.ajax({
         url: 'add_sales',
         type: 'POST',
         headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
         data: { customer: customer, product: product , amount: amount, paid: paid, balance: balance  },
         success: function(response) {
             $('#addModal').css('display', 'none');
             console.log(response)
             fetchPaginatedData(currentPage, pageSize);
         }
     });
 });


 // Row click event to toggle selection
 var selectedRow = null;
$('#myTable tbody').on('click', 'tr', function() {
     if(selectedRow){
         selectedRow.removeClass('selected');
     }
     selectedRow = $(this);
     selectedRow.addClass('selected');
 });

 // Update button click event to open the modal
 $('#updateButton').click(function() {
     if (!selectedRow) {
       alert('Please select a Expense to update.');
     }
     
     var id = selectedRow.find("td:eq(0)").text(); 
    //  var product = selectedRow.find("td:eq(1)").text(); 
     var quantity = selectedRow.find("td:eq(2)").text(); 
     var amount = selectedRow.find("td:eq(3)").text(); 
     $('#updateModal #id').val(id);
    //  $('#updateModal #product').val(product);
     $('#updateModal #quantity').val(quantity);
     $('#updateModal #amount').val(amount);
     $('#updateModal').show();
    
 });
 // Close modal
 $('.btn-close').click(function() {
     $('#updateModal').hide();
 });



  // Delete button click event
 $('#deleteButton').click(function() {
     if(!selectedRow){
         alert('Please select a user to delete.');
         return;
     }
     
    var id = selectedRow.find("td:eq(0)").text(); 
     
     if (confirm('Are you sure you want to delete this Expense?')) {
         // Perform your AJAX request to delete the user
           $.ajax({
             url: 'php/sales.php',
             type: 'DELETE',
             data: { id: id },
             success: function() {
                 fetchPaginatedData(currentPage, pageSize);
             }
         }); 

         // Assuming deletion is successful, remove the row
         selectedRow.remove();
         selectedRow = null; // Reset selection
     }
 });
 
}); 
</script>