<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Manager' || $_SESSION['type'] == 'Cashier' || $_SESSION['type'] == 'Accountant')){
            header("location:logout.php");
}


?>

<html lang="en">


<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
        <title>THE FARM</title>

    <!-- Favicon icon -->
    <link rel="icon" type="./quixlab/image/png" sizes="16x16" href="./quixlab/images/favicon.png">
    <!-- Pignose Calender -->
    <link href="./quixlab/plugins/pg-calendar/css/pignose.calendar.min.css" rel="stylesheet">
    <!-- Chartist -->
    <link rel="stylesheet" href="./quixlab/plugins/chartist/css/chartist.min.css">
    <link rel="stylesheet" href="./quixlab/plugins/chartist-plugin-tooltips/css/chartist-plugin-tooltip.css">
    <!-- Custom Stylesheet -->
    <link href="./quixlab/css/design.css" rel="stylesheet">
    <!-- DataTables with Buttons -->
    <link rel="stylesheet" href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css">
    <link href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="./quixlab/css/buttons.bootstrap.min.css" rel="stylesheet" />

</head>
<style>
 body {
            background-image: url("./quixlab/images/pharm.webp");
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
            height: 100vh;
        }
  </style>
   
    
    
     <style>
        .tabz {
            background-color: rgba(255, 255, 255, 0.5); /* Adjust the alpha (opacity) value as needed */
        }
    </style>


<body>


    <!--*******************
        Preloader start
    ********************-->
    <div id="preloader">
        <div class="loader">
            <svg class="circular" viewBox="25 25 50 50">
                <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="3" stroke-miterlimit="10" />
            </svg>
        </div>
    </div>
    <!--*******************
        Preloader end
    ********************-->
  <div id="main-wrapper">
    
    <!--**********************************
        Main wrapper start
    ***********************************-->
     <div class="nav-header">
            <div class="brand-logo">
                <a href="index.html">
                    <b class="logo-abbr"><img src="images/logo.png" alt=""> </b>
                    <span class="logo-compact"><img src="./images/logo-compact.png" alt=""></span>
                    <span class="brand-title">
                        <img src="images/logo-text.png" alt="">
                    </span>
                </a>
            </div>
        </div>

        <!--**********************************
            Nav header start
        ***********************************-->
      <div class="header">    
            <div class="header-content clearfix">
                
                <div class="nav-control">
                    <div class="hamburger">
                        <span class="toggle-icon"><i class="icon-menu"></i></span>
                    </div>
                </div>
                <div class="header-left">
                    <div class="input-group icons">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-transparent border-0 pr-2 pr-sm-3" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                        </div>
                       <input type="text" class="form-control" placeholder="Search Customer" aria-label="Search Customer" id="client" name="client" onkeyup="searchClients(this.value)" required>
<div id="clientsDropdown"></div>
                          <input type="hidden" class="form-control" name="client-id" id="client-id">
                        <div class="drop-down   d-md-none">
							<form action="#">
								<input type="text" class="form-control" placeholder="Search">
							</form>
                        </div>
                    </div>
                </div>
                <div class="header-right">
                    <ul class="clearfix">
                  <li class="icons dropdown">
    <a href="#" data-toggle="modal" data-target="#cartModal">
        <i class="mdi mdi-cart"></i>
        <span class="badge badge-pill gradient-1">
    <?php
    $itemCount = 0;
    $totl = 0;

    if (isset($_SESSION['cartz']) && !empty($_SESSION['cartz'])) {
        foreach ($_SESSION['cartz'] as $index => $item) {
            $itemCount++;

            // Check if price and quantity are numeric
            if (is_numeric($item['price']) && is_numeric($item['quantity'])) {
                $subtotal = $item['price'] * $item['quantity'];
                $totl += $subtotal;
            }
        }
        echo $itemCount;
    } else {
        echo "0";
    }
    ?>
</span>


    </a>
