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


?>
<!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 id="shopname"></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">

</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-12 col-sm-12" id="vendor">
                        <div class="card gradient-9">
                            <div class="card-body">
                                <h3 class="card-title text-white"></h3>
                                <div class="d-inline-block">
                                    <h2 class="text-white">Receive/Dispose</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">Product Details</h4>
                                <div class="table-responsive">
                                    <table class="table table-striped display table-bordered items-table" >
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Product Name</th>
                                                <th>Vendor</th>
                                                <th>Buying Price</th>
                                                <th>Selling Price</th>
                                                <th>Qty</th>
                                                <th>Product Category</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">Invoice Details</h4>
                                <div class="table-responsive">
                                    <table class="table table-striped table-bordered display table-sm purchase-table" id="purchaseTable">
                                        <thead>
                                            <tr>
                                                <th>#</th>
                                                <th>Invoice  No</th>
                                                <th>Supplier</th>
                                                <th>Total</th>
                                                <th>Date</th>
                                                <th>Action</th>
                                               
                                              
                                            </tr>
                                        </thead>
                                       <tbody></tbody>
                                        <tfoot>
                                            <tr>
                                                <th>#</th>
                                                <th>Invoice  No</th>
                                                <th>Supplier</th>
                                                <th>Total</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">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">Issued List</h4>
                                <div class="table-responsive">
                                    <table class="table table-hover" id="issuelist">
                                         <thead>
                <tr>
                    <th>#</th>
                    <th>Issued By</th>
                    <th>Issue Date/Time</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody></tbody>
            <tfoot>
                <tr>
                    <th>#</th>
                    <th>Issued By</th>
                    <th>Issue Date/Time</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>
               
               
                
                <!-- Issued Products Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Issued Products</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <!-- Data will be displayed here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

               
               <!-- range issued report  modal --> 
               
                <div class="modal fade" id="issuedModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="exampleModalLabel">Issued Items</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                    <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <!-- Data will be dynamically populated here -->
                            </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="printButton">Print</button>
                            </div>
                        </div>
                    </div>
                </div>
       
                       
        
                <!-- End Of Send To Shop Modal -->
                <!-- Start Of Send To shop Items  Modal-->
                <div class="modal fade" id="shopite">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                       <div class="dropdown-content-body-sm">
                                    <div class="card-sm">
                                      <div class="card-body">
                                          <h4 class="card-title">Items Details</h4>
                                          <div class="table-responsive">
                                              <table class="table table-striped table-bordered zero-configuration table-sm" id="bootstrap-data-table-export">
                                                <thead>
                                                    <tr>
                                                        
                                                        <th scope="col">Name</th>
                                                        <th scope="col">Company</th>
                                                        <th scope="col">Price</th>
                                                        <th scope="col">Quantity</th>
                                                        <th scope="col">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <th>Brake Pads</th>
                                                        <th>Brembo</th>
                                                        <td>250</td>
                                                        <td>5</td>
                                                        <td><button class="btn btn-info btn-sm">Remove</button></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Head Lamps</th>
                                                        <td>Neon</td>
                                                        <td>450</td>
                                                        <td>45</td>
                                                        <td><button class="btn btn-info btn-sm">Remove</button></td>
                                                    </tr>
                                                   
                                                </tbody>
                                                 <tfoot>
                                            <tr>
                                               
                                                <th>***</th>
                                                <th>***</th>
                                                <th></th>
                                                <th></th>
                                                <th><button class="btn btn-danger btn-sm">Send To Shop</button></th>
                                            </tr>
                                        </tfoot>
                                            </table>
                                          </div>
                                      </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 Product</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 Product</button>
                </form>
            </div>
        </div>
    </div>
