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

unset($_SESSION['recipe']);
        unset($_SESSION['food_items']);

?>
<!DOCTYPE html>
<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>Park Place Hotel</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" type="text/css" href="https://cdn.datatables.net/buttons/1.7.1/css/buttons.dataTables.min.css">

   <link href="./quixlab/js/DataTables/datatables.min.css" rel="stylesheet"/>
   <link href="./quixlab/js/datatables.min.css" rel="stylesheet"/>
   <link href="./quixlab/js/DataTables/Buttons-2.3.6/css/buttons.bootstrap.css" rel="stylesheet"/>
   <link href="./quixlab/js/DataTables/Buttons-2.3.6/css/buttons.bootstrap.min.css" rel="stylesheet"/>
   <link href="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.13.4/af-2.5.3/b-2.3.6/b-colvis-2.3.6/b-html5-2.3.6/b-print-2.3.6/date-1.4.0/r-2.4.1/sp-2.1.2/datatables.min.css" rel="stylesheet"/>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.25/datatables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.7.1/css/buttons.dataTables.min.css"/>


   <link href="./quixlab/js/DataTables/datatables.css" rel="stylesheet"/>
   <link href="./quixlab/js/datatables.css" rel="stylesheet"/>
    <link href="./quixlab/css/buttons.bootstrap.min.css" rel="stylesheet">
    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" crossorigin="anonymous" />
   <link href="./plugins/bootstrap-material-datetimepicker/css/bootstrap-material-datetimepicker.css" rel="stylesheet">
 
  <link href="./plugins/clockpicker/dist/jquery-clockpicker.min.css" rel="stylesheet">
 
   <link href="./plugins/bootstrap-datepicker/bootstrap-datepicker.min.css" rel="stylesheet">

 <link href="./plugins/timepicker/bootstrap-timepicker.min.css" rel="stylesheet">
    <link href="./plugins/bootstrap-daterangepicker/daterangepicker.css" rel="stylesheet">

    <script src="./plugins/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>

 <link href="./quixlab/plugins/sweetalert2/dist/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

</head>

<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
    ********************-->

            
    
    <!--**********************************
        Main wrapper start
    ***********************************-->
    <div id="main-wrapper">

        <!--**********************************
            Nav header start
        ***********************************-->
        <div class="nav-header">
            <div class="brand-logo" style="background-image: url('./quixlab/images/room.png');">
                
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            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="drop-down animated flipInX 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 d-none d-md-flex">
    <a href="javascript:void(0)" class="log-user" data-toggle="modal" data-target="#cartModal">
        <span>Cart</span> <i class="fa fa-shopping-cart f-s-14" aria-hidden="true"></i>
        <?php
        // Show the number of item rows in the cart
        $itemCount = !empty($_SESSION['cart']) ? count($_SESSION['cart']) : 0;
        echo '<span class="badge badge-danger">' . $itemCount . '</span>';
        ?>
    </a>
</li>
                                               
                    </ul>
                </div>
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header 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", 
    "payments.php", 
    "purchases.php", 
    "reg-customer.php", 
    "inventory.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>
        <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

        <!--**********************************
            Sidebar start
        ***********************************-->
    
        <!--**********************************
            Sidebar end
        ***********************************-->

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

            <div class="container-fluid mt-3">
                 <div class="row">
                    <div class="col-lg-3 col-sm-3" id="Ingredient">
                        <div class="card gradient-9" data-toggle="modal" data-target="#ingredientModal">
                            <div class="card-body">
                                <h3 class="card-title text-white"></h3>
                                <div class="d-inline-block">
                                    <h2 class="text-white">Ingredient</h2>
                                    <p class="text-white mb-0"></p>
                                </div>
                                <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
                            </div>
                        </div>
                    </div>

                   <div class="col-lg-3 col-sm-3" id="foodManagement">
                        <div class="card gradient-8" data-toggle="modal" data-target="#foodModal">
                            <div class="card-body">
                                <h3 class="card-title text-white"></h3>
                                <div class="d-inline-block">
                                    <h2 class="text-white">Food Management</h2>
                                    <p class="text-white mb-0"></p>
                                </div>
                                <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
                            </div>
                        </div>
                    </div>
                     
                    <div class="col-lg-3 col-sm-3" id="beveragesManagement">
                        <div class="card gradient-4" data-toggle="modal" data-target="#beverageModal">
                            <div class="card-body">
                                <h3 class="card-title text-white"></h3>
                                <div class="d-inline-block">
                                    <h2 class="text-white">Beverages Management</h2>
                                    <p class="text-white mb-0"></p>
                                </div>
                                <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
                            </div>
                        </div>
                    </div>
                     
                     <!-- Tot Management Card -->
<div class="col-lg-3 col-sm-3" id="tot">
    <div class="card gradient-1" data-toggle="modal" data-target="#totsModal">
        <div class="card-body">
            <h3 class="card-title text-white"></h3>
            <div class="d-inline-block">
                <h2 class="text-white">Tot Management</h2>
                <p class="text-white mb-0"></p>
            </div>
            <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
        </div>
    </div>
</div>
                    
                      
                   
              </div>
              </div>
              <div class="container-fluid mt-3">

              <div class="row">
                   
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                            <div class="card-body">
                                <h4 class="card-title"></h4>
                                <div class="table-responsive">
                                        <h1>Food Menu</h1>

                                    <table id="foodTable" class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>Food ID</th>
                                                <th>Name</th>
                                                <th>Price</th>
                                                <th>Cost Price</th>
                                                <th>Food Group</th>
                                                <th>Category</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div> </div> 
            <div class="container-fluid mt-3">

              <div class="row">
                   
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                            <div class="card-body">
                                <h4 class="card-title"></h4>
                                <div class="table-responsive">
                                        <h1>Beverages Stock List</h1>

                                    <table id="beveragesTable" class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Beverage Name</th>
                                                <th>Buying  Price</th>
                                                <th>Selling Price</th>
                                                <th>Tot/Glass  Price</th>
                                                <th>Category</th>
                                                <th>Tots/Glass Available</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div> </div>
               <div class="container-fluid mt-3">
          
              <div class="row">
        <h2>Tots Management</h2>
        <table id="totsTable" class="table table-striped table-bordered display table-sm ">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Quantity</th>
                    <th>Created At</th>
                    <th>Price</th>
                    <th>Actions</th>
                </tr>
            </thead>
        </table>

                   </div>
            </div>
                  
                  <div class="container-fluid mt-3">
          
              <div class="row">
                   
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                            <div class="card-body">
                                <h4 class="card-title"></h4>
                                <div class="table-responsive">
                                      <h1>Ingredients List</h1>
                                    <table class="table table-striped table-bordered display table-sm purchase-table" id="ingredientsTable">
                                        <thead>
                                           <tr>
                                                <th>ID</th>
                                                <th>Name</th>
                                                <th>Quantity</th>
                                                <th>Unit</th>
                                                <th>Cost Per Unit</th>
                                                <th>Total Cost</th>
                                                <th>Action</th>
                                            </tr>   

                                        </thead>
                                       <tbody></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
               </div>
                </div>
                
                
                <div class="container-fluid mt-3">
                  <div class="row">
                    <div class="col-lg-12 col-sm-12">
                      <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Disposal Details</h4>
                                <div class="table-responsive">
                                    <table class="table table-striped table-bordered display table-sm purchase-table" id="disposeTable">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Disposed By</th>
                                                <th>Date</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                       <tbody></tbody>
                                        <tfoot>
                                           <tr>
                                                <th>#</th>
                                                <th>Disposed By</th>
                                                <th>Date</th>
                                                <th>Action</th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
               </div>
                </div>
                
                 
                  
                   
           <div class="container-fluid mt-3">
              <div class="row">
                  <div class="col-lg-12 col-sm-12">
                      <div class="card">
                          <div class="card-body">
                              <h4 class="card-title">Consumed Items Report</h4>
                              <form id="issued-summary">
                                  <div class="row form-material">
                                      <div class="col-md-4">
                                          <label for="start-date">Start Date/Time</label>
                                          <input type="datetime-local" id="start-date" name="start-date" class="form-control">
                                      </div>
                                      <div class="col-md-4">
                                          <label for="end-date">End Date/Time</label>
                                          <input type="datetime-local" id="end-date" name="end-date" class="form-control">
                                      </div>
                                      <div class="col-md-4">
                                          <button type="button" id="check-minutes" class="btn waves-effect waves-light btn-success">Check</button>
                                      </div>
                                  </div>
                              </form>
                          </div>
                      </div>
                  </div>
              </div>
            </div>
                
                
                
               
            <!-- #/ container -->
      
         <div class="modal fade" id="ShopModal">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">

                        <div class="modal-body">
                           <div class="input-group icons">
                                      <div class="input-group-prepend">
                                          <span class="input-group-text bg-transparent border-0 pr-1 pr-sm-2" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                                      </div>
                                      <input type="search" class="form-control rounded" placeholder="Search Products" aria-label="Search Dashboard">
                                      <div class="drop-down animated flipInX d-md-none">
                                          <form action="#">
                                              <input type="text" class="form-control" placeholder="Search">
                                          </form>
                                      </div>
                                </div>
                        </div>

                    </div>
                </div>
            </div>
               
                <!-- End  of Send to Shop Items Modal -->
               <!-- Modal -->