</li>

                        <li class="icons dropdown"><a href="javascript:void(0)" data-toggle="dropdown">
                                <i class="mdi mdi-bell-outline"></i>
                                <span class="badge badge-pill gradient-2">3</span>
                            </a>
                            <div class="drop-down animated fadeIn dropdown-menu dropdown-notfication">
                              
                                
                            </div>
                        </li>
                        <li class="icons dropdown d-none d-md-flex">
                            <a href="javascript:void(0)" class="log-user"  data-toggle="dropdown">
                                <span>English</span>  <i class="fa fa-angle-down f-s-14" aria-hidden="true"></i>
                            </a>
                            <div class="drop-down dropdown-language animated fadeIn  dropdown-menu">
                                <div class="dropdown-content-body">
                                    <ul>
                                        <li><a href="javascript:void()">English</a></li>
                                        <li><a href="javascript:void()">Dutch</a></li>
                                    </ul>
                                </div>
                            </div>
                        </li>
                        <li class="icons dropdown">
                            <div class="user-img c-pointer position-relative"   data-toggle="dropdown">
                                <span class="activity active"></span>
                                 <img class="profileImage" height="40" width="40" alt="">
                            </div>
                            <div class="drop-down dropdown-profile animated fadeIn dropdown-menu">
                                <div class="dropdown-content-body">
                                    <ul>
                                        <li>
                                            <a href="app-profile.html"><i class="icon-user"></i> <span>Profile</span></a>
                                        </li>
                                        <li>
                                            <a href="javascript:void()">
                                                <i class="icon-envelope-open"></i> <span>Inbox</span> <div class="badge gradient-3 badge-pill gradient-1">3</div>
                                            </a>
                                        </li>
                                        
                                        <hr class="my-2">
                                        <li>
                                            <a href="page-lock.html"><i class="icon-lock"></i> <span>Lock Screen</span></a>
                                        </li>
                                        <li><a href="page-login.html"><i class="icon-key"></i> <span>Logout</span></a></li>
                                    </ul>
                                </div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
         
        <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

        <!--**********************************
            Sidebar start
        ***********************************-->
        <div class="nk-sidebar">           
    <div class="nk-nav-scroll">
        <ul class="metismenu" id="menu">
            <li class="nav-label">Dashboard</li>
             <?php


// Define arrays for each user role and the corresponding allowed links
$managerLinks = array(
    "orders.php", 
    "payments.php", 
    "reports.php", 
    "purchases.php", 
    "employee.php", 
    "reg-customer.php", 
    "inventory.php"
);

$cashierLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "sales.php"
);

$receptionistLinks = array(
    "orders.php", 
    "reg-customer.php", 
    "payments.php", 
    "sales.php"
);

// Check if user is logged in and their role is set in the session
if(isset($_SESSION['type'])) {
    $role = $_SESSION['type'];
    
    // Assign the corresponding links based on the user role
    switch($role) {
        case "Manager":
            $links = $managerLinks;
            break;
        case "Cashier":
            $links = $cashierLinks;
            break;
        case "Accountant":
            $links = $receptionistLinks;
            break;
        default:
            $links = array();
            break;
    }
} else {
    // Redirect user to login page if they are not logged in
    header("Location: login.php");
    exit();
}

?>
            <li>
                <a class="has-arrow" href="javascript:void()" aria-expanded="false">
                    <i class="icon-speedometer menu-icon"></i><span class="nav-text">Dashboard</span>
                </a>
                <ul aria-expanded="false">
                    <li><a href="index.php">Dashboard</a></li>
                    <!-- <li><a href="./index-2.html">Home 2</a></li> -->
                </ul>
            </li>
            <?php 
               foreach($links as $link) {
    $linkText = ucfirst(str_replace(".php", "", $link)); // remove .php extension and capitalize first letter
    echo '<li><a href="' . $link . '"><i class="icon-menu menu-icon"></i><span class="nav-text">' . $linkText . '</span></a></li>';
}

            ?>
            <li>
                <a href="logout.php" aria-expanded="false">
                    <i class="icon-lock menu-icon"></i><span class="nav-text">LogOut</span>
                </a>
            </li>
        </ul>
    </div>
