<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Cashier' || $_SESSION['type'] == 'Receptionist'  || $_SESSION['type'] == 'Manager')){
            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" 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" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css">
    <link rel="stylesheet" href="./quixlab/plugins/sweetalert2/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" >
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">


    

   
</head>

<!-- Print Styles -->
<style>
@media print {
    body * {
        visibility: hidden;
    }
    .modal-content, .modal-content * {
        visibility: visible;
    }
    .modal {
        position: absolute;
        left: 0;
        top: 0;
        margin: 0;
        padding: 0;
        overflow: visible !important;
    }
    .modal-dialog {
        max-width: 100%;
        width: auto !important;
    }
    .modal-header, .modal-footer {
        display: none !important;
    }
    .table {
        width: 100% !important;
    }
}
</style>
<body>

    <!--*******************
        Preloader start
    ********************-->
    <div id="preloader">
        <div class="loader">
            <svg class="circular" viewBox="25 25 50 50">
                <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="3" stroke-miterlimit="10" />
            </svg>
        </div>
    </div>
    <!--*******************
        Preloader end
    ********************-->

            
    
    <!--**********************************
        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">           
    <?php require 'navbar.php'; ?>
</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">Request/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 table-bordered items-table" id="productsInfo">
                                        <thead>
                                          <tr>
                                            <th>Product Name</th>
                                            <th>Qty Available</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">Request Details</h4>
                                      <div class="table-responsive">
                                              <table class="table table-striped table-bordered display table-sm">
                                            <thead>
                                                <tr>
                                                    <th>Request ID</th>
                                                    <th>Request By</th>
                                                    <th>Date</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody id="requests-table-body">
                                                <!-- Rows will be populated by JavaScript -->
                                            </tbody>
                                        </table>
                                      </div>
                                  </div>
                              </div>
                          </div>
                     </div>
                </div>
                
                 
                  
         <div class="container-fluid mt-3">
          
        
                </div>
                
                 
                  
                   
          
                
                
               
            <!-- #/ container -->
      
        <div class="modal fade" id="requestItemsModal" 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">Request 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">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Product Name</th>
                            <th>Quantity</th>
                            <th>Category</th>
                        </tr>
                    </thead>
                    <tbody id="request-items-table-body">
                        <!-- Rows will be populated by JavaScript -->
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
              <!-- Modal for displaying cart items -->

<!-- Start of Cart Modal -->
<div class="modal fade" id="cartModal" tabindex="-1" role="dialog" aria-labelledby="cartModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" 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">
    <div class="table-responsive">
    <table id="disposeSessionTable" class="table table-striped table-bordered">
        <thead class="thead-dark">
            <tr>
                <th>Product Name</th>
                <th>Quantity</th>
                <th>Category</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <!-- Session data will be dynamically inserted here -->
        </tbody>
    </table>
</div>

</div>
          <div class="modal-body">
    <div class="table-responsive">
        <table id="requestSessionTable" class="table table-striped table-bordered">
            <thead class="thead-dark">
                <tr>
                    <th>Product Name</th>
                    <th>Quantity</th>
                    <th>Category</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <!-- Request session data will be dynamically inserted here -->
            </tbody>
        </table>
    </div>
</div>
          
          
            <div class="modal-footer">
           <form id="receive-invoice">
    <div class="row">
        <!-- Column for the "Request By" input -->
        <div class="col-md-6">
            <div class="form-group">
                <label for="member_name">By</label>
                <input type="text" id="member_name" class="form-input" name="member_name" placeholder="Enter Your Name " required>
            </div>
        </div>

        <!-- Column for the buttons -->
        <div class="col-md-6">
            <div class="form-group">
                <button type="button" class="btn btn-warning mb-0" id="dispose-products-btn">Dispose Products</button>
                <button type="button" class="btn btn-secondary mb-0" id="request-products-btn">Request Products</button>
            </div>
        </div>
    </div>
