<?php
// 1. START SESSION & INCLUDE HEADER
session_start();
include 'admin-header.php';

// --- Page-Specific Logic Starts Here ---

$page_error = '';
$hotel = null;
$rooms_result = null;

// 2. VALIDATE THE HOTEL ID FROM THE URL
$hotel_id = filter_input(INPUT_GET, 'hotel_id', FILTER_VALIDATE_INT);
if (!$hotel_id) {
    $page_error = "No hotel specified. Please return to the hotels list and select a hotel to manage.";
} else {
    // 3. FETCH THE PARENT HOTEL'S NAME
    $stmt_hotel = $conn->prepare("SELECT name FROM hotels WHERE id = ?");
    $stmt_hotel->bind_param("i", $hotel_id);
    $stmt_hotel->execute();
    $hotel = $stmt_hotel->get_result()->fetch_assoc();
    $stmt_hotel->close();

    if (!$hotel) {
        $page_error = "The specified hotel could not be found.";
    } else {
        // 4. HANDLE FORM SUBMISSIONS (CREATE, UPDATE, DELETE)
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
            $action = $_POST['action'];

            switch ($action) {
                case 'add_room':
                    $name = trim($_POST['name']);
                    $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
                    $max_adults = filter_input(INPUT_POST, 'max_adults', FILTER_VALIDATE_INT);
                    $max_children = filter_input(INPUT_POST, 'max_children', FILTER_VALIDATE_INT);
                    if (!empty($name) && $price && $max_adults) {
                        $stmt = $conn->prepare("INSERT INTO rooms (hotel_id, name, price_per_night, max_adults, max_children) VALUES (?, ?, ?, ?, ?)");
                        $stmt->bind_param("isdii", $hotel_id, $name, $price, $max_adults, $max_children);
                        if($stmt->execute()) $_SESSION['success_message'] = "Room added successfully."; else $_SESSION['error_message'] = "Error adding room.";
                        $stmt->close();
                    } else { $_SESSION['error_message'] = "Please fill in all required fields."; }
                    break;
                
                case 'edit_room':
                    $room_id = filter_input(INPUT_POST, 'room_id', FILTER_VALIDATE_INT);
                    $name = trim($_POST['name']);
                    $price = filter_input(INPUT_POST, 'price', FILTER_VALIDATE_FLOAT);
                    $max_adults = filter_input(INPUT_POST, 'max_adults', FILTER_VALIDATE_INT);
                    $max_children = filter_input(INPUT_POST, 'max_children', FILTER_VALIDATE_INT);
                    if ($room_id && !empty($name) && $price && $max_adults) {
                        $stmt = $conn->prepare("UPDATE rooms SET name = ?, price_per_night = ?, max_adults = ?, max_children = ? WHERE id = ? AND hotel_id = ?");
                        $stmt->bind_param("sdiiii", $name, $price, $max_adults, $max_children, $room_id, $hotel_id);
                        if($stmt->execute()) $_SESSION['success_message'] = "Room updated successfully."; else $_SESSION['error_message'] = "Error updating room.";
                        $stmt->close();
                    } else { $_SESSION['error_message'] = "Invalid data for update."; }
                    break;

                case 'delete_room':
                    $room_id = filter_input(INPUT_POST, 'room_id', FILTER_VALIDATE_INT);
                    if ($room_id) {
                        $stmt = $conn->prepare("DELETE FROM rooms WHERE id = ? AND hotel_id = ?");
                        $stmt->bind_param("ii", $room_id, $hotel_id);
                        if($stmt->execute()) $_SESSION['success_message'] = "Room deleted successfully."; else $_SESSION['error_message'] = "Error deleting room.";
                        $stmt->close();
                    }
                    break;
            }
            header("Location: manage-rooms.php?hotel_id=" . $hotel_id);
            exit();
        }

        // 5. FETCH ALL ROOMS FOR THIS HOTEL
        $stmt_rooms = $conn->prepare("SELECT * FROM rooms WHERE hotel_id = ? ORDER BY price_per_night ASC");
        $stmt_rooms->bind_param("i", $hotel_id);
        $stmt_rooms->execute();
        $rooms_result = $stmt_rooms->get_result();
        $stmt_rooms->close();
    }
}
?>