</div>
   
        <!--**********************************
            Sidebar end
        ***********************************-->

        <!--**********************************
            Content body start
        ***********************************-->
        <div class="content-body">

              <div class="container-fluid mt-3">
               
                <div class="row">
                    <div class="col-sm-10">
                        <div class="card">
                            <div class="card-body">
                            <div class="input-group icons">
                                <div class="input-group-prepend">
                                    <span class="input-group-text bg-transparent border-0 pr-2 pr-sm-3" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                                </div>
                                <input type="search" class="form-control" placeholder="Search Inventory" aria-label="Search Inventory" id="searchInput">
                            </div>
                            <div class="search-results">
                            </div>
                        </div>
                      </div>  
                    </div>
                   
                   
                    <div class="col-sm-1">
                       <div class="card">
                          <div class="input-group icons">
                            <span>
                                <input type="checkbox" id="chkInvoice">
                                <label class="toggle" for="chkInvoice">Invoice</label>
                            </span>
                           
                          </div>
                        </div>
                   </div>
                       <div class="col-sm-1">
                       <div class="card">
                          <div class="input-group icons">
                           <span>
                                <input type="checkbox" id="chkReceipt">
                                <label class="toggle" for="chkReceipt">Receipt</label>
                            </span>
                          </div>
                        </div>
                   </div> 
                     
               </div>
<div class="row" id="invoiceRow" style="display: none;">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body" id="inv">
                    <div class="invoice-title text-right">
                      <h4 class="float-end font-size-15">Invoice <span class="salesReceipt"></span></h4>
                       
                    </div>

                    

                    <div class="row">
                        <div class="col-sm-6">
                            <div class="text-muted">
                                <h5 class="font-size-16 mb-3">Billed To:</h5>
                                <h5 class="font-size-15 mb-2"><span id="clientname"></span> </h5>
                                <p class="mb-1"><span id="location"></span></p>
                                <p><span id="phone"></span></p>
                                <p><input type="number" required readonly id="cid" name="clid" style="border: none;"></p>
                                 <p><input type="hidden"  id="cphone" name="cphone" style="border: none;"></p>
                            </div>
                        </div>
                        <!-- end col -->
                       
                        <!-- end col -->
                    </div>
                    <!-- end row -->
                    
                    <div class="py-2">
                        <div class="text-center">
                            <h4 class="font-size-15">Invoice Details</h4>
                        </div>  
                      <div class="table-responsive">
                            <table class="table align-middle table-nowrap table-centered mb-0">
                                <thead>
                                     <tr>
                                        <th>No.</th>
                                        <th>Item</th>
                                        <th>Price</th>
                                        <th>Quantity</th>
                                        <th class="text-end">Sub Total</th>
                                    </tr>
                                </thead><!-- end thead -->
                                <tbody  class="cart-display-container">
        <!-- Cart items will be dynamically inserted here using AJAX -->
        <div></div>
    </tbody>

                                    <!-- end tr -->
                               
                            </table><!-- end table -->
                        </div><!-- end table responsive -->
                        <div class="d-print-none mt-4">
                            <div class="float-end">
                              <button id="printButton" class="btn btn-success me-1"><i class="fa fa-print"></i>Print</button>

                              <button class="btn btn-primary w-md">Send </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- end col -->
    </div>
             
