<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();

/* ================= Session Timeout (12 hours) ================= */
$SESSION_TIMEOUT = 43200;

if (isset($_SESSION['LAST_ACTIVITY'])) {
    if (time() - $_SESSION['LAST_ACTIVITY'] > $SESSION_TIMEOUT) {
        session_unset();
        session_destroy();
        header("Location: login.php?timeout=1");
        exit;
    }
}
$_SESSION['LAST_ACTIVITY'] = time();

include('includes/db.php');
include('includes/header.php');


// ---------------- CSRF Token ----------------
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---------------- Room Status Options ----------------
$roomStatuses = ["Available", "Occupied", "Under Maintenance", "Cleaning", "Reserved"];

// ---------------- Handle CRUD ----------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (!isset($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['csrf_token']) die("Invalid CSRF token");

    $facility_id = $_SESSION['facility_id'];

    // ---------- CREATE ----------
    if (isset($_POST['create'])) {
        $room_number = trim($_POST['room_number']);
        $room_type = trim($_POST['room_type']);
        $floor = trim($_POST['floor']);
        $wing = trim($_POST['wing']);
        $capacity = intval($_POST['capacity']);
        $current_status = trim($_POST['current_status']);
        $description = trim($_POST['description']);

        $stmt = $pdo->prepare("INSERT INTO rooms (facility_id, room_number, room_type, floor, wing, capacity, current_status, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$facility_id, $room_number, $room_type, $floor, $wing, $capacity, $current_status, $description]);

        $_SESSION['flash'] = ['message'=>'Room added successfully!','color'=>'#28a745'];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- UPDATE ----------
    if (isset($_POST['update'])) {
        $id = intval($_POST['id']);
        $room_number = trim($_POST['room_number']);
        $room_type = trim($_POST['room_type']);
        $floor = trim($_POST['floor']);
        $wing = trim($_POST['wing']);
        $capacity = intval($_POST['capacity']);
        $current_status = trim($_POST['current_status']);
        $description = trim($_POST['description']);

        $stmt = $pdo->prepare("UPDATE rooms SET room_number=?, room_type=?, floor=?, wing=?, capacity=?, current_status=?, description=? WHERE id=? AND facility_id=?");
        $stmt->execute([$room_number, $room_type, $floor, $wing, $capacity, $current_status, $description, $id, $facility_id]);

        $_SESSION['flash'] = ['message'=>'Room updated successfully!','color'=>'#007bff'];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }

    // ---------- DELETE ----------
    if (isset($_POST['delete'])) {
        $id = intval($_POST['id']);

        $stmt = $pdo->prepare("DELETE FROM rooms WHERE id=? AND facility_id=?");
        $stmt->execute([$id, $facility_id]);

        $_SESSION['flash'] = ['message'=>'Room deleted successfully!','color'=>'#dc3545'];
        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
}

// ---------------- Fetch Rooms (facility-aware) ----------------
$roomsStmt = $pdo->prepare("
    SELECT *
    FROM rooms
    WHERE facility_id = :facility_id
    ORDER BY floor, room_number ASC
");
$roomsStmt->execute(['facility_id' => $_SESSION['facility_id']]);
$rooms = $roomsStmt->fetchAll(PDO::FETCH_ASSOC);
?>


<!-- Navbar and Sidebar -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
  <?php include('includes/navbar.php'); ?>
</nav>
<div class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
  <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
  <div class="content-wrapper">
    <div class="col-xs-12">
      <div class="card">
        <div class="card-header">
          <h4 class="card-title">Rooms Management</h4>
        </div>
        <div class="card-body collapse in">
          <div class="card-block card-dashboard">
            <div class="row mb-2">
              <div class="col-lg-4 col-md-6 col-sm-12">
                <button type="button" class="btn btn-outline-primary btn-md" data-toggle="modal" data-target="#addRoomModal">Add New Room</button>
              </div>
            </div>

            <div class="table-responsive">
              <table class="table table-hover mb-0" id="Table">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Room Number</th>
                    <th>Type</th>
                    <th>Floor</th>
                    <th>Wing</th>
                    <th>Capacity</th>
                    <th>Status</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <?php $counter=1; foreach($rooms as $room): 
                  $statusColor = [
                    'Available' => '#28a745',
                    'Occupied' => '#dc3545',
                    'Under Maintenance' => '#ffc107',
                    'Cleaning' => '#17a2b8',
                    'Reserved' => '#6f42c1'
                  ][$room['current_status']] ?? '#6c757d';
                  ?>
                  <tr>
                    <td><?= $counter++ ?></td>
                    <td><?= htmlspecialchars($room['room_number']) ?></td>
                    <td><?= htmlspecialchars($room['room_type']) ?></td>
                    <td><?= htmlspecialchars($room['floor']) ?></td>
                    <td><?= htmlspecialchars($room['wing']) ?></td>
                    <td><?= htmlspecialchars($room['capacity']) ?></td>
                    <td style="color: <?= $statusColor ?>; font-weight:bold;">
                        <?= htmlspecialchars($room['current_status']) ?>
                    </td>
                    <td>
                      <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#editModal<?= $room['id'] ?>">Edit</button>
                      
                      <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#viewModal<?= $room['id'] ?>">View</button>
                      
                      <form method="post" style="display:inline-block" onsubmit="return confirm('Are you sure you want to delete this room?');">
                        <input type="hidden" name="id" value="<?= $room['id'] ?>">
                        <input type="hidden" name="csrf" value="<?= $csrf ?>">
                        <button type="submit" name="delete" class="btn btn-sm btn-danger">Delete</button>
                      </form>
                    </td>
                  </tr>

                  <!-- Edit Modal -->
                  <div class="modal fade" id="editModal<?= $room['id'] ?>" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                      <div class="modal-content">
                        <form method="post">
                          <input type="hidden" name="csrf" value="<?= $csrf ?>">
                          <input type="hidden" name="id" value="<?= $room['id'] ?>">

                          <div class="modal-header">
                            <h4>Edit Room</h4>
                          </div>
                          <div class="modal-body">
                            <div class="row">
                              <div class="col-md-6">
                                <label>Room Number *</label>
                                <input type="text" name="room_number" class="form-control" 
                                       value="<?= htmlspecialchars($room['room_number']) ?>" required>
                              </div>
                              <div class="col-md-6">
                                <label>Room Type *</label>
                                <input type="text" name="room_type" class="form-control" 
                                       value="<?= htmlspecialchars($room['room_type']) ?>" required>
                              </div>
                            </div>
                            
                            <div class="row mt-2">
                              <div class="col-md-4">
                                <label>Floor</label>
                                <input type="text" name="floor" class="form-control" 
                                       value="<?= htmlspecialchars($room['floor']) ?>">
                              </div>
                              <div class="col-md-4">
                                <label>Wing/Section</label>
                                <input type="text" name="wing" class="form-control" 
                                       value="<?= htmlspecialchars($room['wing']) ?>">
                              </div>
                              <div class="col-md-4">
                                <label>Capacity</label>
                                <input type="number" name="capacity" class="form-control" min="1" 
                                       value="<?= htmlspecialchars($room['capacity']) ?>">
                              </div>
                            </div>
                            
                            <div class="row mt-2">
                              <div class="col-md-6">
                                <label>Current Status *</label>
                                <select name="current_status" class="form-control" required>
                                  <?php foreach($roomStatuses as $status): ?>
                                    <option value="<?= $status ?>" <?= $room['current_status']==$status?'selected':'' ?>><?= $status ?></option>
                                  <?php endforeach; ?>
                                </select>
                              </div>
                            </div>
                            
                            <div class="row mt-2">
                              <div class="col-md-12">
                                <label>Description</label>
                                <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($room['description']) ?></textarea>
                              </div>
                            </div>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
                            <button type="submit" name="update" class="btn btn-outline-primary btn-md">Update</button>
                          </div>
                        </form>
                      </div>
                    </div>
                  </div>

                  <!-- View Modal -->
                  <div class="modal fade" id="viewModal<?= $room['id'] ?>" tabindex="-1">
                    <div class="modal-dialog">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h4>Room Details</h4>
                        </div>
                        <div class="modal-body">
                          <p><strong>Room Number:</strong> <?= htmlspecialchars($room['room_number']) ?></p>
                          <p><strong>Type:</strong> <?= htmlspecialchars($room['room_type']) ?></p>
                          <p><strong>Floor:</strong> <?= htmlspecialchars($room['floor']) ?></p>
                          <p><strong>Wing:</strong> <?= htmlspecialchars($room['wing']) ?></p>
                          <p><strong>Capacity:</strong> <?= htmlspecialchars($room['capacity']) ?></p>
                          <p><strong>Status:</strong> <span style="color: <?= $statusColor ?>; font-weight:bold;"><?= htmlspecialchars($room['current_status']) ?></span></p>
                          <?php if(!empty($room['description'])): ?>
                            <p><strong>Description:</strong> <?= htmlspecialchars($room['description']) ?></p>
                          <?php endif; ?>
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
                        </div>
                      </div>
                    </div>
                  </div>

                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Room Modal -->
<div class="modal fade" id="addRoomModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <form method="post">
        <input type="hidden" name="csrf" value="<?= $csrf ?>">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <label class="modal-title">Add New Room</label>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6">
              <label>Room Number *</label>
              <input type="text" name="room_number" class="form-control" required>
            </div>
            <div class="col-md-6">
              <label>Room Type *</label>
              <input type="text" name="room_type" class="form-control" required>
            </div>
          </div>
          
          <div class="row mt-2">
            <div class="col-md-4">
              <label>Floor</label>
              <input type="text" name="floor" class="form-control">
            </div>
            <div class="col-md-4">
              <label>Wing/Section</label>
              <input type="text" name="wing" class="form-control">
            </div>
            <div class="col-md-4">
              <label>Capacity</label>
              <input type="number" name="capacity" class="form-control" min="1" value="1">
            </div>
          </div>
          
          <div class="row mt-2">
            <div class="col-md-6">
              <label>Current Status *</label>
              <select name="current_status" class="form-control" required>
                <?php foreach($roomStatuses as $status): ?>
                  <option value="<?= $status ?>"><?= $status ?></option>
                <?php endforeach; ?>
              </select>
            </div>
          </div>
          
          <div class="row mt-2">
            <div class="col-md-12">
              <label>Description</label>
              <textarea name="description" class="form-control" rows="3" maxlength="500" placeholder="Optional description"></textarea>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-outline-secondary btn-md" data-dismiss="modal">Close</button>
          <button type="submit" name="create" class="btn btn-outline-primary btn-md">Save Room</button>
        </div>
      </form>
    </div>
  </div>
</div>

<style>
.toast-message{
  position:fixed;
  top:20px;
  right:20px;
  z-index:9999;
  padding:.75rem 1rem;
  border-radius:.25rem;
  opacity:0.95;
  color: #fff;
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
}

.form-control {
  height: 45px;
}

textarea.form-control {
  height: auto;
  min-height: 80px;
}

.table th, .table td {
  vertical-align: middle;
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Focus on room number input when modal opens
  $('#addRoomModal').on('shown.bs.modal', function () {
    $(this).find('input[name="room_number"]').focus();
  });
  
  // Focus on room number input when edit modal opens
  $('[id^="editModal"]').on('shown.bs.modal', function () {
    $(this).find('input[name="room_number"]').focus().select();
  });
});
</script>

<?php include('includes/footer.php'); ?>

<?php if(isset($_SESSION['flash'])): ?>
<script>
  window.onload = function() {
    const toast = document.createElement('div');
    toast.className = 'toast-message';
    toast.style.background = '<?= $_SESSION['flash']['color'] ?>';
    toast.innerText = '<?= $_SESSION['flash']['message'] ?>';
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
  }
</script>
<?php unset($_SESSION['flash']); endif; ?>