<?php
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);

    // Sanitize inputs
    $roomId = filter_var($data['roomId'] ?? null, FILTER_VALIDATE_INT);
    $bedNumber = trim($data['bedNumber'] ?? '');

    if (!$roomId || empty($bedNumber)) {
        echo json_encode(['success' => false, 'message' => 'Room ID and Bed Number are required.']);
        exit;
    }

    // Insert into beds table
    $sql = "INSERT INTO beds (room_id, bed_number) VALUES (:room_id, :bed_number)";
    
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(':room_id', $roomId, PDO::PARAM_INT);
        $stmt->bindParam(':bed_number', $bedNumber, PDO::PARAM_STR);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Bed added successfully!']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to add bed.']);
        }
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            echo json_encode(['success' => false, 'message' => 'This bed number already exists in this room.']);
        } else {
            error_log("DB error in add_bed_process.php: " . $e->getMessage());
            echo json_encode(['success' => false, 'message' => 'A database error occurred.']);
        }
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