<div class="row" id="receiptRow" style="display: none;">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body" id="rct">
                    <div class="invoice-title" style="float: right;">
                      <h4 class="float-end font-size-15">Receipt No #<span class="salesReceipt"></span></h4>

                       
                    </div>

                    

                   
                    <div class="row">
                        <div class="col-sm-6">
                            <div class="text-muted">
                                <h5 class="font-size-16 mb-3"></h5>
                                <h5 class="font-size-15 mb-2"><span id="clientnames"></span> </h5>
                                <p class="mb-1"><span id="locations"></span></p>
                                <p><span id="phones"></span></p>
                                <p><input type="number" required readonly id="cids" name="clids" style="border: none;"></p>
                            </div>
                        </div>
                        <!-- end col -->
                       
                        <!-- end col -->
                    </div>
                    <!-- end row -->
                    
                    <div class="py-2">
                        <div class="text-center">
                            <h4 class="font-size-15">Receipt Details</h4>
                        </div>  
                      <div class="table-responsive">
                             <table class="table  table-nowrap table-centered mb-0">
                                 <thead>
        <tr>
            <th>No.</th>
            <th>Item</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Sub Total</th>
        </tr>
    </thead>
    <tbody  class="cart-display-container">
        <!-- Cart items will be dynamically inserted here using AJAX -->
        <div></div>
    </tbody>
    <tfoot>
        
        <tr>
            <th scope="row" colspan="5" class="border-0"></th>
            <th scope="row" class="border-0 text-right">Payment Method :</th>
            <td class="border-0 text-right" style="border: none;">
                <h4 class="m-0 fw-semibold text-right">
                    <select class="border-0 no-arrow" id="paymethod" style="-webkit-appearance: none; appearance: none; background: url('your-custom-arrow-image.png') no-repeat right center; padding-right: 20px;">
                        <option selected disabled>Select payment method</option>
                        <option class="text-right">Equity</option>
                        <option class="text-right">K.C.B</option>
                        <option class="text-right">Cash</option>
                        <option class="text-right">Mpesa</option>
                    </select>
                </h4>
            </td>
        </tr>
        <!-- Add similar rows for Payment Amount, Shipping Charge, Tax -->
        <tr>
            <th scope="row" colspan="5" class="border-0"></th>
            <th scope="row" class="border-0 text-right">Payment amount :</th>
            <td class="border-0 text-right">
                <h4 class="m-0 fw-semibold text-right">
                    <input type="number" class="border-0 text-right" id="amount" placeholder="Enter Paid amount" step="0.01">
                </h4>
            </td>
        </tr>
        <tr>
            <th scope="row" colspan="5" class="border-0"></th>
            <th scope="row" class="border-0 text-end">Change:</th>
            <td class="border-0 text-end"><h4 class="m-0 fw-semibold" id="resultOutput">0.00</h4></td>
        </tr>
        <!-- Add similar rows for Shipping Charge, Tax, and Total -->
    </tfoot><!-- end tbody -->
                            </table><!-- end table -->
                        </div><!-- end table responsive -->
                       <div class="d-print-none mt-4">
                            <div class="float-end">
                              <button id="submitButton" class="btn btn-success me-1"><i class="fa fa-print"></i>Print</button>

                              
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div><!-- end col -->
    </div>

                        

        <!--**********************************
            Footer end
        ***********************************-->
    
    <!--**********************************
        Main wrapper end
    ***********************************-->

    <!--**********************************
        Scripts
    ***********************************-->
   
     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="./quixlab/plugins/common/common.min.js"></script>
    <script src="./quixlab/js/custom.min.js"></script>
    <script src="./quixlab/js/settings.js"></script>
    <script src="./quixlab/js/gleek.js"></script>
    <script src="./quixlab/js/styleSwitcher.js"></script>

    <script src="./quixlab/plugins/tables/js/jquery.dataTables.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable/dataTables.bootstrap4.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable-init/datatable-basic.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
     <script>
    const chkInvoice = document.getElementById("chkInvoice");
const chkReceipt = document.getElementById("chkReceipt");
const chkDelivery = document.getElementById("chkDelivery");
const invoiceRow = document.getElementById("invoiceRow");
const receiptRow = document.getElementById("receiptRow");
const deliveryRow = document.getElementById("deliveryRow");

