<?php
     session_start();
      include 'database/shikanisha.kts.php';
        if(!($_SESSION['type'] == 'Manager' || $_SESSION['type'] == 'Receptionist' || $_SESSION['type'] == 'Cashier')){
            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="image/png" sizes="16x16" href="./quixlab/images/favicon.png">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    <!-- FullCalendar CSS -->
 <link rel="stylesheet" href="./quixlab//plugins/fullcalendar/css/fullcalendar.min.css">
    <!-- Pignose Calendar CSS -->
    <link href="./quixlab/plugins/pg-calendar/css/pignose.calendar.min.css" rel="stylesheet">

    <!-- Chartist CSS -->
    <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">

    <!-- DataTables with Buttons CSS -->
    <link href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="./quixlab/css/buttons.bootstrap.min.css" rel="stylesheet" />

    <!-- SweetAlert2 CSS -->
    <link href="./quixlab/plugins/sweetalert2/dist/sweetalert2.min.css" rel="stylesheet">

    <!-- International Telephone Input CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/css/intlTelInput.min.css">

    <!-- Custom Stylesheet -->
    <link href="./quixlab/css/design.css" rel="stylesheet">



<style>
body {
    background-image: url("./imgs/accomodation.jpg");
    background-size: cover;
    background-repeat: repeat; /* Allow repeating */
    background-position: center;
}
.circle {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: red; /* Adjust the color as needed */
    position: absolute;
    top: 5px; /* Adjust the position as needed */
    right: 5px; /* Adjust the position as needed */
}
  .booked-checked-in{
     color: black;
  }
 
  </style>
    
    
     <style>
        .tabz {
background-color: rgba(139, 69, 19, 0.5); /* Brown color with 0.5 opacity */
        }
       .card.tabz {
  color: honeydew;
}
       

    </style>
</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 tabz">

        <!--**********************************
            Nav header start
        ***********************************-->
        <div class="nav-header tabz">
            <div class="brand-logo tabz">
              
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
        <div class="header tabz">    
            <div class="header-content clearfix tabz">
                
                <div class="nav-control tabz">
                    <div class="hamburger">
                        <span class="toggle-icon"><i class="icon-menu"></i></span>
                    </div>
                </div>
               
            </div>
        </div>
        <!--**********************************
            Nav header end
        ***********************************-->

        <!--**********************************
            Header start
        ***********************************-->
    <?php


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

$cashierLinks = array(
    "orders.php", 
    "table.php", 
    "payments.php"
);

$receptionistLinks = array(
    "orders.php", 
    "payments.php", 
    "accomodation.php", 
    "table.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 "Receptionist":
            $links = $receptionistLinks;
            break;
        default:
            $links = array();
            break;
    }
} else {
    // Redirect user to login page if they are not logged in
    header("Location: login.php");
    exit();
}

?>

<div class="nk-sidebar tabz">           
    <div class="nk-nav-scroll tabz">
        <ul class="metismenu  tabz" id="menu">
            <li class="nav-label tabz">Dashboard</li>
            <li>
                <a class="has-arrow tabz" href="javascript:void()" aria-expanded="false">
                    <i class="icon-speedometer menu-icon"></i><span class="nav-text">Dashboard</span>
                </a>
                <ul aria-expanded="false" class="tabz">
                    <li class="tabz"><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 class="tabz"><a href="' . $link . '"><i class="icon-menu menu-icon"></i><span class="nav-text">' . $linkText . '</span></a></li>';
}

            ?>
            <li class="tabz">
                <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-4 col-sm-6">
                      <div class="card gradient-10" 
