<?php

function CustomFields($location,$table_arr='')
{	global $_SYSTEM,$DBType;
        

	if($_REQUEST['servicemod']=='mod_users/UsrFieldsProperties.php')
	{
		$custom_fields_table = 'USER_FIELDS';
	}
	elseif(($_REQUEST['servicemod']=='mod_schools/SchFieldsProperties.php') OR ($_REQUEST['servicemod']=='mod_ssetup/SchFieldsProperties.php'))
	{
		$custom_fields_table = 'SCHOOL_FIELDS';
	}
	else
	{
		$custom_fields_table = 'STUDENT_FIELDS';
	}
//var_dump($_REQUEST['month_cust_log']);
	if(is_countable($_REQUEST['month_cust_begin']) &&count($_REQUEST['month_cust_begin']))
	{
		foreach($_REQUEST['month_cust_begin'] as $field_name=>$month)
		{
			$_REQUEST['cust_begin'][$field_name] = $_REQUEST['day_cust_begin'][$field_name].'-'.$month.'-'.$_REQUEST['year_cust_begin'][$field_name];
			$_REQUEST['cust_end'][$field_name] = $_REQUEST['year_cust_end'][$field_name].'-'.$_REQUEST['month_cust_end'][$field_name].'-'.$_REQUEST['day_cust_end'][$field_name];
			if(!VerifyDate($_REQUEST['cust_begin'][$field_name]) || !VerifyDate($_REQUEST['cust_end'][$field_name]))
			{
				unset($_REQUEST['cust_begin'][$field_name]);
				unset($_REQUEST['cust_end'][$field_name]);
			}
		}
		unset($_REQUEST['month_cust_begin']);unset($_REQUEST['year_cust_begin']);unset($_REQUEST['day_cust_begin']);
		unset($_REQUEST['month_cust_end']);unset($_REQUEST['year_cust_end']);unset($_REQUEST['day_cust_end']);
	}
//var_dump($_REQUEST['cust_log']);
	//if(count($_REQUEST['cust']))
		
	if(is_countable($_REQUEST['cust']) && count($_REQUEST['cust']))
	
	{
		foreach($_REQUEST['cust'] as $key=>$value)
		{
			if($value=='')
				unset($_REQUEST['cust'][$key]);
		}
	}
	switch($location)
	{
		case 'from':
		break;
		
		case 'where':
//if(count($_REQUEST['cust']) && count($_REQUEST['cust'])  ||count$_REQUEST['cust_begin']) && count($_REQUEST['cust_begin']))
			if(is_array($_REQUEST['cust']) || is_array($_REQUEST['cust_begin']))	
	//if(is_countable($_REQUEST['cust']))  ||(is_countable($_REQUEST['cust_begin']))
	
{  
if($_SYSTEM['user_search']==true)
				$fields_table = 'USER_FIELDS';
			else
				$fields_table = 'STUDENT_FIELDS';
			$fields = db_request(db_execute("SELECT TITLE,ID,TYPE FROM ".$fields_table),array(),array('ID'));
		}

		//if(is_countable($_REQUEST['cust']) && count($_REQUEST['cust']))
			
		if(is_array($_REQUEST['cust']))
		{
			foreach($_REQUEST['cust'] as $field_name => $value)
			{
				if($value!='')
				{
					switch($fields[substr($field_name,7)][1]['TYPE'])
					{
						case 'radio':
							$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].': </b></font>';
							if($value=='Y')
							{
								$string .= " AND s.$field_name='$value' ";
								$_SYSTEM['SearchTerms'] .= _('Yes');
							}
							elseif($value=='N')
							{
								$string .= " AND (s.$field_name!='Y' OR s.$field_name IS NULL) ";
								$_SYSTEM['SearchTerms'] .= _('No');
							}
							$_SYSTEM['SearchTerms'] .= '<BR>';
						break;
						
						case 'select':
						case 'select_one':
							$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].': </b></font>';
							if($value=='!')
							{
								$string .= " and (s.$field_name='' OR s.$field_name IS NULL) ";
								$_SYSTEM['SearchTerms'] .= _('No Value');
							}
							else
							{
								$string .= " and s.$field_name='$value' ";
								$_SYSTEM['SearchTerms'] .= $value;
							}
							$_SYSTEM['SearchTerms'] .= '<BR>';
						break;

						case 'multiple':
							$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].': </b></font>';
							if($value=='!')
							{
								$string .= " AND (s.$field_name='' OR s.$field_name IS NULL) ";
								$_SYSTEM['SearchTerms'] .= _('No Value');
							}
							else
							{
								$string .= " AND s.$field_name LIKE '%||$value||%' ";
								$_SYSTEM['SearchTerms'] .= $value;
							}
							$_SYSTEM['SearchTerms'] .= '<BR>';
						break;

						
						case 'text':
							if($value=='!')
							{
								$string .= " AND (s.$field_name='' OR s.$field_name IS NULL) ";
								$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].': </b></font>'._('No Value').'<BR>';
							}
							elseif(substr($value,0,2)=='\"' && substr($value,-2)=='\"')
							{
								$string .= " AND s.$field_name='".substr($value,2,-2)."' ";
								$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].': </b></font>'.substr($value,2,-2).'<BR>';
							}
							else
							{
								$string .= " AND LOWER(s.$field_name) LIKE '".strtolower($value)."%' ";
								$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].' '._('starts with').': </b></font>'.$value.'<BR>';
							}
						break;
					}
				}
			}
		}
		if(is_countable($_REQUEST['cust_begin']) && count($_REQUEST['cust_begin']))
		{
			foreach($_REQUEST['cust_begin'] as $field_name => $value)
			{
				if($fields[substr($field_name,7)][1]['TYPE']=='numeric')
				{
					$_REQUEST['cust_end'][$field_name] = preg_replace('/[^0-9.-]+/','',$_REQUEST['cust_end'][$field_name]);
					$value = preg_replace('/[^0-9.-]+/','',$value);
				}

				if($_REQUEST['cust_begin'][$field_name]!='' && $_REQUEST['cust_end'][$field_name]!='')
				{
					if($fields[substr($field_name,7)][1]['TYPE']=='numeric' && $_REQUEST['cust_begin'][$field_name]>$_REQUEST['cust_end'][$field_name])
					{
						$temp = $_REQUEST['cust_end'][$field_name];
						$_REQUEST['cust_end'][$field_name] = $value;
						$value = $temp;
					}
					
					if($value==='0' && $_REQUEST['cust_end'][$field_name]==='0')
						$string .= " and (s.$field_name IS NULL OR s.$field_name='0') ";
					else
						$string .= " and s.$field_name BETWEEN '$value' AND '".$_REQUEST['cust_end'][$field_name]."' ";

					if($fields[substr($field_name,7)][1]['TYPE']=='date')
						$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].' '._('between').': </b></font>'.ProperDate($value).' &amp; '.ProperDate($_REQUEST['cust_end'][$field_name]).'<BR>';
					else
						$_SYSTEM['SearchTerms'] .= '<font color=gray><b>'.$fields[substr($field_name,7)][1]['TITLE'].' '._('between').': </b></font>'.$value.' &amp; '.$_REQUEST['cust_end'][$field_name].'<BR>';
				}
			}
		}
                
                
                if(substr($_REQUEST['servicemod'],0,9)=='mod_apply')
                {
                    if(count($_REQUEST['cast_faculty']))
                    {
                            if($_REQUEST['cast_faculty'])
                            {
//                                    $priority = ($_REQUEST['cast_faculty']['PRIORITY'])?'':'';
  //                                  unset($_REQUEST['cast_faculty']['PRIORITY']);
                                    foreach($_REQUEST['cast_faculty'] as $field_id=>$values)
                                    {
                                            if(empty($values))
                                                unset($_REQUEST['cast_faculty'][$field_id]);
                                    }
                            }
                            /*поиск по факультетам*/
                            $faculty="";
                            $go = false;
                            foreach($_REQUEST['cast_faculty'] as $field_id=>$values)
                            {
                                    if($field_id == 'RECOMEND_CODE' || $field_id == 'ENROLLMENT_CODE')
                                        $faculty .= " AND ssf.$field_id IN ('".implode("','",$values)."') ";
                                    else
                                        $faculty .= " AND ssf.$field_id = '$values' ";
                                    $go = true;
                                    //echo '<hr>';
                                    //var_dump($values);
                            }
                            if($go)
                                $string .= " AND EXISTS (SELECT '' FROM STUDENT_SPEC_FIELDS ssf WHERE ssf.STUDENT_ID=ssm.STUDENT_ID  ".$faculty.") ";
                            
                            //if($_SYSTEM['user_search']==true)
                            //		$string .= " AND EXISTS (SELECT '' FROM USER_LF_DATA sld WHERE sld.USER_ID=s.USER_ID AND sld.USER_FIELD_ID='".substr($field_id,7)."' ";
                            //	else
                            //		$string .= " AND EXISTS (SELECT '' FROM STUDENT_LF_DATA sld WHERE sld.STUDENT_ID=ssm.STUDENT_ID AND sld.STUDENT_FIELD_ID='".substr($field_id,7)."' ";

                            //$string .= "AND sld.$field_name LIKE '".$value."%' ";
                            
                            /*поиск по факультетам*/
                            

                    }
                }
		if(is_countable($_REQUEST['cust_log']) && count($_REQUEST['cust_log']) ||is_countable($_REQUEST['month_cust_log']) && count($_REQUEST['month_cust_log']))
		{
                        $_REQUEST['month_cust_log'] = ($_REQUEST['month_cust_log'])?$_REQUEST['month_cust_log']:array();
			foreach($_REQUEST['month_cust_log'] as $field_id=>$values)
			{
				foreach($values as $field_name=>$value)
				{
                                //    var_dump($field_id,$field_name,$value);
					//$field_id = substr($field_id,7);
					$_REQUEST['cust_log'][$field_id][$field_name]['end'] = $_REQUEST['year_cust_log'][$field_id][$field_name]['end'].'-'.$_REQUEST['month_cust_log'][$field_id][$field_name]['end'].'-'.$_REQUEST['day_cust_log'][$field_id][$field_name]['end'];
					$_REQUEST['cust_log'][$field_id][$field_name]['begin'] = $_REQUEST['year_cust_log'][$field_id][$field_name]['begin'].'-'.$_REQUEST['month_cust_log'][$field_id][$field_name]['begin'].'-'.$_REQUEST['day_cust_log'][$field_id][$field_name]['begin'];
					if(!VerifyDate($_REQUEST['cust_log'][$field_id][$field_name]['begin']) || !VerifyDate($_REQUEST['cust_log'][$field_id][$field_name]['end']))
					{
						unset($_REQUEST['cust_log'][$field_id][$field_name]['begin']);
						unset($_REQUEST['cust_log'][$field_id][$field_name]['end']);
					}
				
				}
			}
//			var_dump($_REQUEST['cust_log']);
			/* clear all empty values from the $_REQUEST */		
			if($_REQUEST['cust_log'])
			{
				foreach($_REQUEST['cust_log'] as $field_id=>$values)
				{
					foreach($values as $field_name=>$value)
					{
						if(empty($value))
							unset($_REQUEST['cust_log'][$field_id][$field_name]);
    						
						if(is_array($value))
						{		
							if($value['begin'] =='' && $value['begin'] =='')
								unset($_REQUEST['cust_log'][$field_id][$field_name]);	
						}
						
						if(empty($_REQUEST['cust_log'][$field_id]))
							unset($_REQUEST['cust_log'][$field_id]);					
					}	
				}	
			}

			foreach($_REQUEST['cust_log'] as $field_id=>$values)
			{
				$fieldId = substr($field_id,7);
				
				$logFieldsType = db_request(db_execute("SELECT 
										LOG_FIELD1,LOG_FIELD2,LOG_FIELD3,LOG_FIELD4,LOG_FIELD5,LOG_FIELD6,LOG_FIELD7,LOG_FIELD8,LOG_FIELD9,LOG_FIELD10,
										LOG_FIELD11,LOG_FIELD12,LOG_FIELD13,LOG_FIELD14,LOG_FIELD15,LOG_FIELD16,LOG_FIELD17,LOG_FIELD18,LOG_FIELD19,LOG_FIELD20														
									FROM ".$custom_fields_table."
									WHERE ID = '".$fieldId."'"));
				//need to check
//				if(in_array('select',$logFieldsType[1]) || in_array('date',$logFieldsType[1]) || in_array('numeric',$logFieldsType[1]) || in_array('text',$logFieldsType[1]))
//					continue;
				//$field_id = substr($field_id,7);
				if($_SYSTEM['user_search']==true)
					$string .= " AND EXISTS (SELECT '' FROM USER_LF_DATA sld WHERE sld.USER_ID=s.USER_ID AND sld.USER_FIELD_ID='".substr($field_id,7)."' ";
				else
					$string .= " AND EXISTS (SELECT '' FROM STUDENT_LF_DATA sld WHERE sld.STUDENT_ID=ssm.STUDENT_ID AND sld.STUDENT_FIELD_ID='".substr($field_id,7)."' ";
				foreach($values as $field_name=>$value)
				{
					if(!empty($logFieldsType[1][$field_name]))
						$fieldType = $logFieldsType[1][$field_name];
					
					if(is_array($value))
					{
						if($fieldType=='numeric')
						{
							$_REQUEST['cust_log'][$field_id][$field_name]['end'] = ereg_replace('[^0-9.-]+','',$_REQUEST['cust_log'][$field_id][$field_name]['end']);
							$_REQUEST['cust_log'][$field_id][$field_name]['begin'] = ereg_replace('[^0-9.-]+','',$_REQUEST['cust_log'][$field_id][$field_name]['begin']);
							$type = 'numeric';
						}
						elseif($fieldType=='date')
							$type = 'date';
						
						if($_REQUEST['cust_log'][$field_id][$field_name]['begin']!='' && $_REQUEST['cust_log'][$field_id][$field_name]['end']!='')
						{
							if($fieldType=='numeric')
								$type = 'numeric';
							else	
								$type = 'date';
												
							if($fieldType=='numeric' && $_REQUEST['cust_log'][$field_id][$field_name]['begin']>$_REQUEST['cust_log'][$field_id][$field_name]['end'])
							{
								$temp = $_REQUEST['cust_log'][$field_id][$field_name]['end'];
								$_REQUEST['cust_log'][$field_id][$field_name]['end'] = $_REQUEST['cust_log'][$field_id][$field_name]['begin'];
								$_REQUEST['cust_log'][$field_id][$field_name]['begin'] = $temp;
							}
							if($DBType == 'mssql')
								$string .= " AND ".db_cast(db_cast("sld.$field_name",'varchar(20)'),'DATETIME')." BETWEEN '".$_REQUEST['cust_log'][$field_id][$field_name]['begin']."' AND '".$_REQUEST['cust_log'][$field_id][$field_name]['end']."' ";
							else
								$string .= " AND sld.$field_name::$type BETWEEN '".$_REQUEST['cust_log'][$field_id][$field_name]['begin']."' AND '".$_REQUEST['cust_log'][$field_id][$field_name]['end']."' ";
						}
                                                //var_dump($string);
					}
					elseif($value)
						$string .= "AND sld.$field_name LIKE '".$value."%' ";
				}
				$string .= ')';
			}
		}
		break;
	}
	if($_REQUEST['servicemod'] == 'mod_grades/MassTeacherAssign.php' && $_REQUEST['cust'])
	{
		echo "<script langiage='javascript' type='text/javascript'>";
		echo 'document.mass_assignment.action = document.mass_assignment.action + "&cust_search=" + "'.$string.'"</script>';
		return $string;
	}else{
		return $string;
	}
}
?>