<?php if (isset($_SESSION['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
<?php endif; ?>

<?php if ($page_error): ?>
    <div class="alert alert-danger mt-4"><h4 class="alert-heading">Error</h4><p><?php echo $page_error; ?></p><hr><a href="manage-hotels.php" class="btn btn-outline-danger">Return to Hotels List</a></div>
<?php else: ?>
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <div>
            <h1 class="h2">Manage Rooms</h1>
            <p class="text-muted mb-0">For Hotel: <span class="fw-bold text-light"><?php echo htmlspecialchars($hotel['name']); ?></span></p>
        </div>
        <div class="btn-toolbar mb-2 mb-md-0">
            <a href="manage-hotels.php" class="btn btn-outline-secondary me-2"><i class="bi bi-arrow-left-circle me-1"></i> Back to Hotels</a>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#roomModal">
                <i class="bi bi-plus-circle-fill me-1"></i> Add New Room
            </button>
        </div>
    </div>
    
    <div class="card shadow-sm">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-dark">
                    <tr><th>Room Name / Type</th><th>Price Per Night</th><th>Max Occupancy</th><th class="text-end">Actions</th></tr>
                </thead>
                <tbody>
                    <?php if ($rooms_result->num_rows > 0): while ($room = $rooms_result->fetch_assoc()): ?>
                    <tr>
                        <td class="fw-bold"><?php echo htmlspecialchars($room['name']); ?></td>
                        <td>₱<?php echo number_format($room['price_per_night'], 2); ?></td>
                        <td>
                            <i class="bi bi-person-fill"></i> <?php echo $room['max_adults']; ?> Adult<?php if($room['max_adults']!=1) echo 's'; ?>
                            <?php if($room['max_children'] > 0): ?>
                                + <i class="bi bi-person-fill"></i> <?php echo $room['max_children']; ?> Child<?php if($room['max_children']!=1) echo 'ren'; ?>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <div class="d-inline-flex gap-1">
                                <button type="button" class="btn btn-sm btn-warning edit-btn"
                                        data-bs-toggle="modal" data-bs-target="#roomModal"
                                        data-id="<?php echo $room['id']; ?>"
                                        data-name="<?php echo htmlspecialchars($room['name']); ?>"
                                        data-price="<?php echo $room['price_per_night']; ?>"
                                        data-adults="<?php echo $room['max_adults']; ?>"
                                        data-children="<?php echo $room['max_children']; ?>">
                                    <i class="bi bi-pencil-fill"></i>
                                </button>
                                <form method="POST" action="manage-rooms.php?hotel_id=<?php echo $hotel_id; ?>" onsubmit="return confirm('Are you sure you want to delete this room?');">
                                    <input type="hidden" name="action" value="delete_room">
                                    <input type="hidden" name="room_id" value="<?php echo $room['id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-danger"><i class="bi bi-trash-fill"></i></button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endwhile; else: ?>
                    <tr><td colspan="4" class="text-center p-4">No rooms have been added for this hotel yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
<?php endif; ?>

<div class="modal fade" id="roomModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
<form action="manage-rooms.php?hotel_id=<?php echo $hotel_id; ?>" method="POST">
    <div class="modal-header"><h5 class="modal-title" id="roomModalLabel">Add New Room</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <input type="hidden" name="action" id="modal-action" value="add_room">
        <input type="hidden" name="room_id" id="modal-room-id">
        <div class="mb-3"><label for="modal-name" class="form-label">Room Name / Type <span class="text-danger">*</span></label><input type="text" class="form-control" id="modal-name" name="name" required></div>
        <div class="mb-3"><label for="modal-price" class="form-label">Price Per Night <span class="text-danger">*</span></label><div class="input-group"><span class="input-group-text">₱</span><input type="number" step="0.01" class="form-control" id="modal-price" name="price" required></div></div>
        <div class="row">
            <div class="col-md-6 mb-3"><label for="modal-adults" class="form-label">Max Adults <span class="text-danger">*</span></label><input type="number" class="form-control" id="modal-adults" name="max_adults" min="1" required></div>
            <div class="col-md-6 mb-3"><label for="modal-children" class="form-label">Max Children</label><input type="number" class="form-control" id="modal-children" name="max_children" min="0"></div>
        </div>
    </div>
    <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button type="submit" class="btn btn-primary" id="modal-submit-btn">Save Room</button></div>
</form></div></div></div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const roomModal = document.getElementById('roomModal');
    roomModal.addEventListener('show.bs.modal', function (event) {
        const button = event.relatedTarget;
        const form = roomModal.querySelector('form'); form.reset();
        if (button.classList.contains('edit-btn')) {
            roomModal.querySelector('.modal-title').textContent = 'Edit Room';
            roomModal.querySelector('#modal-submit-btn').textContent = 'Update Room';
            document.getElementById('modal-action').value = 'edit_room';
            document.getElementById('modal-room-id').value = button.dataset.id;
            document.getElementById('modal-name').value = button.dataset.name;
            document.getElementById('modal-price').value = button.dataset.price;
            document.getElementById('modal-adults').value = button.dataset.adults;
            document.getElementById('modal-children').value = button.dataset.children;
        } else {
            roomModal.querySelector('.modal-title').textContent = 'Add New Room';
            roomModal.querySelector('#modal-submit-btn').textContent = 'Save Room';
            document.getElementById('modal-action').value = 'add_room';
            document.getElementById('modal-room-id').value = '';
        }
    });
});
</script>

<?php include 'admin-footer.php'; ?>