data-toggle="modal" data-target="#addRoomModal">
                        <div class="card-body">
                          <h3 class="card-title text-white"></h3>
                          <div class="d-inline-block">
                            <h2 class="text-white">Add Room</h2>
                            <p class="text-white mb-0"></p>
                          </div>
                          <span class="float-right display-5 opacity-5"><i class="fa fa-shopping-cart"></i></span>
                        </div>
                      </div>
                    </div>

                   
                    <div class="col-lg-4 col-sm-6" >
                        <a href="checked-in.php" class="card gradient-10">
    <div class="card-body">
        <h3 class="card-title text-white"></h3>
        <div class="d-inline-block">
            <h2 class="text-white">Checked In Rooms</h2>
            <p class="text-white mb-0"></p>
        </div>
        <span class="float-right display-5 opacity-5"><i class="fa fa-users"></i></span>
    </div>
</a>

                    </div>
              <div class="col-lg-4 col-sm-6" >
               <a href="roombills.php" class="card gradient-10">
                  <div class="card-body">
                      <h3 class="card-title text-white"></h3>
                      <div class="d-inline-block">
                          <h2 class="text-white">Room Bills</h2>
                          <p class="text-white mb-0"></p>
                      </div>
                      <span class="float-right display-5 opacity-5"><i class="fa fa-money"></i></span>
                  </div>
                </a>
             </div>
                 <!-- end of row -->
                  </div>
               
            
    <div class="row">
    
    <div class="col-lg-12">
        <div class="card tabz">
            <div class="card-body">
                <div class="active-member">
                    <div class="table-responsive">
                      <table id="roomTable" class="table table-hover table-sm display">
        <thead>
            <tr>
                <th>Room Name</th>
                <th>Description</th>
                <th>Price</th>
                <th>Check-In Date</th>
                <th>Check-Out Date</th>
                <th>Availability</th>
                <th>Action</th>
                <th>View Calendar</th>
            </tr>
        </thead>
        <tbody>
            <!-- DataTable rows will be dynamically populated -->
                        </tbody>
                      </table>
                </div>
            </div>
        </div>
    </div>
</div>
              </div>
    
     <div class="row">
    <div class="col-lg-12">
     <div class="card tabz">
                                      <div class="card-body">
                                          <h4 class="card-title">Bookings Details</h4>
                                          <div class="table-responsive">
                                              <table class="table table-striped" id="bookings">
                                                 <thead>
            <tr>
                <th>Booking ID</th>
                <th>Room Name</th>
                <th>Receptionist</th>
                <th>Client</th>
                <th>Cost</th>
                <th>Check In Date</th>
                <th>Check Out Date</th>
                <th>Check In</th>
                <th>Check Out Date</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
                                        </div>
       </div>    
      </div>
       </div> 
              </div>
                          
                <!-- End Of Send To Shop Modal -->
                
                
                
<!-- The Accomodation modal -->
<div class="modal" id="bookRoomModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Book Room</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
           

            <!-- Modal body -->
            <div class="modal-body">
                <form id="bookRoomForm">
                    <input type="hidden" name="roomId" id="roomId" value="">
                    <div class="form-group">
                        <label for="guestName">Guest Name:</label>
                        <input type="text" class="form-control" id="guestName" name="guestName" required>
                    </div>
                   <div class="form-group">
                      <label for="checkInDate">Check In:</label>
                      <input type="datetime-local" class="form-control" id="checkInDate" name="checkInDate" required>
                  </div>
                  <div class="form-group">
                      <label for="checkOutDate">Check Out:</label>
                      <input type="datetime-local" class="form-control" id="checkOutDate" name="checkOutDate" required>
                  </div>

                    
                    <div class="form-group">
                        <label for="occupants">Number of Occupants:</label>
                        <select class="form-control" id="occupants" name="occupants" required>
                            <option value="">-- Select --</option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                        </select>
                    </div>
                   
<button type="submit" class="btn btn-primary">Book</button>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
    <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="redirectPage()">Close</button>
</div>
</div>
</div>