</form> 
             </div>

            </div>
        </div>
    </div>
</div>
<!-- End of Cart Modal -->


<!-- Request Details Modal -->
<!-- Request Details Modal -->
<div class="modal fade" id="requestDetailsModal" tabindex="-1" role="dialog" aria-labelledby="requestDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="requestDetailsModalLabel">Request 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="requestDetailsBody">
                <!-- Content will be loaded 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="printRequestBtn">
                    <i class="fas fa-print"></i> Print
                </button>
            </div>
            
            <!-- Hidden print container (will only be used for printing) -->
            <div id="printContainer" style="display:none;"></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/plugins/common/common.min.js"></script>
    <script src="./quixlab/plugins/sweetalert2/dist/sweetalert2.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>

    <!-- Chartjs -->
    <script src="./quixlab/plugins/chart.js/Chart.bundle.min.js"></script>
    <!-- Circle progress -->
    <script src="./quixlab/plugins/circle-progress/circle-progress.min.js"></script>
    <!-- Datamap -->
    <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>
    <!-- Morrisjs -->
    <script src="./quixlab/plugins/raphael/raphael.min.js"></script>
    <script src="./quixlab/plugins/morris/morris.min.js"></script>
    <!-- Pignose Calender -->
    <script src="./quixlab/plugins/moment/moment.min.js"></script>
    <script src="./quixlab/plugins/pg-calendar/js/pignose.calendar.min.js"></script>
    <!-- ChartistJS -->
    <script src="./quixlab/plugins/chartist/js/chartist.min.js"></script>
    <script src="./quixlab/plugins/chartist-plugin-tooltips/js/chartist-plugin-tooltip.min.js"></script>
    <script src="./quixlab/js/dashboard/dashboard-1.js"></script>
    <script src="./quixlab/plugins/chart.js/Chart.bundle.min.js"></script>
    <script src="./quixlab/js/plugins-init/chartjs-init.js"></script>
    <!-- Datatables -->
    <script src="./quixlab/js/dashboard/dashboard-1.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://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>

    <script src="./quixlab/js/data-table/dataTables.buttons.min.js"></script>
    <script src="./quixlab/js/data-table/buttons.flash.min.js"></script>
    <script src="./quixlab/js/data-table/jszip.min.js"></script>
    <script src="./quixlab/js/data-table/pdfmake.min.js"></script>
    <script src="./quixlab/js/data-table/vfs_fonts.js"></script>
    <script src="./quixlab/js/data-table/buttons.html5.min.js"></script>
    <script src="./quixlab/js/data-table/buttons.print.min.js"></script>
    <script src="./quixlab/js/data-table/datatables-init.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
            <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.print.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>
 
 
 

