<?php
require_once '../../config/config.php';

// Get parameters
$roomName = isset($_POST['room_name']) ? trim($_POST['room_name']) : '';
$inchargeId = isset($_POST['incharge_id']) ? (int)$_POST['incharge_id'] : 0;
$capacity = isset($_POST['capacity']) ? (int)$_POST['capacity'] : 0;

if (empty($roomName) || $inchargeId <= 0 || $capacity <= 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Room name, supervisor and capacity are required'
    ]);
    exit;
}

try {
    // Check if room name already exists
    $checkSql = "SELECT room_id FROM valuation_rooms WHERE room_name = ?";
    $checkStmt = $pdo->prepare($checkSql);
    $checkStmt->execute([$roomName]);
    
    if ($checkStmt->fetch()) {
        throw new Exception('Room name already exists');
    }

    // Check if supervisor exists
    $supervisorSql = "SELECT staff_id FROM staff WHERE staff_id = ? AND status = 'Active'";
    $supervisorStmt = $pdo->prepare($supervisorSql);
    $supervisorStmt->execute([$inchargeId]);
    
    if (!$supervisorStmt->fetch()) {
        throw new Exception('Selected supervisor is not active or does not exist');
    }

    // Insert new room
    $insertSql = "INSERT INTO valuation_rooms (room_name, incharge_id, capacity) VALUES (?, ?, ?)";
    $insertStmt = $pdo->prepare($insertSql);
    $insertStmt->execute([$roomName, $inchargeId, $capacity]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Valuation room created successfully'
    ]);

} catch (Exception $e) {
    error_log('Create Valuation Room Error: ' . $e->getMessage());
    
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>