</div>

                
     <div class="modal fade tabz" id="addRoomModal" tabindex="-1" role="dialog" aria-labelledby="addRoomModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addRoomModalLabel">Add Room</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
     <form id="addRoomForm" method="POST" enctype="multipart/form-data">
    <div class="modal-body">
        <div class="form-group">
            <label for="roomName">Room Name:</label>
            <input type="text" class="form-control" id="roomName" name="roomName" required>
        </div>
        <div class="form-group">
            <label for="description">Description:</label>
            <input type="text" class="form-control" id="description" name="description" required>
        </div>
        <div class="form-group">
            <label for="price">Price:</label>
            <input type="number" class="form-control" id="price" name="price" required>
        </div>
        <div class="form-group">
            <style>
                #preview-image {
                    max-width: 100px;
                    max-height: 100px;
                }
            </style>
            <img src="./imgs/upload.svg" class="upload-icon" id="preview-image" />
            <input type="file" name="image" class="upload-input" onchange="previewFile(event)" />
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Add Room</button>
    </div>
</form>

    </div>
  </div>
</div>
           
           <div class="modal fade" id="checkInModal" 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">Check In Modal</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="checkinForm"> 
                  <div class="form-group">
                      <label for="bookingIdInput">Booking ID:</label>
                      <input type="text" class="form-control" id="bookingIdInput" name="bookid" readonly>
                  </div>
                  <div class="form-group">
                      <label for="phone">Phone Number:</label>
                      <input type="tel" class="form-control" id="phone" name="phone" required>
                  </div>
                  <div class="form-group">
                        <label for="bookingIdInput">Client Name:</label>
                        <input type="text" class="form-control" id="cname" name="cname" required>
                  </div>
                  <div class="form-group">
                        <label for="bookingIdInput">Passport/ID Number:</label>
                        <input type="text" class="form-control" id="idno" name="idno" required>
                  </div>
                  
                  <div class="form-group">
                        <label for="bookingIdInput">Payment Amount:</label>
                        <input type="number" class="form-control" id="payamount" name="payamount" required>
                  </div>
                  <div class="form-group">
                      <label for="checkOutDate">Check Out:</label>
                      <input type="datetime-local" class="form-control" id="cCutDate" name="COutDate" required>
                  </div>
                   <div class="basic-form">
                                                          <label>Payment Mode</label>
                                                          <select class="custom-select browser-default input-rounded" id="paymethod" name="paymethod" required>
                                                          <option value="">Please select</option>
                                                          <option value="cash">Cash</option>
                                                          <option value="till">Till</option>
                                                          <option value="merchant"> Merchant</option>
                                                        </select>
                                                        </div>
                   <div class="modal-footer">
    <button type="button" class="btn btn-secondary btn-rounded" data-dismiss="modal">Close</button>
    <button type="button" id="checkInButton" class="btn btn-success btn-rounded">Check In</button>
  </div>
</form>

                  </div>
                  
          </div>
    </div>
</div>

     
              
            </div>
            
<!-- Add Room Modal -->
<!-- Modal -->

     <!-- Include jQuery -->

<!-- Include libphonenumber -->
 <div class="modal fade" id="calendarModal" tabindex="-1" role="dialog" aria-labelledby="calendarModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="calendarModalLabel">Room Calendar</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 id="calendar"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

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

    <!--**********************************
        Scripts
***********************************-->
  
    <!--telphone-->
   <!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

<!-- Bootstrap -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="./quixlab/plugins/jqueryui/js/jquery-ui.min.js"></script>
<script src="./quixlab/plugins/moment/moment.min.js"></script>
<script src="./quixlab/plugins/fullcalendar/js/fullcalendar.min.js"></script>
<!-- FullCalendar -->

<!-- Other scripts ... -->
<script src="./quixlab/plugins/sweetalert2/dist/sweetalert2.min.js"></script>
<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>
<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>
<!-- ... -->

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<script src="./quixlab/plugins/tables/js/dataTables.bootstrap4.min.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>