<!--- Start of Pharmacy Code From Spot -->
<script>
$(document).ready(function() {
    fetchProductData();
    updateDisposeSessionTable();
    updateRequestSessionTable();

    function fetchProductData() {
        $.ajax({
            url: './database/available.kts.php',
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                var tableBody = $('#productsInfo tbody');
                tableBody.empty(); // Clear existing rows

                response.forEach(function(item) {
                    var row = `<tr>
                                  <td>${item.name}</td>
                                  <td class="quantity">${item.quantity_available}</td>
                                  <td>${item.category}</td>
                                  <td>
                                    <button type="button" class="btn btn-danger btn-sm dispose-item" data-id="${item.id}" data-name="${item.name}" data-category="${item.category}">
                                      <i class="fa fa-trash"></i> Dispose
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm request-item" data-id="${item.id}" data-name="${item.name}" data-category="${item.category}">
                                      <i class="fa fa-plus"></i> Request
                                    </button>
                                  </td>
                               </tr>`;
                    tableBody.append(row);
                });

                // Initialize DataTables
                $('#productsInfo').DataTable();

                // Attach click event handlers to the buttons
                $('.dispose-item').click(function() {
                    var itemId = $(this).data('id');
                    var itemName = $(this).data('name');
                    var itemCategory = $(this).data('category');
                    handleDispose(itemId, itemName, itemCategory);
                });

                $('.request-item').click(function() {
                    var itemId = $(this).data('id');
                    var itemName = $(this).data('name');
                    var itemCategory = $(this).data('category');
                    handleRequest(itemId, itemName, itemCategory);
                });
            },
            error: function(xhr, status, error) {
                console.error('Error fetching data:', error);
                toastr.error('Failed to load product data.');
            }
        });
    }

    function handleDispose(itemId, itemName, itemCategory) {
        var disposeData = {
            id: itemId,
            name: itemName,
            category: itemCategory,
            quantity: 1 // Default quantity
        };

        $.ajax({
            url: './database/add_to_dispose_session.kts.php', // PHP script to handle session updates
            method: 'POST',
            data: disposeData,
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    updateDisposeSessionTable();
                } else {
                    toastr.error('Failed to add item to session.');
                }
            },
            error: function() {
                toastr.error('Error occurred while adding item to session.');
            }
        });
    }

    function handleRequest(itemId, itemName, itemCategory) {
        var requestData = {
            id: itemId,
            name: itemName,
            category: itemCategory,
            quantity: 1 // Default quantity
        };

        $.ajax({
            url: './database/add_to_request_session.kts.php', // PHP script to handle session updates
            method: 'POST',
            data: requestData,
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    updateRequestSessionTable();
                } else {
                    toastr.error('Failed to add item to session.');
                }
            },
            error: function() {
                toastr.error('Error occurred while adding item to session.');
            }
        });
    }

    function updateDisposeSessionTable() {
        $.ajax({
            url: './database/fetch_disposal_data.kts.php', // PHP script to fetch session data
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                var tableBody = $('#disposeSessionTable tbody');
                tableBody.empty(); // Clear existing rows

                response.forEach(function(item) {
                    var row = `<tr>
                                  <td>${item.name}</td>
                                  <td class="quantity">
                                    <button type="button" class="btn btn-secondary btn-sm decrease-quantity" data-id="${item.id}" data-category="${item.category}" data-session="dispose">-</button>
                                    ${item.quantity}
                                    <button type="button" class="btn btn-secondary btn-sm increase-quantity" data-id="${item.id}" data-category="${item.category}" data-session="dispose">+</button>
                                  </td>
                                  <td>${item.category}</td>
                                  <td>
                                    <button type="button" class="btn btn-danger btn-sm remove-item" data-id="${item.id}" data-category="${item.category}" data-session="dispose">
                                      <i class="fa fa-trash"></i> Remove
                                    </button>
                                  </td>
                               </tr>`;
                    tableBody.append(row);
                });

                // Attach click events to dynamically added buttons
                $('.increase-quantity').off('click').on('click', function() {
                    var itemId = $(this).data('id');
                    var session = $(this).data('session');
                    updateQuantity(itemId, 1, session);
                });

                $('.decrease-quantity').off('click').on('click', function() {
                    var itemId = $(this).data('id');
                    var session = $(this).data('session');
                    updateQuantity(itemId, -1, session);
                });

                $('.remove-item').off('click').on('click', function() {
                    var itemId = $(this).data('id');
                    var session = $(this).data('session');
                    var itemCategory = $(this).data('category'); // Category of the item

                    removeItem(itemId, session, itemCategory);
                });
            },
            error: function(xhr, status, error) {
                console.error('Error fetching session data:', error);
                toastr.error('Failed to load session data.');
            }
        });
    }

    function updateRequestSessionTable() {
        $.ajax({
            url: './database/fetch_request_data.kts.php', // PHP script to fetch session data
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                var tableBody = $('#requestSessionTable tbody');
                tableBody.empty(); // Clear existing rows

                response.forEach(function(item) {
                    var row = `<tr>
                                  <td>${item.name}</td>
                                  <td class="quantity">
                                    <button type="button" class="btn btn-secondary btn-sm decrease-quantity" data-id="${item.id}" data-category="${item.category}" data-session="request">-</button>
                                    ${item.quantity}
                                    <button type="button" class="btn btn-secondary btn-sm increase-quantity" data-id="${item.id}" data-category="${item.category}" data-session="request">+</button>
                                  </td>
                                  <td>${item.category}</td>
                                  <td>
                                    <button type="button" class="btn btn-danger btn-sm remove-item" data-id="${item.id}" data-category="${item.category}" data-session="request">
                                      <i class="fa fa-trash"></i> Remove
                                    </button>
                                  </td>
                               </tr>`;
                    tableBody.append(row);
                });

                // Attach click events to dynamically added buttons
                $('.increase-quantity').off('click').on('click', function() {
                    var itemId = $(this).data('id');
                    var session = $(this).data('session');
                    updateQuantity(itemId, 1, session);
                });

                $('.decrease-quantity').off('click').on('click', function() {
                    var itemId = $(this).data('id');
                    var session = $(this).data('session');
                    updateQuantity(itemId, -1, session);
                });

                $('.remove-item').off('click').on('click', function() {
                    var itemId = $(this).data('id');
                    var session = $(this).data('session');
                    var itemCategory = $(this).data('category'); // Category of the item

                    removeItem(itemId, session, itemCategory);
                });
            },
            error: function(xhr, status, error) {
                console.error('Error fetching session data:', error);
                toastr.error('Failed to load session data.');
            }
        });
    }

   function updateQuantity(itemId, change, session) {
    $.ajax({
        url: './database/update_session_quantity.kts.php', // PHP script to handle quantity updates
        method: 'POST',
        data: {
            id: itemId,
            change: change,
            session: session
        },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                if (session === 'dispose') {
                    updateDisposeSessionTable();
                } else if (session === 'request') {
                    updateRequestSessionTable();
                }
            } else {
                toastr.error('Failed to update quantity.');
            }
        },
        error: function() {
            toastr.error('Error occurred while updating quantity.');
        }
    });
}


    function removeItem(itemId, session, category) {
        $.ajax({
            url: './database/remove_from_dispose_session.kts.php', // PHP script to handle item removal
            method: 'POST',
            data: { id: itemId, session: session, category: category },
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    if (session === 'dispose') {
                        updateDisposeSessionTable();
                    } else {
                        updateRequestSessionTable();
                    }
                } else {
                    toastr.error('Failed to remove item from session.');
                }
            },
            error: function() {
                toastr.error('Error occurred while removing item from session.');
            }
        });
    }
});
</script>

    
<script>
    // JavaScript code to fetch data and display it
    function fetchBusinessDetails() {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', './database/fetch_business.kts.php', true);
        xhr.onload = function() {
            if (this.status === 200) {
                var data = JSON.parse(this.responseText);
                
                console.log(data);  // Check if contact2 is present in the response
                
                // Check if no error
                if (!data.error) {
                    // Update the span elements with the fetched data
                    document.getElementById('shopname').innerText = data.shop_name || '';
                    document.getElementById('shopname1').innerText = data.shop_name || '';
                    document.getElementById('location').innerText = data.location || '';
                    document.getElementById('quote').innerText = data.quote || '';
                    document.getElementById('street').innerText = data.street || '';
                    document.getElementById('address').innerText = data.address || '';
                    document.getElementById('pin').innerText = data.pin || '';
                    document.getElementById('contact1').innerText = data.contact1 || '';
                    document.getElementById('contact2').innerText = data.contact2 || ''; // This should populate contact2
                } else {
                    console.error("Error: " + data.error);
                }
            } else {
                console.error("Failed to fetch data");
            }
        };
        xhr.send();
    }

    // Call the function as soon as the DOM is fully loaded
    document.addEventListener('DOMContentLoaded', fetchBusinessDetails);