<div class="modal fade" id="update-product-modal" tabindex="-1" role="dialog" aria-labelledby="updateProductModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="updateProductModalLabel">Update Ingredient</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="update-product-form">
                    <input type="hidden" id="product-id-input" name="product-id-input">
                    <div class="form-row">
                      <div class="form-group col-md-4">
                        <label for="product-name-input">Product Name</label>
                        <input type="text" class="form-control" id="product-name-input" name="product-name-input">
                      </div>
                    
                    <div class="form-group col-md-4">
                        <label for="buying-price-input">Buying Price</label>
                        <input type="number" class="form-control" id="buying-price-input" name="buying-price-input">
                    </div>
                     <div class="form-group col-md-4">
                        <label for="selling-price-input">Selling Price</label>
                        <input type="number" class="form-control" id="selling-price-input" name="selling-price-input">
                    </div>
                  </div>
                   <div class="form-row">
                      <div class="form-group col-md-4">
                        <label for="product-name-input">Available</label>
                        <input type="text" class="form-control" id="shop-quantity-input" name="name-input" readonly>
                      </div>
  
                  </div>
                 
                    <button type="submit" class="btn btn-primary">Update Ingredient</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="invoiceDetailsModal" tabindex="-1" role="dialog" aria-labelledby="invoiceDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="invoiceDetailsModalLabel">Invoice Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body" id="invoiceDetailsBody">
        <!-- Invoice details content will be loaded here -->
      </div>
    </div>
  </div>
</div>


<div class="modal fade" id="disposeDetailsModal" tabindex="-1" role="dialog" aria-labelledby="invoiceDetailsModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="disposeDetailsModalLabel">Disposed Details</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body" id="disposeDetailsBody">
        <!-- Invoice details content will be loaded here -->
      </div>
    </div>
  </div>
</div>
 
<!-- Ingredient Modal -->
<div class="modal fade" id="ingredientModal" tabindex="-1" role="dialog" aria-labelledby="ingredientModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="ingredientModalLabel">Add Ingredient</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="ingredientForm">
          <div class="form-group">
            <label for="ingredientName">Name</label>
            <input type="text" class="form-control" id="ingredientName" placeholder="Enter ingredient name">
          </div>
          <div class="form-group">
            <label for="ingredientQuantity">Quantity</label>
            <input type="number" class="form-control" id="ingredientQuantity" placeholder="Enter quantity">
          </div>
          <div class="form-group">
            <label for="ingredientUnit">Unit</label>
            <select class="form-control" id="ingredientUnit">
                <!-- Options will be dynamically loaded -->
            </select>
        </div>

          <div class="form-group">
            <label for="ingredientCost">Cost per Unit</label>
            <input type="number" class="form-control" id="ingredientCost" placeholder="Enter cost per unit">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="saveIngredient">Save</button>
      </div>
    </div>
  </div>
</div>
            

<!-- Food Modal -->
<div class="modal fade" id="foodModal" tabindex="-1" role="dialog" aria-labelledby="foodModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="foodModalLabel">Add Food</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
    <div class="row">
        <div class="col-md-6"> 
            <form id="foodEntity">
            <div class="form-group">
                <label for="foodName">Name</label>
                <input type="text" class="form-control" id="foodName" placeholder="Enter food name" required>
            </div>
            <div class="form-group">
                <label for="foodName">Selling Price</label>
                <input type="number" class="form-control" id="foodPrice" placeholder="Enter selling price" required>
            </div>
                <div class="form-group">
            <label for="categoryz">Category</label>
            <select class="form-control" id="categoryz" name="category">
                <option value="">Choose...</option>
                <option value="Pork">Pork</option>
                <!-- Options will be populated here by fetchCategories() -->
            </select>
        </div>
            <div class="form-group">
    <label for="foodName">Image</label>
    <div class="row">
        <div class="col-md-6 col-sm-6">
            <input type="file" class="form-control-file" id="foodImageInput" accept="image/*" required>
        </div>
        <div class="col-md-6 col-sm-6">
            <img src="" alt="Preview Image" id="imagePreview" style="max-width: 100px; max-height: 100px; margin-top: 10px; display: none;">
        </div>
    </div>
</div>

            <div class="form-group">
    <label for="foodName">Description</label>
    <textarea class="form-control" id="fooddescription" rows="2" placeholder="Enter food description" required></textarea>
</div>

              <div class="form-group">
                <label for="foodType">Type</label>
                <select class="form-control" id="foodType">
                    <option value="Select Type" selected>Select Type</option>
                    <option value="Single">Single</option>
                    <option value="Group">Group</option>
                </select>
            </div>
                </form>
        </div>
            
        <div class="col-md-6">
          <div id="recipe_items">
          </div>
             <div id="food_items">
          </div>
        </div>
         
    </div>
    <!-- Add any other form elements below as needed -->
</div>

                <!-- Single Food Content -->
                <div class="modal-body" id="single" style="display:none;">
                    <h5>Add Ingredients</h5>
                    <div class="input-group mb-3">
                        <input type="text" class="form-control" id="ingredientSearch" placeholder="Search ingredients">
                        
                    </div>
                    <div id="ingredientResults"></div>
                        <!-- Ingredient items will be dynamically added here -->
                  
                </div>

                <!-- Group Food Content -->
               <div class="modal-body" id="group" style="display:none;">
    <h5>Add Foods</h5>
    <div class="input-group mb-3">
    <input type="text" class="form-control" id="foodSearch" placeholder="Search foods">
    
</div>
    <div id="foodResults"></div>
</div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="saveFood">Save</button>
            </div>
        </div>
    </div>
</div>
            
   