<!-- Other scripts ... -->
<script src="./quixlab/js/plugins-init/chartjs-init.js"></script>
<script src="./quixlab/js/dashboard/dashboard-1.js"></script>
<!-- Include intl-tel-input script with bundled libphonenumber -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/intlTelInput-jquery.min.js"></script>


<script>
    $(document).ready(function () {
        $("#phone").intlTelInput({
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.12/js/utils.js",
        });

        // Set default country to Kenya
        var intlNumber = $("#phone").intlTelInput("getNumber");
        if (!intlNumber) {
            $("#phone").intlTelInput("setCountry", "ke");
        }
    });
</script>
<script>
  $(document).ready(function() {
    $('#bookRoomForm').submit(function(event) {
      event.preventDefault();
      $.ajax({
        url: 'database/bookroom.kts.php',
        type: 'POST',
        data: $('#bookRoomForm').serialize(),
        dataType: 'json', // Specify that the expected response is JSON
        success: function(response) {
          // Check the status property in the JSON response
          if (response.status === 'success') {
            // if booking is successful, hide the modal and show success message
            $('#bookRoomModal').modal('hide');
            Swal.fire({
              title: 'Room booked successfully!',
              type: 'success',
              confirmButtonText: 'OK'
            }).then(function() {
              // Reload the current page
              location.reload();
            });
          } else {
            // if booking is not successful, show error message
            Swal.fire({
              title: 'Error!',
              text: response.message, // Access the message property in the JSON response
              type: 'error',
              confirmButtonText: 'OK'
            });
          }
        }
      });
    });
  });
</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();
  })    
 </script>
 

 <script>

    $(document).ready(function(){
        $('#search_text').keyup(function(){
            var txt = $(this).val();
            if (txt != ''){
                $.ajax({
                    url:"./database/fetch.kts.php",
                    method: "post",
                    data:{search:txt},
                    dataType:"text",
                    success:function(data)
                    {
                        $('#result').html(data);
                    }
                });
            }
            else{
                $('#result').html('');
            }
		
		});
    });
		

    
</script>
  <script>
   function redirectToPage(url) {
    window.location.href = url;
    }
  </script>  
      

<script>
function redirectPage() {
  window.location.href = 'database/accotrans.kts.php';
}
</script>

<script>
    function previewFile(event) {
        var input = event.target;
        var preview = document.getElementById('preview-image');

        var file = input.files[0];
        var reader = new FileReader();

        reader.onload = function () {
            var img = new Image();

            img.onload = function () {
                // Set the width and height of the preview image
                var maxWidth = 100;
                var maxHeight = 100;

                // Calculate the aspect ratio to maintain proportions
                var aspectRatio = img.width / img.height;

                if (img.width > maxWidth || img.height > maxHeight) {
                    if (img.width > img.height) {
                        img.width = maxWidth;
                        img.height = maxWidth / aspectRatio;
                    } else {
                        img.height = maxHeight;
                        img.width = maxHeight * aspectRatio;
                    }
                }

                preview.src = img.src;
            };

            img.src = reader.result;
        };

        reader.readAsDataURL(file);
    }
</script>

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

            var formData = new FormData(this);

            $.ajax({
                type: 'POST',
                url: 'database/addroom.kts.php',
                data: formData,
                processData: false,  // Prevent jQuery from automatically processing data
                contentType: false,  // Prevent jQuery from automatically setting content type
                success: function (response) {
                    // Parse the JSON response
                    var responseData = JSON.parse(response);

                    // Display SweetAlert based on the response status
                    if (responseData.status === 'success') {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: responseData.message,
                        }).then(function () {
                            // Redirect to another page
                            window.location.replace("accomodation.php");
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: responseData.message,
                        });
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        });
    });