</script>





<script>
    
$(document).ready(function() {
    // Initialize the page by fetching requests
    fetchAllRequests();

    // Button click event for Disposing Products
    $('#dispose-products-btn').on('click', function(e) {
        e.preventDefault();
        disposeOrRequestProducts('dispose');
    });

    // Button click event for Requesting Products
    $('#request-products-btn').on('click', function(e) {
        e.preventDefault();
        sendRequest();
    });

    // Function to fetch all requests and display them in the table
    function fetchAllRequests() {
        $.ajax({
            url: './database/fetch_requests.kts.php',
            method: 'GET',
            success: function(response) {
                try {
                    let requests = JSON.parse(response);
                    let tableBody = $('#requests-table-body');
                    tableBody.empty();
                    
                    if (requests.length === 0) {
                        tableBody.append('<tr><td colspan="5" class="text-center">No requests found</td></tr>');
                        return;
                    }

                    requests.forEach(request => {
                        let row = `<tr>
                            <td>${request.request_id || 'N/A'}</td>
                            <td>${request.request_by || 'N/A'}</td>
                            <td>${request.date ? new Date(request.date).toLocaleString() : 'N/A'}</td>
                            <td><span class="badge ${getStatusBadgeClass(request.status)}">${request.status || 'N/A'}</span></td>
                            <td>
                                <button class="btn btn-primary btn-sm view-request-details" data-id="${request.request_id}">
                                    <i class="fas fa-eye"></i> View
                                </button>
                                <button class="btn btn-info btn-sm print-request" data-id="${request.request_id}">
                                    <i class="fas fa-print"></i> Print
                                </button>
                            </td>
                        </tr>`;
                        tableBody.append(row);
                    });

                    // Add click event listeners for the new buttons
                    $('.view-request-details').on('click', function() {
                        let requestId = $(this).data('id');
                        fetchRequestDetails(requestId);
                    });

                    $('.print-request').on('click', function() {
                        let requestId = $(this).data('id');
                        printRequestDirect(requestId);
                    });

                } catch (error) {
                    console.error("Error parsing requests:", error);
                    showAlert('error', 'Error', 'Failed to load requests data.');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Fetch requests error:", textStatus, errorThrown);
                showAlert('error', 'Error', 'Failed to fetch requests.');
            }
        });
    }

    // Function to fetch and display request details in modal
    function fetchRequestDetails(requestId) {
        $.ajax({
            url: './database/fetch_request_items.kts.php',
            method: 'GET',
            data: { request_id: requestId },
            dataType: 'json',
            beforeSend: function() {
                $('#requestDetailsBody').html('<div class="text-center"><i class="fas fa-spinner fa-spin fa-3x"></i></div>');
            },
            success: function(response) {
                if (!response.success) {
                    $('#requestDetailsBody').html(`<div class="alert alert-danger">${response.message || 'Failed to load request details.'}</div>`);
                    return;
                }

                // Build the display HTML (for modal)
                let displayHtml = buildRequestDetailsHtml(response, false);
                $('#requestDetailsBody').html(displayHtml);
                
                // Build the print HTML (thermal printer optimized)
                let printHtml = buildRequestDetailsHtml(response, true);
                $('#printContainer').html(printHtml);
                
                // Set up print button
                $('#printRequestBtn').off('click').on('click', function() {
                    printRequest();
                });
                
                // Show the modal
                $('#requestDetailsModal').modal('show');
            },
            error: function(jqXHR) {
                let errorMessage = "Error loading request details.";
                try {
                    const response = JSON.parse(jqXHR.responseText);
                    if (response.message) errorMessage = response.message;
                } catch (e) {}
                $('#requestDetailsBody').html(`<div class="alert alert-danger">${errorMessage}</div>`);
            }
        });
    }

    // Function to build HTML for both display and print
    function buildRequestDetailsHtml(response, isForPrint) {
        // Common header for both display and print
        let html = `
            <div class="${isForPrint ? 'print-header' : 'request-header mb-4'}">
                <div class="${isForPrint ? 'text-center' : 'd-flex justify-content-between align-items-center'}">
                    <h${isForPrint ? '2' : '4'}>Request #${response.request.request_id}</h${isForPrint ? '2' : '4'}>
                </div>
                <div class="row mt-3">
                    <div class="col-md-6">
                        <p><strong>Requested by:</strong> ${response.request.user_name}</p>
                        <p><strong>Date:</strong> ${new Date(response.request.request_date).toLocaleString()}</p>
                    </div>
                    <div class="col-md-6">
                        <p><strong>Status:</strong> <span class="badge ${getStatusBadgeClass(response.request.status)}">${response.request.status}</span></p>
                    </div>
                </div>
            </div>
            <div class="${isForPrint ? 'print-table' : 'table-responsive'}">
                <table class="${isForPrint ? 'print-table' : 'table table-bordered'}">
                    <thead class="${isForPrint ? '' : 'thead-dark'}">
                        <tr>
                            <th>#</th>
                            <th>Product Name</th>
                            <th>Qty</th>
                            <th>Category</th>
                        </tr>
                    </thead>
                    <tbody>`;
        
        // Add items
        response.items.forEach((item, index) => {
            html += `
                <tr>
                    <td>${index + 1}</td>
                    <td>${item.product_name}</td>
                    <td>${item.quantity}</td>
                    <td>${item.category}</td>
                </tr>`;
        });
        
        // Close tags
        html += `
                    </tbody>
                </table>
            </div>`;
        
        // Add print-specific footer if needed
        if (isForPrint) {
            html += `
            <div class="print-footer">
                <p>Printed on: ${new Date().toLocaleString()}</p>
            </div>`;
        }
        
        return html;
    }

    // Print function for direct printing from table (without opening modal)
    function printRequestDirect(requestId) {
        $.ajax({
            url: './database/fetch_request_items.kts.php',
            method: 'GET',
            data: { request_id: requestId },
            dataType: 'json',
            success: function(response) {
                if (!response.success) {
                    showAlert('error', 'Error', response.message || 'Failed to load request details for printing.');
                    return;
                }

                // Build the print HTML
                let printHtml = buildRequestDetailsHtml(response, true);
                printThermal(printHtml, `Request #${requestId}`);
            },
            error: function(jqXHR) {
                let errorMessage = "Error loading request details for printing.";
                try {
                    const response = JSON.parse(jqXHR.responseText);
                    if (response.message) errorMessage = response.message;
                } catch (e) {}
                showAlert('error', 'Error', errorMessage);
            }
        });
    }

  function printThermal(printContent, title) {
    // Create a print window
    let printWindow = window.open('', '_blank', 'width=320,height=600');

    // Thermal printer friendly styles
    let styles = `
        <style>
            body {
                font-family: Arial, sans-serif;
                font-size: 12px;
                margin: 0;
                padding: 5px;
            }
            .print-header {
                text-align: center;
                margin-bottom: 10px;
                border-bottom: 1px dashed #000;
                padding-bottom: 10px;
            }
            .print-header h2 {
                font-size: 16px;
                margin: 5px 0;
            }
            .print-table {
                width: 100%;
                border-collapse: collapse;
                margin: 10px 0;
            }
            .print-table th {
                font-weight: bold;
                border-bottom: 1px solid #000;
                padding: 3px 0;
                text-align: left;
            }
            .print-table td {
                padding: 2px 0;
                border-bottom: 1px dashed #ddd;
            }
            .print-footer {
                margin-top: 10px;
                font-size: 10px;
                text-align: center;
                border-top: 1px dashed #000;
                padding-top: 5px;
            }
            .badge {
                display: inline-block;
                padding: 0.15em 0.3em;
                font-size: 10px;
                font-weight: bold;
                line-height: 1;
                text-align: center;
                white-space: nowrap;
                vertical-align: baseline;
                border-radius: 0.15rem;
            }
            .badge-warning { background-color: #ffc107; color: #212529; }
            .badge-success { background-color: #28a745; color: white; }
            .badge-danger { background-color: #dc3545; color: white; }
            .badge-info { background-color: #17a2b8; color: white; }
            .badge-secondary { background-color: #6c757d; color: white; }
            @media print {
                body { margin: 0; padding: 0; }
                .print-header { margin-top: 0; }
            }
        </style>
    `;

    // Write to print window
    printWindow.document.open();
    printWindow.document.write(`
        <html>
            <head>
                <title>${title}</title>
                ${styles}
            </head>
            <body>
                ${printContent}
            </body>
        </html>
    `);
    printWindow.document.close();

    // Wait for DOM to be ready before printing
    printWindow.onload = function () {
        setTimeout(function () {
            printWindow.print();
            printWindow.close();
        }, 200);
    };
}


    // Print function for modal (uses pre-loaded print content)
    function printRequest() {
        let printContent = $('#printContainer').html();
        let title = $('#requestDetailsModalLabel').text().replace('Request Details', '').trim();
        printThermal(printContent, title);
    }

    // Function to handle Request Products AJAX request
    function sendRequest() {
        const memberName = $('#member_name').val().trim();
        if (!memberName) {
            showAlert('warning', 'Warning!', 'Please enter your name before requesting products.');
            return;
        }

        let requestData = {
            action: 'request',
            member_name: memberName
        };

        $.ajax({
            url: './database/process_request.kts.php',
            method: 'POST',
            data: requestData,
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.success) {
                        showAlert('success', 'Success!', result.message);
                        fetchAllRequests();
                        $('#member_name').val('');
                    } else {
                        showAlert('error', 'Error!', result.message);
                    }
                } catch (e) {
                    console.error("Error parsing JSON response:", response);
                    showAlert('error', 'Error!', 'Unexpected response format.');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("AJAX Error:", textStatus, errorThrown);
                showAlert('error', 'Error!', 'There was an error processing your request.');
            }
        });
    }

    // Function to handle Dispose Products AJAX request
    function disposeOrRequestProducts(actionType) {
        const memberName = $('#member_name').val().trim();
        if (!memberName) {
            showAlert('warning', 'Warning!', 'Please enter your name before disposing products.');
            return;
        }

        $.ajax({
            url: './database/update_and_insert_disposal_data.kts.php',
            method: 'POST',
            data: {
                member_name: memberName,
                action: actionType,
                dispose_items: <?php echo json_encode($_SESSION['dispose_items'] ?? []); ?>
            },
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.status === 'success') {
                        showAlert('success', 'Success', 'Products have been successfully processed.');
                        fetchAllRequests();
                        $('#member_name').val('');
                    } else {
                        showAlert('error', 'Error', result.message || 'Failed to process products.');
                    }
                } catch (error) {
                    console.error("Error parsing JSON response:", response);
                    showAlert('error', 'Error', 'Unexpected response format.');
                }
            },
            error: function(xhr, status, error) {
                console.error("AJAX Error:", status, error);
                showAlert('error', 'Error', 'An error occurred while processing products.');
            }
        });
    }

    // Helper function to show alerts
    function showAlert(icon, title, text) {
        Swal.fire({
            icon: icon,
            title: title,
            text: text,
            confirmButtonText: 'OK'
        });
    }

    // Helper function to get Bootstrap badge class based on status
    function getStatusBadgeClass(status) {
        switch ((status || '').toLowerCase()) {
            case 'pending': return 'badge-warning';
            case 'approved': return 'badge-success';
            case 'rejected': return 'badge-danger';
            case 'completed': return 'badge-info';
            default: return 'badge-secondary';
        }
    }
});
</script>
</body>

</html>