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


?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Jacyjoka Apartment</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 href="./quixlab/plugins/tables/css/datatable/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="./quixlab/css/buttons.bootstrap.min.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
 body {
            background-image: url("./imgs/accomodation.jpg");
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
            
        }
  </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-12 col-sm-12">
                       <a href="accomodation.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">Book 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>
                      </a>
                    </div>

                   
                  
                  </div>
               
            
   
    
     <div class="row">
    <div class="col-lg-12">
     <div class="card tabz">
                                      <div class="card-body">
                                          <h2 class="card-title">Occupied Rooms</h2>
                                          <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>Action</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" method="post">
                    <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>
            
<!-- Add Room Modal -->


                    

            <!-- #/ 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></p>
            </div>
        </div>
        <!--**********************************
            Footer end
        ***********************************-->
    </div>
    <!--**********************************
        Main wrapper end
    ***********************************-->

    <!--**********************************
        Scripts
***********************************-->
    <script src="./quixlab/plugins/common/common.min.js"></script>
    <script src="./quixlab/js/custom.min.js"></script>
    <script src="./quixlab/js/settings.js"></script>
    <script src="./quixlab/js/gleek.js"></script>
    <script src="./quixlab/js/styleSwitcher.js"></script>

    <!-- 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="./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>

    
    <!--Bookroommodal-->
    
<script>
   

    $(document).ready(function() {
        $('#bookRoomForm').submit(function(event) {
            event.preventDefault();
            $.ajax({
                url: 'database/bookroom.kts.php',
                type: 'POST',
                data: $('#bookRoomForm').serialize(),
                success: function(response) {
                    // if booking is successful, hide the modal and show success message
                    if(response == 'success') {
                        $('#bookRoomModal').modal('hide');
                        alert('Room booked successfully!');
                    } else {
                        // if booking is not successful, show error message
                        alert(response);
                    }
                }
            });
        });
    });
</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("accommodation.php");
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: responseData.message,
                        });
                    }
                },
                error: function (error) {
                    console.log(error);
                }
            });
        });
    });
</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": null,
                    "render": function(data, type, row) {
                        return '<button type="button" class="btn btn-rounded btn-primary" onclick="openRoomModal(' + row.room_id + ')">Book Room!</button>';
                    }
                }
            ]
        });

        // Initialize the Book Room Form
        $('#bookRoomForm').submit(function(e) {
            e.preventDefault();
            // Handle the form submission (you can implement AJAX here to send the booking data to the server)
            // For now, just log the form data to the console
            console.log('Form submitted:', $(this).serialize());
            // Close the modal (replace this with your modal closing logic)
            $('#bookRoomModal').modal('hide');
        });
    });

    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...');
    }
</script>

<script>
   $(document).ready(function () {
    $('#bookings').DataTable({
        "ajax": {
            "url": "./database/checkedin.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-info" onclick="checkOut(' + row.booking_id + ')">Check Out</button>';
                }
            }
        ]
    });
});

/// Click functions
function checkOut(bookingId) {
    console.log('Check Out clicked, Booking ID: ' + bookingId);

    // Confirm the checkout action using SweetAlert
    Swal.fire({
        title: 'Are you sure?',
        text: 'You are about to check out.Kindly ensure client has no existing accomodation bill. This action cannot be undone!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, check out!'
    }).then((result) => {
        if (result.isConfirmed) {
            // AJAX request to checkout.kts.php
           $.ajax({
    url: 'database/checkout.kts.php',
    type: 'POST',
    data: { booking_id: bookingId }, // Pass the booking_id to the PHP script
    dataType: 'json', // Specify that you expect a JSON response
    success: function(response) {
        // Handle the response from the server
        console.log(response);

        // Handle the response with SweetAlert
        if (response.status === 'success') {
            // Successful checkout
            Swal.fire({
                title: 'Check Out successful!',
                text: response.message, // Display server message if available
                icon: 'success',
                confirmButtonText: 'OK'
            }).then(() => {
                // You can add more logic here if needed
            });
        } else {
            // Checkout failed
            Swal.fire({
                title: 'Check Out failed',
                text: response.message, // Display server message if available
                icon: 'error',
                confirmButtonText: 'OK'
            });
        }
    },
    error: function(xhr, status, error) {
        // Handle AJAX errors
        console.error('AJAX Error: ' + error);

        // Display error message with SweetAlert
        Swal.fire({
            title: 'Error',
            text: 'An error occurred. Please try again.',
            icon: 'error',
            confirmButtonText: 'OK'
        });
    }
});

        }
    });
}


function checkIn(bookingId) {
    console.log('Check In clicked, Booking ID: ' + bookingId);
    // Add your logic here for Check In
}

function removeBooking(bookingId) {
    console.log('Delete clicked, Booking ID: ' + bookingId);
    // Add your logic here for Delete
}
</script>


</body>

</html>