<?php
// update_room_process.php - Handles updating room data

ini_set('display_errors', 1); // Debugging only — remove in production
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    $roomId = filter_var($data['room_id'] ?? '', FILTER_VALIDATE_INT);
    $floorId = filter_var($data['floorId'] ?? '', FILTER_VALIDATE_INT);
    $roomNumber = trim($data['roomNumber'] ?? '');
    $roomType = trim($data['roomType'] ?? '');
    $capacity = filter_var($data['capacity'] ?? '', FILTER_VALIDATE_INT);

    // Validate required fields
    if ($roomId === false || $floorId === false || !$roomNumber || !$roomType || $capacity === false) {
        echo json_encode(['success' => false, 'message' => 'All fields are required and must be valid.']);
        exit;
    }

    if ($capacity < 1) {
        echo json_encode(['success' => false, 'message' => 'Capacity must be at least 1.']);
        exit;
    }

    $allowedRoomTypes = ['single', 'shared', 'dormitory'];
    if (!in_array($roomType, $allowedRoomTypes)) {
        echo json_encode(['success' => false, 'message' => 'Invalid room type.']);
        exit;
    }

    try {
        $sql = "UPDATE rooms
                SET floor_id = :floor_id, room_number = :room_number, room_type = :room_type, capacity = :capacity
                WHERE room_id = :room_id";

        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':floor_id', $floorId, PDO::PARAM_INT);
        $stmt->bindParam(':room_number', $roomNumber);
        $stmt->bindParam(':room_type', $roomType);
        $stmt->bindParam(':capacity', $capacity, PDO::PARAM_INT);
        $stmt->bindParam(':room_id', $roomId, PDO::PARAM_INT);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Room updated successfully.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update room.']);
        }
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            echo json_encode(['success' => false, 'message' => 'Duplicate room number for the selected floor.']);
        } else {
            error_log("DB Error in update_room_process.php: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'A database error occurred.']);
        }
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}