<!-- Modal -->
<div class="modal fade" id="beverageModal" tabindex="-1" aria-labelledby="beverageModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="beverageModalLabel">Beverages</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="beverageForm" enctype="multipart/form-data">
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="beverageName" class="form-label">Beverage Name</label>
                <input type="text" class="form-control" id="beverageName" name="beverage_name" required>
              </div>
              <div class="mb-3">
                <label for="buyingPrice" class="form-label">Buying Price</label>
                <input type="number" class="form-control" id="buyingPrice" name="buying_price" required>
              </div>
              <div class="mb-3">
                <label for="sellingPrice" class="form-label">Selling Price</label>
                <input type="number" class="form-control" id="sellingPrice" name="selling_price" required>
              </div>
              <div class="mb-3">
                <label for="beverageImage" class="form-label">Beverage Image</label>
                <input type="file" class="form-control" id="beverageImage" name="beverage_image" accept="image/*" style="display: none;" onchange="previewImage(event)">
                <button type="button" class="btn btn-primary" onclick="document.getElementById('beverageImage').click()">Upload Image</button>
                <img id="beverageImagePreview" src="#" alt="Image Preview" style="display: none; margin-top: 10px;" width="80px" height="80">
              </div>
                <div id="tot-session"></div>
            </div>
            <div class="col-md-6">
              
              <div class="mb-3">
                <label for="totPerGlass" class="form-label">total Tot/Glass Per Bottle</label>
                <input type="number" class="form-control" id="totPerGlass" name="tot_per_glass" required>
              </div>
              
            <div class="mb-3">
                <label for="beverageCategory" class="form-label">Beverage Category</label>
                <select class="form-control" id="beverageCategory" name="beverage_category" required>
                    <option value="">Select a category</option>
                    <option value="beer">Beer</option>
                    <option value="wine">Wine</option>
                    <option value="whiskey">Whiskey</option>
                    <option value="vodka">Vodka</option>
                    <option value="rum">Rum</option>
                    <option value="gin">Gin</option>
                    <option value="tequila">Tequila</option>
                    <option value="brandy">Brandy</option>
                    <option value="cocktails">Cocktails</option>
                    <option value="cognac">Cognac</option>
                    <option value="non-alcoholic">Non-Alcoholic</option>
                    <!-- Add more options as needed -->
                </select>
            </div>
              <div class="mb-3">
                <label for="beverageType" class="form-label">Type</label>
                <select class="form-select" id="beverageType" name="type" required>
                  <option value="normal">Normal</option>
                  <option value="cocktail">Cocktail</option>
                </select>
              </div>
                <div class="mb-3">
                <label for="beverageType" class="form-label">Tot Availability</label>
                <select class="form-select" id="t_availability" name="t_availability" required>
                  
                  <option value="No">No</option>
                    <option value="Yes">Yes</option>
                </select>
              </div>
            </div>
          </div>
            <div class="modal-body" id="totsearchpane" style="display:none;">
    <h5>Add tots</h5>
    <div class="input-group mb-3">
        <input type="text" class="form-control" id="totsearch" placeholder="Search tots">
    </div>
    <div id="totsresults"></div>
    <!-- Ingredient items will be dynamically added here -->
</div>
            <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" id="saveBeverages" class="btn btn-success">Save</button>
      </div>
        </form>
            <div id="result" class="mt-3"></div>
      </div>
      
    </div>
  </div>
   
</div>
     
            
<!-- Tot Management Modal -->
<div class="modal fade" id="totsModal" tabindex="-1" role="dialog" aria-labelledby="totsModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="totsModalLabel">Tot Management</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="totsForm">
                    <div class="form-group">
                        <label for="totName">Name</label>
                        <input type="text" class="form-control" id="totName" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="totQuantity">Quantity</label>
                        <input type="number" class="form-control" id="totQuantity" name="quantity" required>
                    </div>
                    <div class="form-group">
                        <label for="totQuantity">Price</label>
                        <input type="number" class="form-control" id="totPricey" name="totpricey" required>
                    </div>
                  <button type="submit" class="btn btn-primary">Save</button>
                </form>
            </div>
        </div>
    </div>
</div>
 <!-- End of cart modal -->
  
        <!--**********************************
            Content body end
        ***********************************-->
        
        
        <!--**********************************
            Footer start
        ***********************************-->
         <div class="container-fluid mt-3">

              <div class="row">
        <div class="footer">
            <div class="copyright">
                <p>Copyright &copy; Designed & Developed by <a href="https://kakashitech.com">Kakashi Tech</a></p>
            </div>
        </div>
           </div>
      </div>
        <!--**********************************
            Footer end
        ***********************************-->
   
    <!--**********************************
        Main wrapper end
    ***********************************-->
  </div>
  </div>
    <!--**********************************
        Scripts
***********************************-->
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
 <script src="./quixlab/js/jquery/jquery.min.js"></script>
<!-- Bootstrap and other common scripts -->
<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>

<!-- Charting libraries -->
<script src="./quixlab/plugins/chart.js/Chart.bundle.min.js"></script>
<script src="./quixlab/plugins/circle-progress/circle-progress.min.js"></script>
<script src="./quixlab/plugins/d3v3/index.js"></script>
<script src="./quixlab/plugins/topojson/topojson.min.js"></script>
<script src="./quixlab/plugins/datamaps/datamaps.world.min.js"></script>
<script src="./quixlab/plugins/raphael/raphael.min.js"></script>
<script src="./quixlab/plugins/morris/morris.min.js"></script>
<script src="./quixlab/plugins/moment/moment.min.js"></script>
<script src="./quixlab/plugins/pg-calendar/js/pignose.calendar.min.js"></script>
<script src="./quixlab/plugins/chartist/js/chartist.min.js"></script>
<script src="./quixlab/plugins/chartist-plugin-tooltips/js/chartist-plugin-tooltip.min.js"></script>

<!-- DataTables and related plugins -->
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.7.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.7.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.7.0/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/searchpanes/2.1.2/js/dataTables.searchPanes.min.js"></script>

<!-- PDFMake library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.66/vfs_fonts.js"></script>

<!-- Other scripts -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
      <script src="./quixlab/js/select2.min.js"></script>

<!-- Your custom scripts -->
<script src="./quixlab/js/dashboard/dashboard-1.js"></script>
<script src="./quixlab/js/plugins-init/chartjs-init.js"></script>
<script src="./quixlab/js/datatables.js"></script>
<script src="./quixlab/js/DataTables/init.js"></script>
    <script src="./plugins/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>


    <script src="./plugins/bootstrap-material-datetimepicker/js/bootstrap-material-datetimepicker.js"></script>
    <script src="./plugins/timepicker/bootstrap-timepicker.min.js"></script>

 <script src="./plugins/bootstrap-daterangepicker/daterangepicker.js"></script>

    <script src="./js/plugins-init/form-pickers-init.js"></script>
         <script src="./quixlab/plugins/sweetalert2/dist/sweetalert2.min.js"></script>
        
            <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>


  <script>
 //Add Stock Modal 
 $('#addstock').click(function(){
   $('#basicModal').modal();
 });
//Send stock to Shop  
 $('#sendshop').click(function(){
   $('#ShopModal').modal();
 });
// Items To Send
  $('#storecart').click(function(){
    $('#shopite').modal();
  });    
// Add Vendor
  $('#vendor').click(function(){
    $('#vendite').modal();
  });
  $('#addbranch').click(function(){
    $('#newbranch').modal();
  });
  $('#addcategory').click(function(){
    $('#newcategory').modal();
  });  
  $('#addshelf').click(function(){
    $('#newshelf').modal();
  });
      $('#beveragesManagement').click(function(){
   $('#beverageModal').modal();
 });
 </script>
 
 
 	<script>
		$(document).ready(function() {
    // Add event listener to form submit button
    $('#product-form').on('submit', function(event) {
        event.preventDefault(); // Prevent default form submission behavior

        // Serialize form data
        var formData = $(this).serialize();

        // Send AJAX request to server
        $.ajax({
            url: './database/products.kts.php', // PHP script to handle the request
            type: 'POST',
            data: formData,
            dataType: 'json', // Specify JSON dataType
            success: function(response) {
                // Display success or error message with SweetAlert
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                    }).then(function() {
                        // Clear the form input fields
                        $('#product-form')[0].reset();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.error,
                    });
                }
            },
            error: function(xhr, status, error) {
                // Handle errors
                console.log(xhr.responseText);
            }
        });
    });
});

	</script>
 <script>
   $(document).ready(function() {
  // Load table data via AJAX
  var table = $('.items-table').DataTable({
    ajax: {
      url: './database/get_products.kts.php',
      type: 'GET',
      dataSrc: ''
    },
    columns: [
      { data: 'product_id' },
      { data: 'product_name' },
      { data: 'company' },
      { data: 'buying_price' },
      { data: 'selling_price' },
      { data: 'shop_quantity' },
      {
        // Update button column
        render: function(data, type, row) {
          return '<button class="btn btn-primary update-product" data-product-id="' + row.product_id + '">Update</button>';
        }
      },
      {
        // Delete button column
        render: function(data, type, row) {
          return '<button class="btn btn-danger delete-product" data-product-id="' + row.product_id + '">Delete</button>';
        }
      }
    ],
    dom: 'Bfrtip',
     buttons: [
    {
      extend: 'pdfHtml5',
      text: 'Export to PDF',
      exportOptions: {
        columns: ':not(.no-export)'
      }
    }
  ]

  });

  // Update button click handler
  $('.items-table tbody').on('click', '.update-product', function() {
    var productId = $(this).data('product-id');
   
    // Make an AJAX call to retrieve the current product details
    $.ajax({
      url: './database/get_products.kts.php',
      type: 'POST',
      data: { 'product_id': productId },
      success: function(response) {
        // Parse the response JSON and populate the modal fields
          var products = JSON.parse(response);
        $('#product-id-input').val(products.product_id);
        $('#product-name-input').val(products.product_name);
        $('#company-input').val(products.company);
        $('#buying-price-input').val(products.buying_price);
        $('#selling-price-input').val(products.selling_price);
       
        $('#shop-quantity-input').val(products.shop_quantity);
        // Display the modal
        $('#update-product-modal').modal('show');
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.error(errorThrown);
      }
    });
  });

  // Delete button click handler
  $('.items-table tbody').on('click', '.delete-product', function() {
    var productId = $(this).data('product-id');
    // Make an AJAX call to delete the product from the server
    $.ajax({
      url: './database/delete_product.kts.php',
      type: 'POST',
      data: { 'product_id': productId },
      success: function(response) {
        // Refresh the table data
        table.ajax.reload();
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.error(errorThrown);
      }
    });
  });
});

