isLoggedIn()) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Unauthorized']); exit; } $db = Database::getInstance(); // Support both GET and POST for backward compatibility $attribute_id = $_POST['attribute_id'] ?? $_GET['attribute_id'] ?? ''; if (empty($attribute_id)) { echo json_encode(['success' => false, 'message' => 'Attribute ID is required']); exit; } try { // Get attribute details - using correct column names $stmt = $db->prepare("SELECT * FROM attributes WHERE id = ?"); $stmt->bind_param('i', $attribute_id); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows === 0) { throw new Exception('Attribute not found'); } $attribute = $result->fetch_assoc(); $choices = []; // Get choices based on attribute choice_type (correct column name) if ($attribute['choice_type'] === 'multiple' || $attribute['choice_type'] === 'single') { // For multiple choice and single choice, get predefined options first $predefined_choices = json_decode($attribute['choices'], true); // correct column name if (is_array($predefined_choices)) { foreach ($predefined_choices as $choice) { if (!in_array($choice, $choices)) { $choices[] = $choice; // Keep as string for backward compatibility } } } } // Additionally, get unique values from panel data for this attribute $query = "SELECT DISTINCT JSON_EXTRACT(attribute_values, '$.\"$attribute_id\"') as value FROM panel_data WHERE JSON_EXTRACT(attribute_values, '$.\"$attribute_id\"') IS NOT NULL AND JSON_EXTRACT(attribute_values, '$.\"$attribute_id\"') != 'null' ORDER BY value"; $result = $db->query($query); if ($result) { while ($row = $result->fetch_assoc()) { $value = $row['value']; // Clean up the value (remove quotes and handle JSON arrays) $value = trim($value, '"'); // Skip empty values if (empty($value) || $value === 'null') { continue; } // Handle JSON arrays (for multiple values) if (substr($value, 0, 1) === '[' && substr($value, -1) === ']') { $array_values = json_decode($value, true); if (is_array($array_values)) { foreach ($array_values as $array_value) { if (!empty($array_value) && !in_array($array_value, $choices)) { $choices[] = $array_value; // Keep as string for backward compatibility } } continue; } } // Add single value if not already in choices if (!in_array($value, $choices)) { $choices[] = $value; // Keep as string for backward compatibility } } } // Sort choices alphabetically sort($choices); // Return format compatible with existing OptimAIze usage echo json_encode([ 'success' => true, 'choices' => $choices, // Array of strings, not objects 'attribute_name' => $attribute['name'], 'attribute_type' => $attribute['choice_type'] ]); } catch (Exception $e) { error_log("Error getting attribute choices: " . $e->getMessage()); echo json_encode([ 'success' => false, 'message' => 'Failed to load choices: ' . $e->getMessage() ]); } ?>