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


?>
<?php  
 
if (isset($_GET['action'])) {
    if ($_GET['action'] == 'clearall') {
        unset($_SESSION['order']);
        header('Location: ./orders.php');
        exit();
    }

    if ($_GET['action'] == 'remove') {
        foreach ($_SESSION['order'] as $key => $value) {
            if ($value['id'] == $_GET['id']) {
                unset($_SESSION['order'][$key]);
                header('Location:./orders.php');
                exit();
            }
        }
    }
}


?>



<!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>Ray Technologys</title>

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

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

</head>

<body class="h-300">

        <!--**********************************
            Nav header start
        ***********************************-->
        
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
        
        <!--**********************************
            Header end ti-comment-alt
        ***********************************-->

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

        <!--**********************************
            Content body start
        ***********************************-->
       



                </div>

            <div class="row page-titles mx-0">
                <div class="col p-md-0">
                    <?php
if ($_SESSION['type'] == "Manager") {
    echo '
    <nav class="navbar navbar-expand-lg navbar-light" style="background: linear-gradient(to right, #FFB6C1, #E066FF, #00FFFF, #00FF00);">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="index.php">Home</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="products.php">Add Products</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="add-customer.php">Add Customer</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="add-cashier.php">Add Cashier</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="bills.php">Client Debts</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="logout.php">Log Out</a>
            </li>
        </ul>
    </nav>
    ';
} else {
    echo '
    <nav class="navbar navbar-expand-lg navbar-light" style="background: linear-gradient(to right, #FFB6C1, #E066FF, #00FFFF, #00FF00);">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="bills.php">Client Debts</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="add-customer.php">Add Customer</a>
            </li>
            <li class="nav-item">
                <a class="nav-link font-weight-bold" href="logout.php">Log Out</a>
            </li>
            
             <li class="breadcrumb-item active"><a href="cashier.php" >Home</a></li>
        </ul>
    </nav>
    ';
}
?>
                </div>
            </div>
            <!-- row -->

            <div class="container-fluid">
                <div class="row">
                    <div class="col-4">
                    <div class="card-sm d-flex">
                                       <div class="card card-sm">
                                      <div id="order-list"  class="card-body">
                                         </div>
                                      </div>
                                    </div>
                  </div>
                    <div class="col-8">
                        <div class="card card-sm">
                            <div class="card-body">
                                <h4 class="card-title">Inventory</h4>
                                <div class="table-responsive">
                                    <table id="productTable" class="table table-bordered  table-sm">

        <thead>
            <tr>
                <th>#code</th>
                <th>Name</th>
                <th>Available</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="productTableBody">
            <!-- Product rows will be populated here -->
        </tbody>
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Available</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Action</th>
            </tr>
        </tfoot>
    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-body">
                                <h4 class="card-title">Orders</h4>
                                <div class="active-member">
                                    <div class="table-responsive">
                                        <table id="bootstrap-data-table-export" class="table table-striped zero-cofiguration table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Seller Name</th>
                                                    <th>Table Name</th>
                                                    <th>Total</th>
                                                    <th>Date</th>
                                                    <th>Action</th>
                                                    <th>Update</th>
                                                </tr>
                                            </thead>
                                             <tbody>
                                              <?php
        
                                                   $sql = "SELECT * FROM orders WHERE seller_name='{$_SESSION['user']}'";
                                                    $result=mysqli_query($conn,$sql);
                                                     while($row=mysqli_fetch_array($result)){
                                                  ?>
                                                <tr>
                                                    <td><?php echo $row['order_id']; ?></td>
                                                    <td>
                                                      <?php echo $row['seller_name']; ?>
                                                    </td>
                                                    <td>
                                                      <?php echo $row['table_name']; ?>
                                                    </td>
                                                    <td>
                                                        <?php echo $row['total_amount']; ?>
                                                    </td>
                                                    
                                                    <td>
                                                       <?php echo $row['order_date']; ?>
                                                    </td>
                                                    <td>
																			
             										<i class="fa fa-eye view-order-details" data-id="<?php echo $row['order_id'];?>"></i>

              										</td>
                                                  <td>
                                                    <form action="database/ordertosales.kts.php" method="post">
                                                    <input type="hidden" value="<?php echo $row['order_id'] ?>" name="order_id">
                                                    <button type="submit" class="btn btn-danger">Close Bill</button></form></td> <td>
                                                    <form action="database/updateorder.kts.php" method="post">
                                                    <input type="hidden" value="<?php echo $row['order_id'] ?>" name="order_id">
                                                    <button type="submit" class="btn btn-warning">Update Bill</button></form></td>
                                                </tr>
                                               <?php } ?>
                                               
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>                        
                    </div>
                </div>
                
                
                
                <!-- Transaction Modal -->
                                     <div class="modal fade bd-example-modal-sm" id="transaction"  role="dialog"  tabindex="-1" role="dialog" aria-hidden="true">
                                                
                                        <div class="modal-dialog modal-sm" >
                                                     
                                            <div class="modal-content">
                                               <form method="post" action="./database/orders.kts.php">
                                                <div class="modal-header">
                                               
                                                    <h5 class="modal-title">Table Details</h5>
                                                    <button type="button" class="close" data-dismiss="modal"><span>&times;</span>
                                                    </button>
                                                    
                                                </div>
                                               
                                                <div class="modal-header">
                                                <h4 class="modal-title" name="amount_to_pay" id="amounttopay" value="<?php echo $total; ?>">Total Amount: <?php echo $total; ?></h4>

                                                </div>
                                                <div class="modal-body">
                                                  <div class="table-responsive">
                                                        <table class="table header-border table-hover verticle-middle">
                                                                <thead>
                                                                
                                                                        
                                                                      <tr>
                                                                        <td colspan="3"></td>
                                                                            <th> Table Name</th>
                                                                            <td>
                                                                                <input type="text" class="form-control" name="client_name"  id="client_name" onkeyup="searchClients(this.value)"  required>
                                                                                <div id="clientsDropdown"></div>
                                                                            </td>
                                                                        </tr>
                                                                        <tr>
                                                                            <td colspan="3"></td>
                                                                            <th> Table Id</th>
                                                                            <td><input type="text" class="form-control" name="phone_number" id="phone_number"></td>
                                                                        </tr>
                                                                        
                                                                       <input type="hidden" name="cash" id ="cash" value="'.$total.'">
                                                                       <input type="hidden" name="total" id ="total"  value="<?php echo $total; ?>" >
                                                               
                                                
                                                                </thead>
                                                               
                                                           </table>
                                                               </div>
                                                              
                                                   
                                                </div>
                                                
                                                <div class="modal-footer">
                                                
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                    
                                                   <button type="submit" name="transact" class="btn btn-primary">Submit</button>
                                                </div>
                                                </form>
                                         
                    </div>
                 </div>
              </div>
                
                <!-- end of transaction modal -->
                
                    <!-- Add Stock Modal -->
               <div class="modal fade" id="viewOrderDetailsModal">
                  <div class="modal-dialog" role="document">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h5 class="modal-title" id="viewOrderDetailsModalLabel">Order 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">
                            <div class="row">
                              <div class="col-md-12">
                                <table class="table table-bordered">
                                  <thead>
                                    <tr>
                                      <th>Name</th>
                                      <th>Price</th>
                                      <th>Quantity</th>
                                      <th>Subtotal</th>
                                     
                                     
                                    </tr>
                                  </thead>
                                  <tbody id="orderDetailsTableBody">

                                  </tbody>
                                  <tfoot id="ordertotals">

                                  </tfoot>
                                </table>
                              </div>
                            </div>
                          </div>
                                <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                </div>
                        </div>
                      </div>
                    </div>
               <!-- End Of aAdd Poduct Modal  -->
           

            </div>
      </div>
            <!-- #/ container -->
        </div>
        <!--**********************************
            Content body end
        ***********************************-->
        
      
        
        <!--**********************************
            Footer start
        ***********************************-->
        <div class="footer">
            <div class="copyright">
                <p>Copyright &copy; Designed & Developed by <a href="https://kakashitech.com">Kakashi Tech</a> 2023</p>
            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->
    
    <!--**********************************
        Main wrapper end
    ***********************************-->

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

    <script src="./quixlab/plugins/tables/js/jquery.dataTables.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable/dataTables.bootstrap4.min.js"></script>
    <script src="./quixlab/plugins/tables/js/datatable-init/datatable-basic.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>

    
  <script>
    function sub() {
    var numOne = document.getElementById('amounttopay').value;
    var numTwo = document.getElementById('amount_paid').value;
    console.log("numOne:", numOne);
    console.log("numTwo:", numTwo);
    if (numOne == "") numOne = 0;
    if (numTwo == "") numTwo = 0;
    var numOneParsed = parseInt(numOne);
    var numTwoParsed = parseInt(numTwo);
    console.log("numOneParsed:", numOneParsed);
    console.log("numTwoParsed:", numTwoParsed);
    ...
}
</script>
  <script>