</script>

 <script>
  $(document).ready(function() {
    // Initialize the DataTable
    var purchaseTable = $('#purchaseTable').DataTable({
      ajax: {
        url: './database/get_purchases.kts.php',
        type: 'GET',
        dataSrc: ''
      },
      columns: [
        { data: 'invo_id' },
        { data: 'invoice_number' },
        { data: 'supplier_name' },
        { data: 'total' },
        { data: 'date' },
        {
          render: function(data, type, row) {
            return '<i class="fa fa-eye text-danger view-invoice" data-invo-id="' + row.invo_id + '" style="cursor: pointer;"></i>';
          }
        }
      ]
    });

    // Event listener for clicking the "fa-eye" icon
    $('#purchaseTable').on('click', '.view-invoice', function() {
      var invoId = $(this).data('invo-id');

      // Fetch and display invoice details using AJAX
      $.ajax({
        url: './database/get_invoicedetails.kts.php',
        type: 'GET',
        data: { invoId: invoId },
        success: function(response) {
          // Display the fetched data in the modal
          $('#invoiceDetailsBody').html(response);

          // Show the modal
          $('#invoiceDetailsModal').modal('show');
        },
        error: function(xhr, status, error) {
          console.error('AJAX Error:', status, error);
        }
      });
    });
  });
</script>
<!-- Dsposal management -->
 <script>
  $(document).ready(function() {
    // Initialize the DataTable
    var purchaseTable = $('#disposeTable').DataTable({
      ajax: {
        url: './database/fetch_disposed.kts.php',
        type: 'GET',
        dataSrc: ''
      },
      columns: [
        { data: 'dispose_id' },
        { data: 'disposed_by' },
        { data: 'date' },
        {
          render: function(data, type, row) {
            return '<i class="fa fa-eye text-danger view-disposed" data-dispose-id="' + row.dispose_id + '" style="cursor: pointer;"></i>';
          }
        }
      ]
    });

    // Event listener for clicking the "fa-eye" icon
    $('#disposeTable').on('click', '.view-disposed', function() {
      var disposeId = $(this).data('dispose-id');

      // Fetch and display invoice details using AJAX
      $.ajax({
        url: './database/dispose_details.kts.php',
        type: 'GET',
        data: { disposeId: disposeId },
        success: function(response) {
          // Display the fetched data in the modal
          $('#disposeDetailsBody').html(response);

          // Show the modal
          $('#disposeDetailsModal').modal('show');
        },
        error: function(xhr, status, error) {
          console.error('AJAX Error:', status, error);
        }
      });
    });
  });
</script>


<script>
	$(document).ready(function() {
		// Add event listener to form submit button
		$('#update-product-form').on('submit', function(event) {
			event.preventDefault(); // Prevent default form submission behavior

			// Serialize form data
			var formData = $(this).serialize();

			// Send AJAX request to server
			$.ajax({
				url: './database/updateproduct.kts.php', // PHP script to handle the request
				type: 'POST',
				data: formData,
				success: function(response) {
					// Display the response from the PHP script using SweetAlert
					Swal.fire({
						icon: 'success',
						title: 'Product Update',
						text: response,
					});

					// Clear the form input fields
					$('#update-product-form')[0].reset();
    					location.reload();
			
				},
				error: function(xhr, status, error) {
					// Handle errors
					console.log(xhr.responseText);
				}
			});
		});
	});
</script>

	
	<!--VendorSearch-->
	 <script>
   function searchClients(keyword) {
    // Make an AJAX request to search for clients by name
    $.ajax({
        url: 'database/search_vendors.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
$('input[name="company"]').on('input', 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');
    
    
    // Update the client name and phone number inputs and hide the search results dropdown
    $('input[name="company"]').val(clientName);
    $('input[name="id"]').val(clientId);
    $('#clientsDropdown').hide();
    
    // Update the hidden client ID input
   
});

    </script>
    
    
 <script>function searchVendor(keyword) {
  // Make an AJAX request to search for vendors by name
  $.ajax({
    url: 'database/search_vendors.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).on('input', 'input[name="company"]', function() {
  var keyword = $(this).val();
  if (keyword.length > 0) {
    // Search for vendors
    searchVendor(keyword);
  } else {
    // Hide the search results dropdown
    $('.clientsDropdown').hide();
  }
});

// Listen for clicks on a search result
$(document).on('click', '.client-result', function() {
  // Get the vendor ID and name
  var vendorId = $(this).data('id');
  var vendorName = $(this).data('name');
    
  // Update the vendor name and ID inputs and hide the search results dropdown
  $('input[name="company"]').val(vendorName);
  $('input[name="id"]').val(vendorId);
  $('.clientsDropdown').hide();
});

// Listen for form submit
$('form').submit(function(event) {
  event.preventDefault();
  // Submit the form using AJAX or standard form submission
  // depending on your specific requirements
});
</script>

<script>
  // Add event listener to the input field
  document.getElementById('shop_quantity').addEventListener('input', function(e) {
    // Get the user's input
    const input = e.target.value.trim();
    
    // Check if the input is a whole number
    if (Number.isInteger(parseFloat(input))) {
      // Input is a whole number, so set the step attribute to 1
      e.target.step = 1;
    } else {
      // Input is not a whole number, so set the step attribute to any
      e.target.step = "any";
    }
  });
</script>
<script>
  // Add event listener to the input field
  document.getElementById('new-quantity-input').addEventListener('input', function(e) {
    // Get the user's input
    const input = e.target.value.trim();
    
    // Check if the input is a whole number
    if (Number.isInteger(parseFloat(input))) {
      // Input is a whole number, so set the step attribute to 1
      e.target.step = 1;
    } else {
      // Input is not a whole number, so set the step attribute to any
      e.target.step = "any";
    }
  });
</script>


<script>
// Function to fetch and populate category options
function fetchCategories() {
    // AJAX request
    $.ajax({
        url: 'database/fetch_category.kts.php', // Replace with your server-side script URL
        method: 'GET',
        dataType: 'json',
        success: function(data) {
            // Clear existing options
            $('#categoryz').empty();
            // Add default option
            $('#categoryz').append($('<option>', {
                value: '',
                text: 'Choose...'
            }));
            // Populate options with fetched data
            $.each(data, function(index, category) {
                $('#categoryz').append($('<option>', {
                    value: category.cate_name,
                    text: category.cate_name
                }));
            });
        },
        error: function(xhr, status, error) {
            console.error('Error fetching categories: ' + error);
        }
    });
}

// Call the fetchCategories function on document ready
$(document).ready(function() {
    fetchCategories();
});
</script>


<script>
    $(document).ready(function () {
        $('#createCategory').submit(function (e) {
            e.preventDefault();

         
				// Serialize form data
				var formData = $(this).serialize();
          
            // AJAX request
            $.ajax({
                type: 'POST',
                url: 'database/create_category.kts.php', // Replace with your server-side script URL
                data: formData,
               success: function (response) {
    // Check the success status
    if (response.success) {
        // Display success message with SweetAlert
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: 'Category created successfully.',
        }).then(function () {
            // Reload the page
            location.reload();
        });
    } else {
        // Display error message with SweetAlert
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Failed to create category. Please try again.',
        });
    }
},

                error: function () {
                    // Display error message with SweetAlert
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'An unexpected error occurred. Please try again.',
                    });
                }
            });
        });
    });