// Add event listeners to the checkboxes
chkInvoice.addEventListener("change", function () {
    invoiceRow.style.display = chkInvoice.checked ? "block" : "none";
});

chkReceipt.addEventListener("change", function () {
    receiptRow.style.display = chkReceipt.checked ? "block" : "none";
});  
chkDelivery.addEventListener("change", function () {
    deliveryRow.style.display = chkDelivery.checked ? "block" : "none";
});  
    </script>
    
    
    <script>
    // Function to update the cart modal content
 
    // Attach a click event listener to the cart icon
    var cartIcon = document.querySelector('.icons .mdi-cart');
    cartIcon.addEventListener('click', function (e) {
        e.preventDefault();
        updateCartModal();
        $('#cartModal').modal('show'); // Show the modal using Bootstrap's modal function
    });
</script>
    
    
 <script>
    // JavaScript code for client-side interaction

    // Function to display the sales receipt number
    async function displaySalesReceipt() {
        try {
            const response = await fetch('./database/get_latest_row.kts.php');
            if (!response.ok) {
                throw new Error('Failed to fetch latest row number');
            }
            const data = await response.json();
            const latestRowNumber = data.latest_row_number;

            // Use querySelector to select the element with the class name 'salesReceipt'
            const salesReceiptSpan = document.querySelector('.salesReceipt');
            
            // Check if the element exists before updating its content
            if (salesReceiptSpan) {
                salesReceiptSpan.textContent = latestRowNumber;
            } else {
                console.error('Element with class name "salesReceipt" not found.');
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    // Call the function to display the sales receipt number when the page loads
    window.onload = displaySalesReceipt;
</script>


    <script>
  // Get references to the input and resultOutput elements
const numberInput = document.getElementById('amount');
const resultOutput = document.getElementById('resultOutput');

// Calculate and update the result when the input changes
numberInput.addEventListener('input', function() {
  // Parse the input value as a number
  const paidAmount = parseFloat(numberInput.value);
  
  // Check if the input is a valid number
  if (!isNaN(paidAmount)) {
    // Calculate the result by subtracting the paidAmount from the total
    const result = <?php echo $totl; ?> - paidAmount;
    
    // Update the resultOutput element with the calculated result
    resultOutput.textContent = result.toFixed(2);
  } else {
    // Handle invalid input (e.g., non-numeric input)
    resultOutput.textContent = 'Invalid input';
  }
});
      

    </script>
    
<script>
        // Get the current date
        const today = new Date();

        // Extract the date components (year, month, day)
        const year = today.getFullYear();
        const month = today.getMonth() + 1; // Months are 0-based, so add 1
        const day = today.getDate();

        // Format the date as "YYYY-MM-DD" (or customize it as needed)
        const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

        // Display the formatted date in the HTML element with the id "date"
        document.getElementById('date').textContent = formattedDate;
    </script>


<script>
    function searchClients(keyword) {
        // Make an AJAX request to search for clients by name
        $.ajax({
            url: 'database/search_client.kts.php',
            method: 'POST',
            data: { keyword: keyword },
            success: function(response) {
                // Show the search results in a dropdown
                $('#clientsDropdown').html(response);
                $('#clientsDropdown').show();
            },
            error: function(xhr, status, error) {
                console.error(xhr);
            }
        });
    }

    // Listen for changes to the vendor name input
     $(document).ready(function() {
        $('#client').on('keyup', function() {
            var keyword = $(this).val();
            if (keyword.length > 0) {
                // Search for clients
                searchClients(keyword);
            } else {
                // Hide the search results dropdown
                $('#clientsDropdown').hide();
            }
        });
    });
    // Listen for clicks on a search result
    $(document).on('click', '.client-result', function() {
        // Get the client ID, name, and phone number
        var clientId = $(this).data('id');
        var clientName = $(this).data('name');
        var clocation = $(this).data('location');
        var cphone = $(this).data('phone');

        // Update the client name and phone number inputs and hide the search results dropdown
        $('input[name="client"]').val(clientName);
        $('input[name="clid"]').val(clientId);
        $('input[name="cphone"]').val(cphone);
        document.getElementById('clientname').textContent = clientName;
        document.getElementById('location').textContent = clocation;
        document.getElementById('phone').textContent = cphone;

        document.getElementById('clientnames').textContent = clientName;
        document.getElementById('locations').textContent = clocation;
        document.getElementById('phones').textContent = cphone;

        document.getElementById('shopnames').textContent = clientName;
        document.getElementById('shoplocations').textContent = clocation;
        document.getElementById('shopphones').textContent = cphone;
        $('#clientsDropdown').hide();

        // Update the hidden client ID input
    });
</script>



<script>
    $(document).ready(function () {
        // Function to update the cart items on the page
        function updateCartOnPage() {
            // Perform AJAX request to get the updated cart content
            $.ajax({
                url: "get_cart_html.php", // Replace with the correct URL
                method: "POST",
                data: { action: "getCartHTML" },
                success: function (response) {
                    if (response.success) {
                        // Update the cart display on the page
                     $(".cart-display-container").html(response.cartHTML);

console.log(response);
                    } else {
                        console.error(response.message);
                    }
                },
                error: function () {
                    console.error('Error fetching cart HTML');
                }
            });
        }

        // Call the function to update the cart on page load
        updateCartOnPage();

        // Function to add an item to the cart
function addToCart(item) {
    $.ajax({
        url: "database/updatecart.kts.php",
        method: "POST",
        data: {
            action: "addToCart",
            item_name: item.item_name,
            product_id: item.product_id,
            price: item.price,
            quantity: item.quantity
        },
        success: function(response) {
            if (response.success || response.message === "Item added to cart") {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: response.message,
                }).then(function () {
                    updateCartOnPage();
                    location.reload();
                });
            } else {
                // Handle unsuccessful response
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: response.message || 'Something went wrong with the request!',
                });
            }
        },
        error: function () {
            // Handle error response
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Something went wrong with the request!',
            });
        }
    });
}


  updateCartOnPage();
        // Event handler for adding an item to the cart
        $('.search-results').on('click', '.add-to-cart', function () {
            const selectedOption = $(this).closest("tr").find(".price-dropdown").val();
            const customPriceInput = $(this).closest("tr").find(".customPrice");
            const item = {
                item_name: $(this).data("itemname"),
                product_id: $(this).data("productid"),
                quantity: $(this).closest("tr").find(".quantity-input").val(),
                price: selectedOption === 'custom' ? customPriceInput.val() : selectedOption
            };

            // Validate custom price
            if (selectedOption === 'custom' && (isNaN(item.price) || item.price <= 0)) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Price',
                    text: 'Please enter a valid custom price.',
                });
                return;
            }

            // Add the item to the cart
            addToCart(item);
        });

      // Event handler for searching
