<?php

/*
	function for clearing text from the 'Pull-Down/Select Multiple Choices' textarea
	and making an options count
*/
function _clearPullDown($val) 
{
	unset($_SESSION['pullDownOptionsCount']);
	$optCount = _returnOptionsCount($val);	
	if($optCount == 1)
	{
		$val = _clearOptionFromEmptyLines($val);
		$val = str_replace("\n","", $val);
	}
	else 
	{
		$val = _clearOptionFromEmptyLines($val);	
	}
	$_SESSION['pullDownOptionsCount'] = $optCount;	
	return $val;
}

function _clearCodesPullDown($val)
{
	unset($_SESSION['codesPullDownOptionsCount']);
	$codesOptCount = _returnOptionsCount($val);	
	if($codesOptCount == 1)
	{
		$val = _clearOptionFromEmptyLines($val);
		$val = str_replace("\n","", $val);	
	}
	else
	{
		$val = _clearOptionFromEmptyLines($val); 	
	}
	$_SESSION['codesPullDownOptionsCount'] = $codesOptCount;	
	return $val;
}

/*
check counts - return 1, if qty of options in the 'Pull-Down/Select Multiple Choices' ==
qty of options in the 'Codes for Pull-Down/Select Multiple Choices'
0 - if counts are not equal 
*/
function _checkQtyOfPullDown()
{
	if(!empty($_SESSION['codesPullDownOptionsCount']))
	{
		if($_SESSION['codesPullDownOptionsCount'] == $_SESSION['pullDownOptionsCount'])
			return 1;
		else
			return 0;
	}
	return 1;	
}


function _returnOptionsCount($optionsArr)
{
	$count = 0;
	$optionsArr = explode("\n", $optionsArr);
/*
	we will make the array from our string, and will count its options qty
*/
	foreach ($optionsArr as $item)
	{	
		$item = trim($item);
		if($item != '')
		{
			$count++;
		}
		else
		{
			continue;
		}
	}
	return $count;
}

/*
clear the string with options form the empty lines, if it exist
*/

function _clearOptionFromEmptyLines($string)
{
	$string = explode("\n", $string);
	foreach ($string as $item)
	{	
		$item = trim($item);
		if($item != '')
		{
			$str .= $item."\n";
		}
		else
		{
			continue;
		}
	}
	
	$str = substr($str, 0, -1); 
	//$str = str_replace("\n","", $str);
	return $str;
}

/*
if one of the pull-down options  
is changed, it updates the students who had the old option in that  
field so that they now have the new option. Or remove the value from the 'student' table, if
the option has been deleted.

return int - if some values was changed, 0 - if no
*/

function _checkAndReplaceOldOptions($newValuesArr)
{
	global $custom_fields_table, $students_table, $student_id_field;
	$newValuesArr = explode("\n", $newValuesArr);

	/*
	check, if user deleted some values from the Pull-Down/Select Multiple Choices field
	$_SESSION['oldOptionsArr'] - contains the old values
	$newValuesArr - new values
	*/
	$diffArr = array_diff($_SESSION['oldOptionsArr']['OPTIONS'], $newValuesArr);
	$updCount = 0;
	
	foreach($diffArr as $key => $value)
	{
		$res = _checkOptionExists($_SESSION['oldOptionsArr']['ID'], $value);
		
		if($res)
		{
			foreach ($res as $resItem)
			{
				$valForInsert = $newValuesArr[$key];
				$fieldType = _getFieldType($_SESSION['oldOptionsArr']['ID']);
				if($fieldType === 'multiple')
				{
					//$value contains the old option, which we need to change
					$valForInsert = _parseMultipleOptions($resItem["CFIELD_".$_SESSION['oldOptionsArr']['ID'].""], $newValuesArr[$key], $value);
				}
			
				if(_updateOptions($_SESSION['oldOptionsArr']['ID'], $valForInsert, $resItem[$student_id_field]))
				$updCount++;
				
				/* i.e. this option was removed 
				if(!isset($newValuesArr[$key]))
				{
					if(_updateOptions($_SESSION['oldOptionsArr']['ID'], '', $resItem['STUDENT_ID']))
					$updCount++;
				} */
			}
		}
	}
	
	if($updCount)
		return $updCount;
	else 
		return 0;
}

/*
check, if option exists in the 'student' table
*/
function _checkOptionExists($fieldId, $fieldValue)
{
	global $custom_fields_table, $students_table, $student_id_field;
	$sqlQuery = "SELECT ".$student_id_field.", cfield_".$fieldId ." FROM ".$students_table." WHERE cfield_".$fieldId." LIKE '%".$fieldValue."%'";
	
	$studentValuesRes = db_request(db_execute($sqlQuery));
	if($studentValuesRes)
	{
		return $studentValuesRes;
	}
	else 
	{
		return 0;
	}
}

function _updateOptions($fieldId, $newVal, $studentId)
{
	global $custom_fields_table, $students_table, $student_id_field;
	$sqlUpdQuery = "UPDATE ".$students_table." SET cfield_".$fieldId." = '".$newVal."' WHERE ".$student_id_field." = '".$studentId."'";
	if(db_execute($sqlUpdQuery))
		return 1;
	else 
		return 0;
}

/*
get field type - we need because 'multiple' field values stored as ||value||value1||.
we need to parse this string, change old value to the new one and save it back

return string, with field type or 0 if there was an error
*/
function _getFieldType($fieldId) 
{
	global $custom_fields_table, $students_table, $student_id_field;
	$sqlQuery = "SELECT type FROM ".$custom_fields_table." WHERE id = ".$fieldId."";
	$fieldValuesRes = db_request(db_execute($sqlQuery));
	if($fieldValuesRes)
	{
		return $fieldValuesRes[1]['TYPE']; //return string with type
	}
	else 
	{
		return 0;
	}
}


/*
parse string from the Multiple field
*/
function _parseMultipleOptions($oldValuesFromDB, $newValue, $oldValue)
{
	$str = substr($oldValuesFromDB,2);
	$str = substr($str,0,-2);
	$str = explode("||", $str);
	$newString = '||';
	foreach ($str as $item)
	{
		if($item === $oldValue)
		{	
			$newString .= $newValue.'||';
		}
		else
		{	
			$newString .= $item.'||';
		}
	}	
	return	$newString;
}
?>