</script>

<script>
    $(document).ready(function () {
        $('#createShelf').submit(function (e) {
            e.preventDefault();

         
				// Serialize form data
				var formData = $(this).serialize();
          
            // AJAX request
            $.ajax({
                type: 'POST',
                url: 'database/create_shelf.kts.php', // Replace with your server-side script URL
                data: formData,
               success: function (response) {
    // Check the success status
    if (response.success) {
        // Display success message with SweetAlert
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: 'Shelf successfully.',
        }).then(function () {
            // Reload the page
            location.reload();
        });
    } else {
        // Display error message with SweetAlert
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Failed to create Shelf. Please try again.',
        });
    }
},

                error: function () {
                    // Display error message with SweetAlert
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: 'An unexpected error occurred. Please try again.',
                    });
                }
            });
        });
    });
</script>


<script>
    // Additional check to see if jQuery and Select2 are available
    if (typeof jQuery === 'undefined') {
        console.error('jQuery is not available.');
    } else if (typeof jQuery.fn.select2 === 'undefined') {
        console.error('Select2 is not available.');
    } else {
        // jQuery and Select2 are available
        $(document).ready(function() {
            // Fetch and populate shelf data
            fetchShelfData();

            // Function to fetch and populate shelf options
            function fetchShelfData() {
                // AJAX request
                $.ajax({
                    url: 'database/fetch_shelf.kts.php', // Replace with your server-side script URL
                    method: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        // Initialize Select2 after the data is fetched
                        $('#shelf').select2({
                            placeholder: 'Search for a shelf...',
                            data: data
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error('Error fetching shelf data: ' + error);
                    }
                });
            }
        });
    }
</script>

<script>
$(document).ready(function () {
    $('#searchInput').on('input', function () {
        var searchTerm = $(this).val();

        if (searchTerm.length >= 1) {
            // AJAX request to the server-side script (search.php)
            $.ajax({
                url: './database/searchitem.kts.php',
                method: 'POST',
                data: { searchTerm: searchTerm },
                success: function (response) {
                    $('#searchResults').html(response).show(); // Show the results
                }
            });
        } else {
            $('#searchResults').empty().hide(); // Hide and empty the results
        }
    });
});
</script>


<script>
    $(document).ready(function () {
        $('#receive-products-btn').click(function (e) {
            e.preventDefault();

            // Serialize form data
            var formData = $('#receive-invoice').serialize();

            // AJAX request
            $.ajax({
                type: 'POST',
                url: 'database/receive_invoice.kts.php', // Replace with your server-side script URL
                data: formData,
                dataType: 'json', // Expect JSON response
                success: function (response) {
                    // Use SweetAlert for success message
                    Swal.fire({
                        icon: response.success ? 'success' : 'error',
                        title: response.success ? 'Success' : 'Error',
                        text: response.message,
                    }).then((result) => {
                        // Reload the page after SweetAlert is closed
                        location.reload();

                        $.ajax({
                            type: 'POST',
                            url: 'database/unset_cart.kts.php', // Replace with the script to unset the session cart
                            success: function (unsetResponse) {
                                console.log('Session cart unset successfully');
                            },
                            error: function (xhr, status, error) {
                                console.error('Error unsetting session cart:', status, error);
                            }
                        });
                    });
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error:', status, error);

                    // Use SweetAlert for error message
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while processing your request.',
                    });
                }
            });
        });

        $('#dispose-products-btn').click(function (e) {
            e.preventDefault();

            // Serialize form data
            var formData = $('#receive-invoice').serialize();

            // AJAX request
            $.ajax({
                type: 'POST',
                url: 'database/dispose.kts.php', // Replace with your server-side script URL
                data: formData,
                dataType: 'json', // Expect JSON response
                success: function (response) {
                    // Use SweetAlert for success message
                    Swal.fire({
                        icon: response.success ? 'success' : 'error',
                        title: response.success ? 'Success' : 'Error',
                        text: response.message,
                    }).then((result) => {
                        // Reload the page after SweetAlert is closed
                        location.reload();

                        $.ajax({
                            type: 'POST',
                            url: 'database/unset_cart.kts.php', // Replace with the script to unset the session cart
                            success: function (unsetResponse) {
                                console.log('Session cart unset successfully');
                            },
                            error: function (xhr, status, error) {
                                console.error('Error unsetting session cart:', status, error);
                            }
                        });
                    });
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error:', status, error);

                    // Use SweetAlert for error message
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while processing your request.',
                    });
                }
            });
        });
    });
</script>


    <script>
    
      $(document).ready(function () {
    var table = $('#issuelist').DataTable({
        ajax: {
            url: './database/fetch_issued.kts.php',
            dataSrc: ''
        },
        columns: [
            { data: 'issue_id' },
            { data: 'issued_by' },
            { data: 'date_time' },
         {
    data: 'issue_id',
    render: function (data, type, row) {
        return '<i class="fa fa-eye viewBtn text-dark" data-id="' + data + '"></i>';
    }
}

        ]
    });

    $('#issuelist tbody').on('click', '.viewBtn', function () {
        var issueId = $(this).data('id');
        $.ajax({
            url: 'database/fetch_issued_products.kts.php',
            type: 'GET',
            data: { issue_id: issueId },
            dataType: 'json',
            success: function (response) {
                displayDataInModal(response);
            },
            error: function (xhr, status, error) {
                console.error('AJAX Error:', status, error);
            }
        });
    });

    function displayDataInModal(data) {
        $('#myModal').modal('show');
        var modalBody = $('#myModal .modal-body');
        modalBody.empty();

        if (data.length > 0) {
            var table = $('<table class="table table-striped table-bordered"></table>');
            var thead = $('<thead><tr><th>Product Name</th><th>Quantity</th></tr></thead>');
            var tbody = $('<tbody></tbody>');

            data.forEach(function (item) {
                var row = $('<tr><td>' + item.product_name + '</td><td>' + item.quantity + '</td></tr>');
                tbody.append(row);
            });

            table.append(thead);
            table.append(tbody);
            modalBody.append(table);
        } else {
            modalBody.text('No data available.');
        }
    }
});

      
    </script>
    
    
    
<script>
    $(document).ready(function () {
        $('#check-minutes').on('click', function () {
            var startDate = $('#start-date').val();
            var endDate = $('#end-date').val();

            // Validate date range
            if (!startDate || !endDate) {
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    text: 'Please select both start and end dates.',
                });
                return;
            }

            // AJAX request to fetch data
            $.ajax({
                type: 'POST',
                url: 'database/fetch_range.kts.php',
                data: { startDate: startDate, endDate: endDate },
                dataType: 'json',
                success: function (response) {
                    if (response.success) {
                        // Store data and date range in sessions
                        sessionStorage.setItem('issuedData', JSON.stringify(response.data));
                        sessionStorage.setItem('dateRange', JSON.stringify({ start: startDate, end: endDate }));

                        // Open Bootstrap modal
                        $('#issuedModal').modal('show');
                        displayDataInModal(response.data);
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An error occurred while fetching data.',
                        });
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while processing your request.',
                    });
                }
            });
        });

        function displayDataInModal(data) {
            var modalBody = $('#issuedModal .modal-body');
            modalBody.empty();

            if (data.length > 0) {
                var table = $('<table class="table table-striped table-bordered"></table>');
                var thead = $('<thead><tr><th>Product Name</th><th>Quantity</th><th>Product ID</th></tr></thead>');
                var tbody = $('<tbody></tbody>');

                data.forEach(function (item) {
                    var row = $('<tr><td>' + item.product_name + '</td><td>' + item.quantity + '</td><td>' + item.product_id + '</td></tr>');
                    tbody.append(row);
                });

                table.append(thead);
                table.append(tbody);
                modalBody.append(table);
            } else {
                modalBody.text('No data available.');
            }
        }
    });
</script>
<script>
  
  
  $(document).ready(function () {
    // Existing code...

    $('#printButton').on('click', function () {
        // Redirect to issueprint.php
        window.location.href = 'issueprint.php';
    });

    $('#closeButton').on('click', function () {
        // Redirect to database/close.kts.php
        window.location.href = 'database/close.kts.php';
    });
});

  
      </script>