$("#searchInput").on("input", function () {
    const searchQuery = $(this).val();
    if (searchQuery.trim() === '') {
        // If no input, hide the search results container
        $(".search-results").hide();
         updateCartOnPage();
    } else {
        fetchInventory(searchQuery);
        updateCartOnPage();
    }
});

function fetchInventory(query) {
    $.ajax({
        url: "database/searchp.kts.php",
        method: "POST",
        data: { query: query },
        success: function (response) {
            // Update the search results container with the new results
            $(".search-results").html(response);
            // Show the search results container
            $(".search-results").show();
            // Update the cart display after fetching inventory
            updateCartOnPage();
        },
        error: function () {
            console.error('Error fetching inventory');
        }
    });
}

    });
</script>

<!-- create invoice -->
<script>
    $(document).ready(function() {
        $('#printButton').click(function() {
            // Check if the client ID input has data
            var clientId = $('#cid').val();
            var phoneNo = $('#cphone').val();
            if (!clientId) {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Kindly select a customer!',
                });
                return;
            }

            // Prepare the form data
            var formData = new FormData();
            formData.append('clientId', clientId);
            formData.append('phoneNo', phoneNo);

            // Make an AJAX POST request to send the form data
            $.ajax({
                type: 'POST',
                url: 'database/make_sale.kts.php', // Replace with your server endpoint
                data: formData,
                processData: false,  // Prevent jQuery from processing the data
                contentType: false,  // Set content type to false, jQuery will tell the server its a query string request
                success: function(response) {
                    // Handle success response (sale made successfully)
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Sale made successfully!',
                    }).then(function () {
                        // Print the "inv" div
                        window.location.href = 'print.php';
                    });
                },
                error: function() {
                    // Handle error response
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Something went wrong!',
                    });
                },
            });
        });

       
    });
