<?php
ini_set('include_path', '../_class/');
include('class_sql.php');
if ($_SERVER['HTTP_HOST'] == 'badmintoncoach.hu') $sql = new sql('bc_mysql','root','','badminton_coach');
else $sql = new sql('localhost','tollashodos','uprRscU8bGpJ','tollashodos');

//paraméterek: group_id, category_id
//ha nincs category_id, akkor mindenki

function get_value_parts($str) {
	$parts = explode(',', $str);
	return $parts;
}

$user_kid_query = "
SELECT 
    uk_id,
    uk_name,
    ugk_id,
    GROUP_CONCAT(distinct ugk_id) ugk_ids,
    GROUP_CONCAT(distinct ugc_id order by ugc_id) ugc_ids,
    GROUP_CONCAT(ugc_name) ugc_names,
    GROUP_CONCAT(distinct ugk_ugfv_id) ugfv_ids,
    GROUP_CONCAT(distinct if(ugf_table is null, 'null', ugf_table)) ugf_tables,
    GROUP_CONCAT(distinct if(ugf_value is null, 'null', ugf_value)) ugf_values,
    GROUP_CONCAT(distinct if(ugf_label is null, 'null', ugf_label)) ugf_labels
    
    
FROM
    user_kid
        JOIN
    user_group_kid ON ugk_user_kid_uk_id = uk_id
        LEFT JOIN
    user_group_category ON ugc_id = ugk_category_ugc_id
        JOIN
    user_group_filter_value ON ugfv_id = ugk_ugfv_id
        JOIN
    user_group_filter ON ugf_id = ugfv_filter_id
WHERE
	uk_deleted = 0 and uk_is_active = 1 and 
    ugk_user_group_ug_id = ".$_POST['group_id'].""
    .($_POST['category_id']?" AND ugk_category_ugc_id = " . $_POST['category_id']:"").
" GROUP BY uk_id
ORDER BY uk_name ASC;
";

$kid_array = $sql->assoc_array($user_kid_query);
	//var_dump($user_kid_query);

//szívás, ne módosítsuk
foreach ($kid_array as $key => $kid_value) {
	$tables = get_value_parts($kid_value['ugf_tables']);
	$values_to_write = array();
	foreach ($tables as $index => $table_name) {
		if ('null' != $table_name && $kid_value['ugc_names']) {
			$values = get_value_parts($kid_value['ugf_values']);
			$value_field = $values[$index];
			$labels = get_value_parts($kid_value['ugf_labels']);
			$label_field = $labels[$index];
			$values_to_search = get_value_parts($kid_value['ugc_names']);
			//var_dump($values_to_search);
			$value_to_search = $values_to_search[$index];
			$values_to_write[] = $sql->single_variable('select '.$label_field.' from '.$table_name.' where '.$value_field.'='.$value_to_search);
			$query = 'select '.$label_field.' from '.$table_name.' where '.$value_field.'='.$value_to_search;
		}
		else {
			$names = get_value_parts($kid_value['ugc_names']);
			$values_to_write[] = $names[$index];
		}
	}
	$final_string = implode(',', $values_to_write);
	$kid_array[$key]['ugc_names'] = $final_string;
}

echo json_encode($kid_array);

?>