<script>
    function removeFromCart(productId) {
        // AJAX request to remove the item from the cart
        $.ajax({
            url: 'database/rin.kts.php', // Replace with the actual path to your remove_item.php script
            type: 'POST',
            data: { productId: productId },
            dataType: 'json',
            success: function(response) {
                  if (response.success) {
                    // Item removed successfully, reload the entire page
                    location.reload();
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Item removed successfully!'
                    });
                } else {
                    // Show an error message if removal fails
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to remove item: ' + response.message
                    });
                }
            },
            error: function() {
                // Show an error message for general errors
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Failed to remove item. Please try again later.'
                });
            }
        });
    }
</script>
<script>
  $(document).ready(function() {
    // Initialize Select2
    $('#ingredientUnit').select2({
      placeholder: 'Select a unit',
      allowClear: true
    });

    // Fetch units from the database (simulate with an array for this example)
    var units = ['grams', 'ml', 'pieces', 'liters', 'kg', 'packets'];

    // Append units to the select box
    units.forEach(function(unit) {
      var option = new Option(unit, unit, false, false);
      $('#ingredientUnit').append(option);
    });

    // Optionally, if fetching from a server:
    /*
    $.ajax({
      url: '/path/to/your/api/units', // Adjust to your API endpoint
      method: 'GET',
      success: function(data) {
        data.forEach(function(unit) {
          var option = new Option(unit.name, unit.id, false, false);
          $('#ingredientUnit').append(option);
        });
      }
    });
    */
  });
</script>
        
        <script>
     
     document.getElementById('saveIngredient').addEventListener('click', function() {
    var name = document.getElementById('ingredientName').value;
    var quantity = document.getElementById('ingredientQuantity').value;
    var unit = document.getElementById('ingredientUnit').value;
    var cost = document.getElementById('ingredientCost').value;

    if (name && quantity && unit && cost) {
        // Send data to server
        $.ajax({
            url: './database/save_ingredient.kts.php',
            type: 'POST',
            data: {
                name: name,
                quantity: quantity,
                unit: unit,
                cost: cost
            },
            dataType: 'json', // Expect JSON response from the server
            success: function(response) {
                // Handle success response
                if (response.status === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Ingredient Saved',
                        text: response.message,
                        onClose: () => {
                            // Close the modal
                            $('#ingredientModal').modal('hide');
                            // Reset the form
                            document.getElementById('ingredientForm').reset();
                            $('#ingredientUnit').val(null).trigger('change');
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: response.message
                    });
                }
            },
            error: function(error) {
                // Handle error response
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while saving the ingredient.'
                });
                console.log('Error:', error);
            }
        });
    } else {
        // Alert if fields are not filled
        Swal.fire({
            icon: 'warning',
            title: 'Incomplete Fields',
            text: 'Please fill in all fields.'
        });
    }
});
          $('#ingredientModal').modal('hide');
    </script>
       <script>