// Handle click event on "fa fa-eye" icon
$(document).on('click', '.view-order-details', function() {
  var orderId = $(this).data('id');
  
  // Make an AJAX request to get order details for the selected order ID
  $.ajax({
    url: './database/getorderinfo.kts.php',
    method: 'POST',
    data: {order_id: orderId},
    dataType: 'json',
    success: function(response) {
      // Update the table body with order details
      var tableBody = $('#orderDetailsTableBody');
      tableBody.empty();
      
      var totalSubtotal = 0.00;
      
      for (var i = 0; i < response.length; i++) {
        var item = response[i];
        totalSubtotal += parseFloat(item.subtotal);
        tableBody.append('<tr><td>' + item.product_name + '</td><td>' + item.price + '</td><td>' + item.quantity + '</td><td>' + item.subtotal + '</td></tr>');
      }
      
      tableBody.append('<tr><td colspan="3"><strong>Total:</strong></td><td>' + totalSubtotal + '</td></tr>');
      
      // Show the modal
      $('#viewOrderDetailsModal').modal('show');
    },
    error: function(xhr, status, error) {
      alert('Error: ' + error);
    }
  });
});

</script>

  <script>
   function searchClients(keyword) {
    // Make an AJAX request to search for clients by name
    $.ajax({
        url: 'database/searchtable.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 client name input
$('input[name="client_name"]').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');
    var phoneNumber = $(this).data('phone');
    
    // Update the client name and phone number inputs and hide the search results dropdown
    $('input[name="client_name"]').val(clientName);
    $('input[name="phone_number"]').val(phoneNumber);
    $('#clientsDropdown').hide();
    
    // Update the hidden client ID input
    $('#clientIdInput').val(clientId);
});

    </script>
<script>
  // Add event listener to the input field
  document.getElementById('val-username').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>
$(document).ready(function() {
    // Fetch and populate the product table
    $.ajax({
        type: "GET",
        url: "database/fetch_products.kts.php",
        dataType: "json",
        success: function(response) {
            if (response && response.length > 0) {
                var table = $('#productTable').DataTable({
                    "searching": true,
                    "paging": true,
                    "info": true
                });

                $.each(response, function(index, product) {
                    var row = [
                        product.product_id,
                        product.product_name,
                        product.shop_quantity,
                        '<input type="number" class="form-control-sm price-input" placeholder="Enter  price.." step="any" required>',
                        '<input type="number" class="form-control-sm qty-input" placeholder="Enter qty needed.." step="any" required>',
                        '<button class="btn btn-success bg-success fa fa-shopping-cart btn-sm add-to-cart">Order</button>'
                    ];
                    table.row.add(row).draw(false);
                });
            }
        },
        error: function() {
            console.log('Error fetching product details.');
        }
    });

    // Event delegation for the add-to-cart button
    $('#productTable tbody').on('click', '.add-to-cart', function() {
        var $productRow = $(this).closest('tr');
        var productId = $productRow.find('td:eq(0)').text(); // Adjust the index as per your table
        var productName = $productRow.find('td:eq(1)').text(); // Adjust the index as per your table
        var productPrice = $productRow.find(".price-input").val(); // Adjust the index as per your table
        var qty = $productRow.find(".qty-input").val();

        // Validation for quantity
        var productQuantity = parseInt($productRow.find('td:eq(2)').text()); // Adjust the index as per your table
        if (qty <= 0 || qty > productQuantity) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid quantity',
                text: 'Requested Quantity is not available',
            });
            return;
        }

        // AJAX request to add the item to the cart
        $.ajax({
            type: "POST",
            url: "atc.php",
            data: {
                id: productId,
                name: productName,
                price: productPrice,
                qty: qty
            },
            success: function(response) {
                if (response.trim() === "success") {
                    Swal.fire({
                        icon: 'success',
                        title: 'Product added to the cart.',
                        timer: 1000,
                        showConfirmButton: false
                    });

                    $productRow.find(".qty-input").val('');
                    updateOrderList();
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Failed to add the product to the cart.'
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('Error occurred when adding to cart:', xhr.responseText);
            }
        });
    });

    // Function to update the order list
    function updateOrderList() {
        $.ajax({
            url: 'update_order_list.php',
            type: 'GET',
            dataType: 'html',
            success: function(data) {
                $('#order-list').html(data);
            },
            error: function() {
                console.log('Error fetching the order list.');
            }
        });
    }

    // Initially load the order list
    updateOrderList();
});

</script>

</body>

</html>