<?php
// add_room_process.php - Handles adding new room data to the database

// Enable full error reporting for debugging (REMOVE in production!)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once 'config.php'; // DB config

header('Content-Type: application/json'); // Return JSON response

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

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

    // Validation
    if ($floorId === false || !$roomNumber || !$roomType || $capacity === false) { // Added === false checks for filter_var
        echo json_encode(['success' => false, 'message' => 'All fields are required and valid.']);
        exit;
    }

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

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

    try {
        $stmt = $pdo->prepare("
            INSERT INTO rooms (floor_id, room_number, room_type, capacity, current_occupancy)
            VALUES (:floor_id, :room_number, :room_type, :capacity, 0)
        ");
        $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);

        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'Room added successfully!']);
        } else {
            // This else block might indicate a PDO error not caught by the try-catch, or a logical error.
            echo json_encode(['success' => false, 'message' => 'Failed to add room.']);
        }
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) { // Unique constraint violation
            echo json_encode(['success' => false, 'message' => 'This room number already exists for the selected floor.']);
        } else {
            error_log("DB Error [add_room_process.php]: " . $e->getMessage());
            // This is the generic message you are seeing.
            echo json_encode(['success' => false, 'message' => 'A database error occurred. Please try again later.']);
        }
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
// NO CLOSING PHP TAG `?>