</script>
    <script>
        $(document).ready(function () {
            $('#bookings').DataTable({
                "ajax": {
                    "url": "./database/getbookings.kts.php",
                    "dataSrc": "data"
                },
                "columns": [
                    { "data": "booking_id" },
                    { "data": "room_name" },
                    { "data": "receptionist" },
                    { "data": "client" },
                    { "data": "cost" },
                    { "data": "check_in_date" },
                    { "data": "check_out_date" },
                    {
                        "data": null,
                        "render": function (data, type, row) {
                            return '<button type="button" class="btn btn-rounded btn-success" onclick="openCheckInModal(' + row.booking_id + ')">Check In</button>';
                        }
                    },

                    {
                        "data": null,
                        "render": function (data, type, row) {
                            if (row.status === 'Booked' && <?php echo isset($_SESSION['type']) && $_SESSION['type'] == 'Manager' ? 'true' : 'false'; ?>) {
                                return '<button type="button" class="btn btn-rounded btn-danger" onclick="removeBooking(' + row.booking_id + ')">Delete</button>';
                            } else {
                                return '';
                            }
                        }
                    }
                ]
            });
        });

        // Click functions
        function openCheckInModal(bookingId) {
            // Set the booking ID in the modal input
            document.getElementById('bookingIdInput').value = bookingId;
            // Open the modal
            $('#checkInModal').modal('show');
        }

        function removeBooking(bookingId) {
            console.log('Delete clicked, Booking ID: ' + bookingId);
            // Add your logic here for Delete
        }
    </script>
<script>
$(document).ready(function () {
    // Add an event listener for form submission
    $('#checkInButton').on('click', function (event) {
        event.preventDefault(); // Prevent the default form submission behavior

        // Serialize form data
        var formData = new FormData($('#checkinForm')[0]);

        // Make an AJAX request
        $.ajax({
            url: './database/checkin.kts.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                // Check if the operation was successful
                if (data.status === 'success') {
                    // Show SweetAlert for success
                    Swal.fire({
                        icon: 'success',
                        title: 'Check In Successful',
                        text: data.message,
                        onClose: () => {
                            // Redirect to accprint.php after SweetAlert is closed
                            window.location.href = 'accprint.php';
                        }
                    });
                } else {
                    // Show SweetAlert for error
                    Swal.fire({
                        icon: 'error',
                        title: 'Check In Failed',
                        text: data.message,
                    });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // Show SweetAlert for general error
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Something went wrong!',
                });
                console.error('AJAX Error:', textStatus, errorThrown);
            }
        });
    });
});
</script>

