isLoggedIn()) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Unauthorized']); exit; } $db = Database::getInstance(); $attribute_id = $_POST['attribute_id'] ?? ''; if (empty($attribute_id)) { echo json_encode(['success' => false, 'message' => 'Attribute ID is required']); exit; } try { // Get attribute details $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 type if ($attribute['type'] === 'multiple' || $attribute['type'] === 'single') { // For multiple choice and single choice, get predefined options $options = json_decode($attribute['options'], true); if (is_array($options)) { foreach ($options as $option) { $choices[] = [ 'value' => $option, 'label' => $option ]; } } } else { // For other types (text, number, etc.), get unique values from panel data $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)) { $choices[] = [ 'value' => $array_value, 'label' => $array_value ]; } } continue; } } $choices[] = [ 'value' => $value, 'label' => $value ]; } // Remove duplicates $unique_choices = []; $seen_values = []; foreach ($choices as $choice) { if (!in_array($choice['value'], $seen_values)) { $unique_choices[] = $choice; $seen_values[] = $choice['value']; } } $choices = $unique_choices; } } // Sort choices alphabetically usort($choices, function($a, $b) { return strcmp($a['label'], $b['label']); }); echo json_encode([ 'success' => true, 'choices' => $choices, 'attribute_name' => $attribute['name'], 'attribute_type' => $attribute['type'] ]); } catch (Exception $e) { error_log("Error getting attribute choices: " . $e->getMessage()); echo json_encode([ 'success' => false, 'message' => 'Failed to load choices: ' . $e->getMessage() ]); } ?>