$(document).ready(function() {
    // Handle type selection change
    $('#foodType').change(function() {
        var type = $(this).val();
        if (type === 'Single') {
            $('#single').show();
            $('#group').hide();
        } else if (type === 'Group') {
            $('#single').hide();
            $('#group').show();
        } else {
            // Handle default or 'Select Type' case
            $('#single').hide();
            $('#group').hide();
        }
    });
});
</script>

  <script>
  
      $(document).ready(function() {
    // Function to handle live search as user types
    $('#ingredientSearch').on('input', function() {
        var searchQuery = $(this).val().trim(); // Get the trimmed search query

        if (searchQuery.length > 0) {
            $.ajax({
                url: './database/search_ingredient.kts.php', // Replace with your PHP script path
                method: 'GET',
                data: { search: searchQuery },
                dataType: 'json',
                success: function(response) {
                    displayIngredientResults(response);
                },
                error: function(error) {
                    console.log('Error:', error);
                }
            });
        } else {
            $('#ingredientResults').empty(); // Clear results if search query is empty
        }
    });

    // Function to handle adding an ingredient
    function addIngredient(ingredient, quantity) {
        $.ajax({
            url: './database/add_to_recipe.kts.php',
            method: 'POST',
            data: {
                ingredient: ingredient,
                unit: ingredient.unit,
                quantity: quantity
            },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert('Ingredient added to recipe successfully!');
                    fetchRecipeItems();
                } else {
                    alert('Failed to add ingredient to recipe.');
                }
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    }

    // Function to display search results dynamically
    function displayIngredientResults(ingredients) {
        var resultsDiv = $('#ingredientResults');
        resultsDiv.empty();

        if (ingredients.length > 0) {
            var table = $('<table class="table table-striped"></table>');
            var tableHead = $('<thead><tr><th>Code</th><th>Name</th><th>Quantity</th><th>Action</th></tr></thead>');
            var tableBody = $('<tbody></tbody>');

            ingredients.forEach(function(ingredient) {
                var row = $('<tr></tr>');
                var idCell = $('<td>' + ingredient.id + '</td>');
                var nameCell = $('<td>' + ingredient.name + '</td>');
                var quantityCell = $('<td><input type="number" class="form-control" placeholder="Quantity"></td>');
                var addButton = $('<button class="btn btn-primary btn-sm">Add</button>');

                addButton.click(function() {
                    addIngredient({
                        id: ingredient.id,
                        name: ingredient.name,
                        cost_price: ingredient.cost_price,
                        unit: ingredient.unit
                    }, quantityCell.find('input').val());
                });

                var actionCell = $('<td></td>').append(addButton);
                row.append(idCell, nameCell, quantityCell, actionCell);
                tableBody.append(row);
            });

            table.append(tableHead, tableBody);
            resultsDiv.append(table);
        } else {
            resultsDiv.append('<p>No ingredients found.</p>');
        }
    }

    // Function to fetch recipe items
    function fetchRecipeItems() {
        $.ajax({
            url: './database/get_recipe.kts.php',
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                var recipeItemsDiv = $('#recipe_items');
                recipeItemsDiv.empty();

                if (response.length > 0) {
                    var table = $('<table class="table table-striped"></table>');
                    var tableHead = $('<thead><tr><th>Name</th><th>Quantity</th><th>Unit</th><th>Action</th></tr></thead>');
                    var tableBody = $('<tbody></tbody>');

                    response.forEach(function(item, index) {
                        var row = $('<tr></tr>');
                        var nameCell = $('<td>' + item.name + '</td>');
                        var quantityCell = $('<td>' + item.quantity + '</td>');
                        var unitCell = $('<td>' + item.unit + '</td>');
                        var deleteIcon = $('<i class="fa fa-trash" style="cursor:pointer;"></i>');

                        deleteIcon.click(function() {
                            $.ajax({
                                url: './database/delete_from_recipe.kts.php',
                                method: 'POST',
                                data: { index: index },
                                dataType: 'json',
                                success: function(response) {
                                    if (response.status === 'success') {
                                        alert('Ingredient removed from recipe successfully!');
                                        fetchRecipeItems();
                                    } else {
                                        alert('Failed to remove ingredient from recipe.');
                                    }
                                },
                                error: function(error) {
                                    console.log('Error:', error);
                                }
                            });
                        });

                        var actionCell = $('<td></td>').append(deleteIcon);
                        row.append(nameCell, quantityCell, unitCell, actionCell);
                        tableBody.append(row);
                    });

                    table.append(tableHead, tableBody);
                    recipeItemsDiv.append(table);
                } else {
                    recipeItemsDiv.append('<p>No recipe items added.</p>');
                }
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    }

    // Initial fetch to display recipe items when the page loads
    fetchRecipeItems();
});


  </script>
        <script>
    document.getElementById('foodImageInput').addEventListener('change', function() {
        var file = this.files[0];

        if (file) {
            var reader = new FileReader();

            reader.onload = function(e) {
                document.getElementById('imagePreview').src = e.target.result;
                document.getElementById('imagePreview').style.display = 'block';
            };

            reader.readAsDataURL(file);
        } else {
            document.getElementById('imagePreview').src = '';
            document.getElementById('imagePreview').style.display = 'none';
        }
    });
</script>
  <script>
    $(document).ready(function() {
        // Function to handle food search on input change
        $('#foodSearch').on('input', function() {
            var searchTerm = $(this).val().trim();

            if (searchTerm.length > 0) {
                $.ajax({
                    url: './database/search_food.kts.php', // Replace with your search food endpoint
                    method: 'GET',
                    data: { foodSearch: searchTerm },
                    dataType: 'json',
                    success: function(response) {
                        displayFoodResults(response); // Display search results
                    },
                    error: function(error) {
                        console.log('Error:', error);
                    }
                });
            } else {
                $('#foodResults').empty(); // Clear results if search query is empty
            }
        });

       // Function to display food search results
function displayFoodResults(foods) {
    var resultsDiv = $('#foodResults');
    resultsDiv.empty();

    if (foods.length > 0) {
        var table = $('<table class="table table-striped"></table>');
        var tableHead = $('<thead><tr><th>Code</th><th>Name</th><th>Quantity</th><th>Action</th></tr></thead>');
        var tableBody = $('<tbody></tbody>');

        foods.forEach(function(food) {
            var row = $('<tr></tr>');
            var foodCell = $('<td>' + food.food_id + '</td>');
            var nameCell = $('<td>' + food.name + '</td>');
            var quantityCell = $('<td><input type="number" class="form-control" placeholder="Quantity"></td>');
            var addFoodButton = $('<button class="btn btn-primary btn-sm">Add</button>');

            addFoodButton.click(function() {
                var quantity = parseInt(quantityCell.find('input').val());

                if (isNaN(quantity) || quantity === 0) {
                    alert('Please enter a valid quantity.');
                    return;
                }

                var cost = parseFloat(food.cost_price);
                addFoodToSession(food.food_id, food.name, cost, quantity); // Pass food_id, name, cost, and quantity
            });

            var actionCell = $('<td></td>').append(addFoodButton);
            row.append(foodCell, nameCell, quantityCell, actionCell);
            tableBody.append(row);
        });

        table.append(tableHead, tableBody);
        resultsDiv.append(table);
    }
}

// Function to add food to session
function addFoodToSession(foodId, foodName, foodCost, quantity) {
    $.ajax({
        url: './database/add_food_to_session.kts.php', // PHP script to add food to session
        method: 'POST',
        data: {
            food_id: foodId,
            food_name: foodName,
            food_cost: foodCost,
            quantity: quantity
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                alert('Food added to session successfully!');
                fetchAndDisplayFoodItems(); // Refresh food items display
            } else {
                alert('Failed to add food to session.');
            }
        },
        error: function(error) {
            console.log('Error:', error);
        }
    });
}

      function fetchAndDisplayFoodItems() {
    $.ajax({
        url: './database/get_fooditems.kts.php',
        method: 'GET',
        dataType: 'json'
    })
    .done(function(response) {
                console.log('Response:', response);  // Log the response to check its structure

        if (response && response.length > 0) {
            var tableHtml = '<table class="table table-striped">';
            tableHtml += '<thead><tr><th>Name</th><th>Quantity</th><th>Action</th></tr></thead>';
            tableHtml += '<tbody>';

            response.forEach(function(item) {
                tableHtml += '<tr>';
                tableHtml += '<td>' + item.name + '</td>';
                tableHtml += '<td>' + item.quantity + '</td>';
                tableHtml += '<td><button class="btn btn-danger btn-sm delete-food-item" data-id="' + item.food_id + '">Delete</button></td>';
                tableHtml += '</tr>';
            });

            tableHtml += '</tbody></table>';
            $('#food_items').html(tableHtml);

            // Attach click event listener to delete buttons
            $('.delete-food-item').off('click').on('click', function() {
                var foodId = $(this).data('id');
                deleteFoodFromSession(foodId);
            });
        } else {
            $('#food_items').html('<p>No food items found.</p>');
        }
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.log('Error fetching food items:', errorThrown);
        $('#food_items').html('<p>Error fetching food items.</p>');
    });
}

function deleteFoodFromSession(foodId) {
    $.ajax({
        url: './database/delete_food_from_session.php',
        method: 'POST',
        data: { food_id: foodId },
        dataType: 'json'
    })
    .done(function(response) {
        if (response.success) {
            fetchAndDisplayFoodItems(); // Refresh the table after deletion
            alert('Food item deleted from session successfully!');
        } else {
            alert('Failed to delete food item from session.');
        }
    })
    .fail(function(error) {
        console.log('Error:', error);
        alert('Failed to delete food item. Please try again later.');
    });
}

// Initial call to fetch and display food items
$(document).ready(function() {
    fetchAndDisplayFoodItems();
});

        // Initial fetch and display of food items from session when the page loads
        fetchAndDisplayFoodItems();
    });
</script>
<script>

$(document).ready(function() {
    // Preview image on file input change
    $('#foodImageInput').change(function() {
        const file = this.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#imagePreview').attr('src', e.target.result).show();
            }
            reader.readAsDataURL(file);
        }
    });

    $('#saveFood').click(function() {
        const formData = new FormData();
        formData.append('name', $('#foodName').val());
        formData.append('type', $('#foodType').val());
        formData.append('price', $('#foodPrice').val());
        formData.append('category', $('#categoryz').val());
        formData.append('description', $('#fooddescription').val());

        const imageFile = $('#foodImageInput')[0].files[0];
        if (imageFile) {
            formData.append('image', imageFile);
        }

        $.ajax({
            url: './database/insert_food.kts.php',
            method: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire('Success', 'Food item added successfully!', 'success');
                    location.reload();
                    // Optionally, clear the form or reload data
                } else {
                    Swal.fire('Error', 'Failed to add food item: ' + response.message, 'error');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                Swal.fire('Error', 'Error adding food item: ' + errorThrown, 'error');
            }
        });
    });
});

        
</script>
   
    
<script>
  function previewImage(event) {
    var input = event.target;
    var reader = new FileReader();
    reader.onload = function(){
      var dataURL = reader.result;
      var output = document.getElementById('beverageImagePreview');
      output.src = dataURL;
      output.style.display = 'block';
    };
    reader.readAsDataURL(input.files[0]);
  }
</script>
    
 <script>
    $(document).ready(function () {
        $('#saveBeverages').click(function (e) {
            e.preventDefault();

            // Create FormData object
            var formData = new FormData($('#beverageForm')[0]);

            $.ajax({
                url: './database/add_beverage.kts.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                contentType: false, // Important: prevent jQuery from setting content type
                processData: false, // Important: prevent jQuery from processing data
                success: function(response) {
                    if (response.status === 'success') {
                        $('#result').html('<div class="alert alert-success">' + response.message + '</div>');
                        $('#beverageForm')[0].reset(); // Reset form on success
                    } else {
                        $('#result').html('<div class="alert alert-danger">' + response.message + '</div>');
                    }
                },
                error: function(xhr, status, error) {
                    var errorMessage = xhr.status + ': ' + xhr.statusText;
                    $('#result').html('<div class="alert alert-danger">Error: ' + errorMessage + '</div>');
                }
            });
        });
    });