</script>

    
    
  <!-- create cash receipt -->
<script>
    $(document).ready(function() {
        $('#submitButton').click(function() {
            // Check if the client ID input has data
            var amount = $('#amount').val();
            var paymethod = $('#paymethod').val();

            // Check if the payment method input has data
            if (!paymethod) {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Kindly select a payment method!',
                });
                return;
            }

            // Check if the amount input has data
            if (!amount) {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Kindly input the amount paid!',
                });
                return;
            }

            // Prepare the data object
            var postData = {
                amount: amount,
                paymethod: paymethod,
            };

            // Make an AJAX POST request to send the data
            $.ajax({
                type: 'POST',
                url: 'database/sales.kts.php', // Replace with your server endpoint
                data: JSON.stringify(postData),
                contentType: 'application/json',
                success: function (response) {
                    if (response.success) {
                        // Handle success response (sale made successfully)
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: 'Sale made successfully!',
                        }).then(function () {
                            // Redirect to print.php
                            window.location.href = 'print.php';
                        });
                    } else {
                        // Handle error response from the server
                        Swal.fire({
                            icon: 'error',
                            title: 'Oops...',
                            text: response.message || 'Something went wrong!',
                        });
                    }
                },
                error: function () {
                    // Handle general error response (could be a network issue)
                    Swal.fire({
                        icon: 'error',
                        title: 'Oops...',
                        text: 'Something went wrong!',
                    });
                },
            });
        });
    });
</script>

    
   <script>
    $(document).ready(function () {
        // Attach a click event listener to the "Remove" buttons
        $('.remove-item').on('click', function () {
            var index = $(this).data('index');

            // Send an AJAX request to remove_item.php with the index as a parameter
            $.ajax({
                type: 'GET',
                url: 'database/remz.kts.php',
                data: { index: index },
                success: function (response) {
                    // Handle the response from remove_item.php
                   if (response.message === 'Item removed from the cart') {
                        // Show a success SweetAlert
                        Swal.fire({
                            icon: 'success',
                            title: 'Item Removed Successfully',
                            text: response.message,
                        }).then(function () {
                            // Reload the page after the SweetAlert is closed
                            location.reload();
                        });
                    } else {
                        // Show an error SweetAlert
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.error,
                        }).then(function () {
                            // Reload the page after the SweetAlert is closed
                            location.reload();
                        });
                    }
                },
                error: function () {
                    // Show an error SweetAlert if the AJAX request fails
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Unable to remove item.',
                    }).then(function () {
                        // Reload the page after the SweetAlert is closed
                        location.reload();
                    });
                }
            });
        });
    });
</script>