<script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#roomTable').DataTable({
                "ajax": "./database/getrooms.kts.php", // URL to server-side script
                "columns": [
                    { "data": "room_name" },
                    { "data": "description" },
                    { "data": "price" },
                    { 
                        "data": "check_in_date",
                        "render": function(data, type, row) {
                            return '<input type="datetime-local" class="form-control" id="checkInDate' + row.room_id + '" onchange="checkAvailability(' + row.room_id + ')">';
                        }
                    },
                    { 
                        "data": "check_out_date",
                        "render": function(data, type, row) {
                            return '<input type="datetime-local" class="form-control" id="checkOutDate' + row.room_id + '" onchange="checkAvailability(' + row.room_id + ')">';
                        }
                    },
                    { "data": null,
                        "render": function(data, type, row) {
                            return '<span id="availabilityStatus' + row.room_id + '"></span>';
                        }
                    },
                    {
                        "data": null,
                        "render": function(data, type, row) {
                            return '<button type="button" class="btn btn-rounded btn-primary" onclick="openRoomModal(' + row.room_id + ')">Book Room!</button>';
                        }
                    },
                    { 
                        "data": null,
                        "render": function(data, type, row) {
                            return '<button type="button" class="btn btn-rounded btn-secondary btn-calendar" onclick="openCalendarModal(' + row.room_id + ')">View Bookings</button>';
                        }
                    }
                ]
            });
        });

        function openRoomModal(roomId) {
        // Set the selected room ID in the hidden input field
        $('#roomId').val(roomId);
        // Open the Book Room Modal
        $('#bookRoomModal').modal('show');
    }

          function openRoomModal(roomId) {
        // Set the selected room ID in the hidden input field
        $('#roomId').val(roomId);
        // Open the Book Room Modal
        $('#bookRoomModal').modal('show');
    }

    function redirectPage() {
        // Your function to redirect to another page
        console.log('Redirecting to another page...');
    }
   function checkAvailability(roomId) {
            // Get selected dates
            var checkInDate = $('#checkInDate' + roomId).val();
            var checkOutDate = $('#checkOutDate' + roomId).val();

            // Check if both dates are selected
            if (checkInDate && checkOutDate) {
                // Make AJAX request to check availability
                $.ajax({
                    url: './database/checkavailability.kts.php',
                    type: 'POST',
                    data: {
                        'roomId': roomId,
                        'checkInDate': checkInDate,
                        'checkOutDate': checkOutDate,
                    },
                success: function(response) {
    // Update the availability status and badge class in the corresponding span
    var availabilityStatus = $('#availabilityStatus' + roomId);
    var labelClass = (response === 'Available') ? 'label-success' : 'label-danger';
    
    // Build the Bootstrap pill label HTML
    var labelHtml = '<div class="bootstrap-label"><span class="label label-pill ' + labelClass + '">' + response + '</span></div>';
    
    // Set the HTML to the availabilityStatus element
    availabilityStatus.html(labelHtml);
},

                    error: function(xhr, status, error) {
                        console.error('Error checking availability:', error);
                    }
                });
            }
        }
  window.CalendarApp = {
    init: function() {
        // Your initialization code here
        console.log('CalendarApp initialized');
    }
};
  function openCalendarModal(roomId) {
            // Fetch booked and checked-in dates for the room
            $.ajax({
                url: './database/getalldates.kts.php',
                type: 'POST',
                data: {
                    'roomId': roomId,
                },
                success: function(response) {
                    // Render FullCalendar for the selected room using the fetched data
                    renderCalendar(response, roomId);
                    // Open the modal after rendering the calendar
                    $('#calendarModal').modal('show');
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching all dates:', error);
                }
            });
        }
  
function renderCalendar(allDates, roomId) {
    try {
        var eventsData = JSON.parse(allDates);

        // Check if eventsData is an array
        if (!Array.isArray(eventsData)) {
            throw new Error('Parsed data is not an array.');
        }

        // Check if each event has required properties
        if (!eventsData.every(event => event && event.start)) {
            throw new Error('Invalid event structure in the data.');
        }

        // Extract the dates to be highlighted
   // Extract the dates to be highlighted
var highlightedDates = eventsData
    .filter(event => event.isBookedOrCheckedIn)
    .map(event => {
        // Extracting only the date part
        var datePart = event.start.split(' ')[0];
        // Add black color to the text
        return { ...event, datePart, textColor: 'black' };
    });

// Destroy the existing calendar (if any)
$('#calendar').fullCalendar('destroy');

// Initialize FullCalendar
// Initialize FullCalendar
$('#calendar').fullCalendar({
    initialView: 'dayGridMonth',
    events: eventsData.map(event => ({ ...event, textColor: 'black' })), // Set black text color for all events
    dayRender: function (date, cell) {
        // Check if the date should be highlighted
        var formattedDate = date.format('YYYY-MM-DD');
        if (highlightedDates.some(event => event.datePart === formattedDate)) {
            cell.addClass('booked-checked-in');
        }
    }
});


// Show the modal after rendering the calendar
$('#calendarModal').modal('show');

    } catch (error) {
        console.error('Error parsing or rendering calendar data:', error);
    }
}






        // Ensure that the calendar is initialized after fetching data
        $(document).ready(function() {
            // Initialize the calendar when the document is ready
            if (typeof window.CalendarApp !== 'undefined' && window.CalendarApp !== null) {
                window.CalendarApp.init();
            } else {
                console.error('window.CalendarApp is not defined or null. Check your script dependencies.');
            }
        });



    </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('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>


</body>

</html>