</script>
 <script>
    $(document).ready(function() {
        // Initialize Food Table
        var foodTable = $('#foodTable').DataTable({
            "ajax": "./database/fetch_food.kts.php", // PHP script for fetching data
            "columns": [
                { "data": "food_id" },
                { "data": "name" },
                { "data": "price" },
                { "data": "cost_price" },
                { "data": "food_group" },
                { "data": "category" },
                { "data": null, "render": function(data, type, row) {
                    return `<a href="edit_food.php?id=${row.food_id}" class="btn btn-primary btn-sm"><i class="fa fa-edit"></i> Edit</a>
                            <a href="delete_food.php?id=${row.food_id}" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i> Delete</a>`;
                }}
            ],
             "dom": 'Bfrtip', // Adds button elements
      "buttons": [
                    {
                        extend: 'copy',
                        title: 'Food Menu List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'csv',
                        title: 'Food Menu List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'excel',
                        title: 'Food Menu List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'pdf',
                        title: 'Food Menu List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'print',
                        title: 'Food Menu List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    }
                ]
            });
    });

        // Initialize Beverages Table
     
</script>
<script>
      $(document).ready(function() {
    var beveragesTable = $('#beveragesTable').DataTable({
        "ajax": "./database/fetch_beverages.kts.php", // PHP script for fetching data
        "columns": [
            { "data": "beverage_id" },
            { "data": "beverage_name" },
            { "data": "buying_price" },
            { "data": "selling_price" },
            { "data": "qbselling_price" },
            { "data": "category" },
            { "data": "shots_available" },
            { "data": null, "render": function(data, type, row) {
                return `<button data-id="${row.beverage_id}" class="btn btn-primary btn-sm editBeverage">Edit <i class="fa fa-edit"></i></button>
                        <button data-id="${row.beverage_id}" class="btn btn-danger btn-sm deleteBeverage">Delete <i class="fa fa-trash"></i></button>`;
            }}
        ],
        "dom": 'Bfrtip', // Adds button elements
        "buttons": [
                    {
                        extend: 'copy',
                        title: 'Beverages Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'csv',
                        title: 'Beverages Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'excel',
                        title: 'Beverages Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'pdf',
                        title: 'Beverages Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'print',
                        title: 'Beverages Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    }
                ]
            });

        // Event listeners for edit and delete buttons for Beverages Table
        $('#beveragesTable').on('click', '.editBeverage', function() {
            var beverageId = $(this).data('id');
            // Code for handling the edit action
            alert('Edit beverage with ID: ' + beverageId);
        });

        $('#beveragesTable').on('click', '.deleteBeverage', function() {
            var beverageId = $(this).data('id');
            // Code for handling the delete action
            alert('Delete beverage with ID: ' + beverageId);
        });
    });
</script>
 <script>
        $(document).ready(function() {
            var ingredientsTable = $('#ingredientsTable').DataTable({
                "ajax": "./database/fetch_ingredient.kts.php", // PHP script for fetching data
                "columns": [
                    { "data": "id" },
                    { "data": "name" },
                    { "data": "quantity" },
                    { "data": "unit" },
                    { "data": "cost_per_unit" },
                    { 
                        "data": null, 
                        "render": function(data, type, row) {
                            return (row.quantity * row.cost_per_unit).toFixed(2);
                        }
                    },
                    { 
                        "data": null, 
                        "render": function(data, type, row) {
                            return `<button data-id="${row.id}" class="btn btn-primary btn-sm editIngredient">Edit <i class="fa fa-edit"></i></button>
                                    <button data-id="${row.id}" class="btn btn-danger btn-sm deleteIngredient">Delete <i class="fa fa-trash"></i></button>`;
                        }
                    }
                ],
                "dom": 'Bfrtip', // Adds button elements
                "buttons": [
                    {
                        extend: 'copy',
                        title: 'Ingredients Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'csv',
                        title: 'Ingredients Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'excel',
                        title: 'Ingredients Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'pdf',
                        title: 'Ingredients Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    },
                    {
                        extend: 'print',
                        title: 'Ingredients Stock List',
                        exportOptions: {
                            columns: ':not(:last-child)' // Exclude the last column
                        }
                    }
                ]
            });

            // Event listeners for edit and delete buttons for Ingredients Table
            $('#ingredientsTable').on('click', '.editIngredient', function() {
                var ingredientId = $(this).data('id');
                // Code for handling the edit action
                alert('Edit ingredient with ID: ' + ingredientId);
            });

            $('#ingredientsTable').on('click', '.deleteIngredient', function() {
                var ingredientId = $(this).data('id');
                // Code for handling the delete action
                alert('Delete ingredient with ID: ' + ingredientId);
            });
        });
    </script>
    
    <script>
    document.getElementById('totsForm').addEventListener('submit', function(event) {
    event.preventDefault();

    const totName = document.getElementById('totName').value;
    const totQuantity = document.getElementById('totQuantity').value;
    const totPrice = document.getElementById('totPricey').value;
    
    // Perform any necessary validation here

    // Example: Display the form data in the console
    console.log(`Name: ${totName}, Price: ${totPrice}, Quantity: ${totQuantity}`);

    // If you need to send the data to the backend
    fetch('./database/tots.kts.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: totName,
            price: totPrice,
            quantity: totQuantity
        })
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success:', data);
        // Handle success, close the modal, etc.
        $('#totsModal').modal('hide');
    })
    .catch((error) => {
        console.error('Error:', error);
        // Handle error
    });
});
    </script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
    const totSelect = document.getElementById('t_availability');
    const totsearchpane = document.getElementById('totsearchpane');

    totSelect.addEventListener('change', function() {
        if (this.value === 'Yes') {
            totsearchpane.style.display = 'block';
        } else {
            totsearchpane.style.display = 'none';
        }
    });
});

    </script>
    
       
    
<script>
    $(document).ready(function() {
        function updateSessionDisplay(tots) {
            let sessionTable = '<table class="table table-bordered"><thead><tr><th>ID</th><th>Name</th><th>Action</th></tr></thead><tbody>';
            tots.forEach(function(tot) {
                sessionTable += `<tr>
                    <td>${tot.id}</td>
                    <td>${tot.name}</td>
                    <td><button class="btn btn-danger remove-tot" data-id="${tot.id}">Delete</button></td>
                </tr>`;
            });
            sessionTable += '</tbody></table>';
            $('#tot-session').html(sessionTable);
        }

     $('#totsearch').on('input', function() {
            let query = $(this).val();
            if (query.length > 0) {
                $.ajax({
                    url: './database/search_tots.kts.php',
                    type: 'GET',
                    data: { query: query },
                    dataType: 'json',
                    success: function(data) {
                        let resultsTable = '<table class="table table-bordered"><thead><tr><th>ID</th><th>Name</th><th>Action</th></tr></thead><tbody>';
                        data.forEach(function(tot) {
                            resultsTable += `<tr>
                                <td>${tot.tot_id}</td>
                                <td>${tot.name}</td>
                                <td><button class="btn btn-success add-tot" data-id="${tot.tot_id}" data-name="${tot.name}" data-price="${tot.price}">Add</button></td>
                            </tr>`;
                        });
                        resultsTable += '</tbody></table>';
                        $('#totsresults').html(resultsTable);
                    }
                });
            } else {
                $('#totsresults').html('');
            }
        });


        $(document).on('click', '.add-tot', function() {
            let totId = $(this).data('id');
            let totName = $(this).data('name');
            let totBei = $(this).data('price');

            $.ajax({
                url: './database/add_to_sessiontots.kts.php',
                type: 'POST',
                data: { id: totId, name: totName, price:totBei},
                dataType: 'json',
                success: function(response) {
                    alert('Tot added to session!');
                    updateSessionDisplay(response);
                }
            });
        });

        $(document).on('click', '.remove-tot', function() {
            let totId = $(this).data('id');

            $.ajax({
                url: './database/remove_from_session.kts.php',
                type: 'POST',
                data: { id: totId },
                dataType: 'json',
                success: function(response) {
                    alert('Tot removed from session!');
                    updateSessionDisplay(response);
                }
            });
        });

        // Initial call to update the session display when the page loads
        $.ajax({
            url: './database/get_session_tots.kts.php',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                updateSessionDisplay(response);
            }
        });
    });
</script>
      <script>
      <script>
        $(document).ready(function() {
            $('#totsTable').DataTable({
                "ajax": "fetch_tots.php",
                "columns": [
                    { "data": "name" },
                    { "data": "quantity" },
                    { "data": "created_at" },
                    { "data": "price" },
                    {
                        "data": null,
                        "render": function(data, type, row) {
                            return `<button class='btn btn-warning btn-sm edit-btn'>Edit</button> 
                                    <button class='btn btn-danger btn-sm delete-btn'>Delete</button>`;
                        }
                    }
                ]
            });

            $('#totsTable tbody').on('click', 'button.edit-btn', function() {
                var data = $('#totsTable').DataTable().row($(this).parents('tr')).data();
                alert('Edit Tot: ' + data.tot_id);
                // Implement edit functionality here
            });

            $('#totsTable tbody').on('click', 'button.delete-btn', function() {
                var data = $('#totsTable').DataTable().row($(this).parents('tr')).data();
                if (confirm('Are you sure you want to delete Tot: ' + data.tot_id + '?')) {
                    // Implement delete functionality here
                }
            });
        });
    </script>

</body>

</html>