<script>
    $(document).ready(function () {
        // Attach a click event listener to the "Clear All" button
        $('#clear-all').on('click', function () {
            // Send an AJAX request to clear_all.php
            $.ajax({
                type: 'GET',
                url: 'clear_all.php',
                success: function (response) {
                    // Handle the response from clear_all.php
                    if (response.success) {
                        // Show a success SweetAlert
                        Swal.fire({
                            icon: 'success',
                            title: 'Cart Cleared',
                            text: response.message,
                        });

                        // Add code here to update the cart contents in the modal or elsewhere on the page.
                    } else {
                        // Show an error SweetAlert
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.error,
                        });
                    }
                },
                error: function () {
                    // Show an error SweetAlert if the AJAX request fails
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Unable to clear the cart.',
                    });
                }
            });
        });
    });
</script>
 
    
     <script>
        $(document).ready(function() {
            // Initialize the DataTable
            var table = $('#saleTransactionTable').DataTable({
                ajax: {
                    url: 'engine/getsales.kts.php', // Replace with your server-side API endpoint
                    dataSrc: ''
                },
                columns: [
                    { data: 'customer_id' },
                    { data: 'stid' },
                    { data: 'total' },
                    { data: 'method' },
                    { data: 'date' },
                    {
                        data: null,
                        render: function(data) {
                            // Create view and delete buttons
                            return '<button class="btn btn-primary view-btn" data-stid="' + data.stid + '">View</button> ' +
                                   '<button class="btn btn-danger delete-btn" data-stid="' + data.stid + '">Delete</button>';
                        }
                    }
                ]
            });
          
           $('#saleTransactionTable').on('click', '.view-btn', function() {
            var stid = $(this).data('stid');

            // Make an AJAX call to retrieve sale details for the selected stid
          $.ajax({
    url: 'engine/get_salesdetail.kts.php', // Replace with your API endpoint for sale details
    data: { stid: stid },
    type: 'GET',
    success: function(response) {
        // Update the modal with sale details data
        var modalContent = '<table class="table table-bordered"><thead><tr><th>sale No</th><th>Receipt No</th><th>item_name</th><th>quantity</th><th>subtotal</th><th>Actions</th></tr></thead><tbody>';
        response.forEach(function(item) {
            modalContent += '<tr><td>' + item.stno + '</td><td>' + item.stids + '</td><td>' + item.item_name + '</td><td>' + item.quantity_sold + '</td><td>' + item.subtotal + '</td><td>';
            
            // Add icons for edit, delete, and update
            modalContent += '<i class="fa fa-edit edit-icon" data-id="' + item.stids + '"></i> ';
            modalContent += '<i class="fa fa-trash delete-icon red-icon" data-id="' + item.stids + '"></i> ';
            
            modalContent += '</td></tr>';
        });
        modalContent += '</tbody></table>';
        $('#saleTransactionDetails').html(modalContent);
        $('#saleTransactionModal').modal('show');
        
        // Add click event handlers for icons (you can use jQuery for this)
        $('.edit-icon').click(function() {
            // Handle edit icon click here
            var itemId = $(this).data('id');
            // Perform edit action
        });

        $('.delete-icon').click(function() {
            // Handle delete icon click here
            var itemId = $(this).data('id');
            // Perform delete action
        });

        $('.update-icon').click(function() {
            // Handle update icon click here
            var itemId = $(this).data('id');
            // Perform update action
        });
    },
    error: function() {
        // Handle errors if the request fails
        alert('Failed to load sale details.');
    }
});

        });
        });
  </script>
  

<script>
// Function to handle select change event
function handleSelectChange() {
    // Get the selected value
    var selectedValue = $(".priceInput").val();

    // Find the associated custom price input field
    var customPriceInput = $(".customPrice");

    // Check if it's "custom"
    if (selectedValue === "custom") {
        // Show the custom input field
        customPriceInput.show();
    } else {
        // Hide the custom input field
        customPriceInput.hide();
    }
}

// Attach change event handler to the select element with class "priceInput"
$(".priceInput").change(function() {
    handleSelectChange();
});

// Initial call to handleSelectChange for any pre-selected "Custom" options
handleSelectChange();
</script>

  
</body>





 
                                   

</html>