
<?php
session_start();
// Check if user is logged in
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: index.php');
    exit;
}
include("connection.php");

// Pagination logic
$limit = 5; // Number of rooms per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max($page, 1);
$offset = ($page - 1) * $limit;

// Get total number of rooms
$totalQuery = "SELECT COUNT(*) AS total FROM rooms";
$totalResult = mysqli_query($conn, $totalQuery);
$totalData = mysqli_fetch_assoc($totalResult);
$totalRooms = $totalData['total'];
$totalPages = ceil($totalRooms / $limit);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hotel Kottaram Regency - Add Rooms</title>
  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- Bootstrap Icons -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
  <!-- Custom Stylesheet -->
  <link href="style.css" rel="stylesheet">
</head>
<body>
  <!-- Mesh Gradient Background -->
  <div class="mesh-bg"></div>
  <!-- Sidebar Overlay (Mobile) -->
  <div class="sidebar-overlay" id="sidebarOverlay"></div>

  <!-- ======================== SIDEBAR ======================== -->
  <aside class="sidebar" id="sidebar">
    <!-- Logo -->
    <div class="sidebar-logo">
      <img class="img-fluid" src="3.jpg" alt="" width="70%">
    </div>
    <!-- Menu -->
    <nav class="sidebar-menu">
      <span class="menu-label">Main</span>
      <div class="menu-item">
        <a href="#" class="menu-link" data-submenu="submenuUsers">
          <i class="bi bi-box-seam-fill"></i>
          <span class="menu-text">Master</span>
          <i class="bi bi-chevron-right menu-arrow"></i>
        </a>
        <div class="submenu" id="submenuUsers">
          <a href="add_category.php" class="menu-link">Add Category</a>
          <a href="add_gallery.php" class="menu-link">Gallery</a>
          <a href="add_rooms.php" class="menu-link">Rooms</a>
          <a href="add_facilities.php" class="menu-link">Facilities</a>
        </div>
      </div>
    </nav>
  </aside>

  <!-- ======================== MAIN CONTENT ======================== -->
  <div class="main-content">
    <!-- ============ TOP HEADER ============ -->
    <header class="top-header">
      <div class="header-left">
        <button class="sidebar-toggle" id="sidebarToggle">
          <i class="bi bi-list"></i>
        </button>
        <div class="page-title">
          <h1>Rooms Management</h1>
        </div>
      </div>
      <div class="header-right">
        <div class="profile-dropdown">
          <div class="profile-toggle" id="profileToggle">
            <div class="profile-info">
              <div class="profile-name">admin</div>
            </div>
            <i class="bi bi-chevron-down profile-arrow"></i>
          </div>
          <div class="profile-menu" id="profileMenu">
            <a href="logout.php" class="pm-item logout">
              <i class="bi bi-box-arrow-right"></i> Logout
            </a>
          </div>
        </div>
      </div>
    </header>

    <!-- ============ DASHBOARD CONTENT ============ -->
    <div class="dashboard-content">
      <div class="row g-4 mb-4">
        <!-- LEFT: Form Card -->
        <div class="col-lg-4 anim-fade-left anim-delay-5">
          <div class="glass-card">
            <div class="card-header-custom">
              <h5>Add New Room</h5>
            </div>
            <div class="card-body-custom">
              <form id="room-form" onsubmit="return false;">
                <input type="hidden" id="hid_room_id">
                <!-- Room Name -->
                <div class="form-floating-custom">
                  <input type="text" class="form-input" id="txt_room_name" placeholder=" " required="">
                  <label class="form-label-custom" for="txt_room_name">Room Name</label>
                </div>
                <!-- Image Upload -->
                <div class="form-floating-custom">
                  <input type="file" class="form-input" id="txt_image" accept="image/*">
                  <input type="hidden" id="txt_image_old">
                </div>
                <!-- Submit -->
                <div style="display:flex;gap:10px;margin-top:15px;">
                  <button type="button" class="btn-gradient w-100" id="btn_room_add" onclick="add_room();">
                    <i class="bi bi-send-fill"></i> Submit
                  </button>
                  <button type="button" class="btn-gradient w-100" id="btn_room_update" style="display:none;background:#6b7280;" onclick="edit_room();">
                    <i class="bi bi-send-fill"></i> Update
                  </button>
                </div>
                <button type="button" class="btn-gradient w-100" id="btn_room_cancel" style="display:none;background:#9ca3af;margin-top:10px;" onclick="cancelEdit()">
                  Cancel
                </button>
              </form>
            </div>
          </div>
        </div>

        <!-- RIGHT: Table -->
        <div class="col-lg-6 anim-fade-left anim-delay-5">
          <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover align-middle">
              <thead class="table-light">
                <tr>
                  <th>No</th>
                  <th>Room Name</th>
                  <th>Image</th>
                  <th>Action</th>
                </tr>
              </thead>
              <tbody id="table-body">
                <?php
                $query = "SELECT * FROM rooms ORDER BY id ASC LIMIT $limit OFFSET $offset";
                $result = mysqli_query($conn, $query);
                $counter = $offset + 1;
                while($row = mysqli_fetch_assoc($result)) {
                ?>
                <tr>
                  <td><?php echo $counter++; ?></td>
                  <td><?php echo htmlspecialchars($row['room_name']); ?></td>
                  <td>
                    <?php if(!empty($row['image'])) { ?>
                      <img src="room_images/<?php echo htmlspecialchars($row['image']); ?>" alt="Room" style="width: 45px; height: auto; object-fit: cover; border-radius: 4px;">
                    <?php } else { ?>
                      <span style="color: #999; font-size: 12px;">No Image</span>
                    <?php } ?>
                  </td>
                  <td>
                    <button class="btn btn-sm" onclick="fetch_room(<?php echo $row['id']; ?>)">
                      <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-sm" onclick="delete_room(<?php echo $row['id']; ?>)">
                      <i class="bi bi-trash"></i>
                    </button>
                  </td>
                </tr>
                <?php } ?>
              </tbody>
            </table>
            <!-- Pagination -->
            <?php if($totalPages > 1): ?>
            <nav aria-label="Page navigation" class="mt-3">
              <ul class="pagination justify-content-center">
                <!-- Previous Button -->
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                  <a class="page-link" href="?page=<?php echo $page - 1; ?>" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                  </a>
                </li>
                <!-- Page Numbers -->
                <?php for($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                  <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
                <!-- Next Button -->
                <li class="page-item <?php echo $page >= $totalPages ? 'disabled' : ''; ?>">
                  <a class="page-link" href="?page=<?php echo $page + 1; ?>" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                  </a>
                </li>
              </ul>
            </nav>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
    <!-- end dashboard-content -->
  </div>
  <!-- end main-content -->

  <!-- Bootstrap 5 JS Bundle -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <!-- Custom JS -->
  <script src="main.js"></script>
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    var currentPage = <?php echo $page; ?>;
    
    function add_room() {
      var formData = new FormData();
      formData.append("add_room", "1");
      formData.append("room_name", $('#txt_room_name').val());
      var imageFile = $('#txt_image')[0].files[0];
      if(imageFile) {
        formData.append("image", imageFile);
      }
      
      $.ajax({
        type: "POST",
        url: "add_rooms_save.php",
        data: formData,
        contentType: false,
        processData: false,
        cache: true,
        success: function(response) {
          alert(response);
          setTimeout(function(){
            $('#txt_room_name').val('');
            $('#txt_image').val('');
            window.location.href='add_rooms.php?page=' + currentPage;
          }, 3000);
        }
      });
    }

    function fetch_room(room_id) {
      $.ajax({
        type: "POST",
        url: "add_rooms_save.php",
        dataType: "json",
        data: {
          fetch_room: 1,
          room_id: room_id
        },
        success: function(response) {
          $('#hid_room_id').val(response.id);
          $('#txt_room_name').val(response.room_name);
          $('#txt_image_old').val(response.image);
          
          $('#btn_room_add').hide();
          $('#btn_room_update').show();
          $('#btn_room_cancel').show();
        },
        error: function() {
          alert("Failed to fetch room data.");
        }
      });
    }

    function edit_room() {
      var formData = new FormData();
      formData.append("edit_room", "1");
      formData.append("id", $('#hid_room_id').val());
      formData.append("room_name", $('#txt_room_name').val());
      var imageFile = $('#txt_image')[0].files[0];
      if(imageFile) {
        formData.append("image", imageFile);
      }
      
      $.ajax({
        type: "POST",
        url: "add_rooms_save.php",
        data: formData,
        contentType: false,
        processData: false,
        cache: true,
        success: function(response) {
          alert(response);
          setTimeout(function(){
            window.location.href='add_rooms.php?page=' + currentPage;
          }, 3000);
        }
      });
    }

    function delete_room(room_id) {
      if(confirm('Are you sure you want to delete this room?')) {
        $.ajax({
          type: "POST",
          url: "add_rooms_save.php",
          data: {
            delete_room: 1,
            room_id: room_id
          },
          success: function(response) {
            alert(response);
            window.location.href='add_rooms.php?page=' + currentPage;
          }
        });
      }
    }

    function cancelEdit() {
      $('#hid_room_id').val('');
      $('#txt_room_name').val('');
      $('#txt_image').val('');
      $('#txt_image_old').val('');
      
      $('#btn_room_add').show();
      $('#btn_room_update').hide();
      $('#btn_room_cancel').hide();
    }
  </script>
</body>
</html>