</div>

                <!-- Start Of Add Vendor Modal-->
                <div class="modal fade" id="vendite">
                  <div class="modal-dialog" role="document">
                    <div class="modal-content">
                       <div class="dropdown-content-body-sm">
                                    <div class="card-sm">
                                       <div class="card-body">
                               <div class="input-group icons">
                         <div class="input-group-prepend">
                            <span class="input-group-text bg-transparent border-0 pr-2 pr-sm-3" value="search" id="basic-addon1"><i class="mdi mdi-magnify"></i></span>
                        </div>
                       <form action="#" method="POST" name="">
                     
 <input type="text" name="productk" id="searchInput" class="form-control" placeholder="Search Database" aria-label="Search Database"/>
    <div id="searchResults"></div>
                      </form>
                       </div>
                                
                                <p></p>
                                <h4 class="card-title">Add New Product</h4>
                                <p></p>
                                
                                <div></div>
                                <div class="basic-form">
                                    <form  id="product-form">
                                        <div class="form-row">
                                            <div class="form-group col-md-6 col-sm-6">
                                              <label><h6>Product Name</h6></label>
                                                <input type="text" class="form-control" placeholder="Product Name" id="product_name" name="product_name"required>
                                            </div>
                                            <div class="form-group col-md-6 col-sm-6">
                                                <label><h6>Vendor</h6></label>
                                                <input type="text" class="form-control" placeholder="Vendor" id="company" name="company" onkeyup="searchClients(this.value)" required>
                                                <div id="clientsDropdown"></div>
                                                  <input type="hidden" class="form-control" name="id" id="id">
                                                                           
                                            </div>
                                           
                                           </div>
                                           <div class="form-row">
                                            <div class="form-group col-md-4 col-sm-6">
                                                <label><h6>Buying Price</h6></label>
                                                <input type="number" class="form-control" placeholder="Buying Price"   id="buying_price" name="buying_price"required>
                                            </div>
                                            <div class="form-group col-md-4 col-sm-6">
                                                <label><h6>Sellling Price</h6></label>
                                                <input type="number" class="form-control" placeholder="Selling Price"  id="selling_price" name="selling_price"required>
                                            </div>
                                            <div class="form-group col-md-4 col-sm-6">
                                                <label><h6>Quantity</h6></label>
                                                <input type="number" class="form-control" placeholder="Quantity" id="shop_quantity" name="shop_quantity" required>
                                                <input type="hidden" class="form-control" placeholder="Quantity" id="store_quantity" name="store_quantity"  value="0" >
                                            </div>
                                        </div>
                                       
                                         <div class="form-row">
                                             <div class="form-group col-md-4 col-sm-6">
                                                <label><h6>Category</h6></label>
                                               <select id="categoryz" name="categoryz" class="form-control" required>
                                                    <option selected="selected" disabled>Choose...</option>
                                                </select>
                                            </div>  
                                        </div>
                                        
                                        <button type="submit" class="btn btn-dark">Submit</button>
                                         <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                    </form>
                                </div>
                            </div>
                          </div>
                       </div>
                    </div>
                  </div>
               </div>
               
               <!-- Start of cart modal -->
              <!-- Modal for displaying cart items -->
<div class="modal fade" id="cartModal" tabindex="-1" role="dialog" aria-labelledby="cartModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cartModalLabel">Cart Items</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
           
             <div class="modal-body">
  <?php
                // Display cart items in the modal as a responsive table
                if (!empty($_SESSION['cart'])) {
                    echo '<div class="table-responsive">';
                    echo '<table class="table">';
                    echo '<thead>';
                    echo '<tr>';
                    echo '<th>Product Name</th>';
                    echo '<th>Buying Price</th>';
                    echo '<th>Quantity</th>';
                    echo '<th>Subtotal</th>';
                    echo '<th>Action</th>';
                    echo '</tr>';
                    echo '</thead>';
                    echo '<tbody>';

                    $totalCost = 0; // Initialize total cost

                    foreach ($_SESSION['cart'] as $item) {
                        echo '<tr>';
                        echo '<td>' . $item['product_name'] . '</td>';
                        echo '<td>' . $item['buying_price'] . '</td>';
                        echo '<td>' . $item['quantity'] . '</td>';
                        echo '<td>' . $item['quantity'] * $item['buying_price'] . '</td>';
                        echo '<td><button class="btn btn-danger" onclick="removeFromCart(' . $item['product_id'] . ')">Remove</button></td>';
                        echo '</tr>';

                        $totalCost += $item['quantity'] * $item['buying_price']; // Add subtotal to total cost
                    }

                    echo '</tbody>';
                    echo '</table>';
                    echo '</div>';
                } else {
                    echo '<p>Cart is empty.</p>';
                }
                ?>
              </div>
               <div class="modal-body">
            
                
<form id="receive-invoice">
    <div class="form-row">
        <div class="form-group col-md-4">
            <label for="product-name-input">Invoice No/Disposed By</label>
            <input type="text" id="invoice" class="form-control" name="invoice">
        </div>
        <div class="form-group col-md-4">
            <label for="company-input">Supplier/Vendor</label>
            <input type="text" name="company" id="company" class="form-control" required>
            <div class="clientsDropdown"></div>
            <input type="hidden" name="id" id="id">
        </div>
        <div class="form-group col-md-4">
            <label for="buying-price-input">Total cost</label>
            <input type="number" value="<?php echo $totalCost ?>" class="form-control" id="totalcost" name="totalcost">
        </div>
    </div>

    <button type="submit" class="btn btn-danger" id="dispose-products-btn" style="float: left;">Dispose Products</button>
    <button type="submit" class="btn btn-primary" id="receive-products-btn" style="float: right;">Receive Products</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>
 
 <!-- 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>
    <!--**********************************
        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/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>
 //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();
  });    
 </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>
</body>

</html>