<?php
//echo GetBaseJavaFunc();
include_once($staticpath.'classes/Button.php');
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;
$button = new Button;
DisplayHeader(".:".ProgramTitle().":.");

//if(empty($_REQUEST['profile']))
//    $_REQUEST['profile']='user';
//$profile = $_GET[profile];
if($_REQUEST['servicefunction']=='add_student' && $_POST['student'])
{
    
    $exists = db_request(db_execute("SELECT STUDENT_ID,DELIVERY_GROUP_ID FROM STUDENT_IN_DELIVERY_GROUP WHERE STUDENT_IN_DELIVERY_GROUP.DELIVERY_GROUP_ID = '$_REQUEST[DELIVERY_GROUP_ID]';"),array(),array('STUDENT_ID'));
    foreach($_POST['student'] as $student_id=>$y)
    {
        if($exists[$student_id][1]['STUDENT_ID']=='')
        {
            $sql = "INSERT INTO STUDENT_IN_DELIVERY_GROUP (STUDENT_ID,DELIVERY_GROUP_ID) VALUES ('".$student_id."','".$_REQUEST['DELIVERY_GROUP_ID']."');";
            db_execute($sql);
        }
        else
        {
            $error = true;
            $message[2] .= $student_id."<br>";
        }
    }
    if($error)
    {
        $message[1] = _("STUDENTS ALLREADY EXISTS IN THIS DELIVERY LIST:<br>");
        //DisplayBlock(_('Error'), $message);
        Prompt(_('Error'),$message[1].'<FONT color="red">'.$message[2].'</FONT>',ErrorMessage($errors,'error').'<BR>','','Cel',null,null,'get',false);
    }
    unset($_REQUEST['servicefunction']);
}
if($_REQUEST['servicefunction']=='add_user' && $_POST['user'])
{
	$exists = db_request(db_execute("SELECT USER_ID,DELIVERY_GROUP_ID FROM USER_IN_DELIVERY_GROUP WHERE USER_IN_DELIVERY_GROUP.DELIVERY_GROUP_ID = '$_REQUEST[DELIVERY_GROUP_ID]';"),array(),array('USER_ID'));
    foreach($_POST['user'] as $user_id=>$y)
    {
	if($exists[$user_id][1]['USER_ID']=='')
	{
        $sql = "INSERT INTO USER_IN_DELIVERY_GROUP (USER_ID,DELIVERY_GROUP_ID) VALUES ('".$user_id."','".$_REQUEST['DELIVERY_GROUP_ID']."');";
        db_execute($sql);
		}
	else
	{
		$error=true;
		$message[2] .= $user_id."<br>";
	}
	}
    //unset($_REQUEST['servicefunction']);
}
//Add and Update DELIVERY_GROUP
if($_REQUEST['table'] && $_POST['tables'] && $_REQUEST['servicefunction']!='remove' && $_REQUEST['DELIVERY_GROUP_ID'])
{
    switch($_REQUEST['table'])
    {
        case 'DELIVERY_GROUP':
            if($_REQUEST['DELIVERY_GROUP_ID']!='new')
            {
                foreach($_REQUEST['tables']['DELIVERY_GROUP'] as $id=>$columns)
                {
                    $sql = "UPDATE DELIVERY_GROUP SET ";
                    foreach($columns as $column=>$value)
                    {
                        $sql .= $column."='".str_replace("'","''",$value)."',";
                    }
                    $sql = substr($sql,0,-1) . " WHERE ID='$id'";
                    db_execute($sql);
//                    echo $sql;
                }
            }
            else
            {
                $sql = "INSERT INTO DELIVERY_GROUP ";
                $fields = 'ID,';
		$values = db_seq_nextval('DELIVERY_GROUP_SEQ').",";
                $go = 0;
                foreach($_REQUEST['tables']['DELIVERY_GROUP'] as $id=>$columns)
                {
                        foreach($columns as $column=>$value)
                        {
                            if($value)
                            {
                                $fields .= $column.',';
                                $values .= "'".str_replace("'","''",$value)."',";
                                $go = true;
                            }
                        }
                 }
                 $sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';
                        if($go)
                            db_execute($sql);
                           // echo $sql;
            }
        break;

    }
}
//END Add and Update DELIVERY_GROUP

// Delete DELIVERY_GROUP
$after_delete = false;
if($_REQUEST['servicefunction']=='delete')
{
	$groups_array = db_request(db_execute("SELECT '' FROM USER_IN_DELIVERY_GROUP,STUDENT_IN_DELIVERY_GROUP WHERE (USER_IN_DELIVERY_GROUP.DELIVERY_GROUP_ID = '$_REQUEST[DELIVERY_GROUP_ID]') OR (STUDENT_IN_DELIVERY_GROUP.DELIVERY_GROUP_ID = '$_REQUEST[DELIVERY_GROUP_ID]')"));
	if(count($groups_array))
	{
		$second_confirm = ErrorMessage(array(_('Groups in this category assigned to some students or users. If you delete category and groups, you will also lost the group in student information.')),'warning');
	}
	$delete_button_title = _('Delete Group Category');
	$question = '<b>'._('Do you want to delete this group category?').'</b>';
	if(Prompt(_("Delete Confirmation"), "<b>".$question."</b>", "", '', $delete_button_title, null, $second_confirm))
	{
		if($_REQUEST['DELIVERY_GROUP_ID'])
		{
			$groups_array = db_request(db_execute("SELECT ID FROM DELIVERY_GROUP WHERE ID='$_REQUEST[DELIVERY_GROUP_ID]'"));
			if(count($groups_array))
			{
//				foreach($groups_array as $group_id)
					db_execute("DELETE FROM USER_IN_DELIVERY_GROUP WHERE DELIVERY_GROUP_ID='".$_REQUEST['DELIVERY_GROUP_ID']."'");
                                        db_execute("DELETE FROM STUDENT_IN_DELIVERY_GROUP WHERE DELIVERY_GROUP_ID='".$_REQUEST['DELIVERY_GROUP_ID']."'");
			}
			db_execute("DELETE FROM DELIVERY_GROUP WHERE ID='$_REQUEST[DELIVERY_GROUP_ID]'");
			unset($_REQUEST['DELIVERY_GROUP_ID']);
                        unset($_REQUEST['delete_ok']);
                        unset($_REQUEST['servicefunction']);
                        unset($_SESSION['_REQUEST_vars']['servicefunction']);
		}
		unset($_REQUEST['servicefunction']);
//		$_REQUEST['group_title_id']=='new';
		$after_delete = true;
		$group_tid = 'new';
	}
}
//END Delete DELIVERY_GROUP

// Delete People from DELIVERY_GROUP
if($_REQUEST['servicefunction']=='delete_people')
{
 if(!empty($_REQUEST['DELIVERY_GROUP_ID']) && !empty ($_REQUEST['mess_profile']))
 {
     $error ='';
     if($_REQUEST['mess_profile']=='student')
     {
         if(empty ($_REQUEST['STUDENT_ID']))
             $error = 'Student ID is empty.';
     }
     elseif($_REQUEST['mess_profile']=='user')
     {
         if(empty ($_REQUEST['USER_ID']))
             $error = 'User ID is empty.';
     }
        $delete_button_title = _('Delete '.$_REQUEST['mess_profile'].' from delivery group');
	$question = '<b>'._('Do you want to delete this '.$_REQUEST['mess_profile'].' from delivery group?').'</b>';
	if(Prompt(_("Delete Confirmation"), "<b>".$question."</b>", "", '', $delete_button_title, null, $second_confirm))
	{
            db_execute("DELETE FROM ".strtoupper($_REQUEST['mess_profile'])."_IN_DELIVERY_GROUP WHERE ".strtoupper($_REQUEST['mess_profile'])."_ID='".$_REQUEST[strtoupper($_REQUEST['mess_profile']).'_ID']."' AND DELIVERY_GROUP_ID='$_REQUEST[DELIVERY_GROUP_ID]';");
            unset($_REQUEST['delete_ok']);
            unset($_REQUEST['servicefunction']);
            unset($_SESSION['_REQUEST_vars']['servicefunction']);
        }
    }
}
// END Delete People from DELIVERY_GROUP
#-----------------------------------------------END action-----------------------------------------------------#
#-----------------------------------------------START WIEW-----------------------------------------------------#
//TITLES
if($_REQUEST['servicefunction']!='delete' && $_REQUEST['servicefunction']!='remove')
{
    if(!$_REQUEST['servicefunction'] && $_REQUEST['DELIVERY_GROUP_ID'] && $_REQUEST['DELIVERY_GROUP_ID']!='new')
    {
        $types_array = db_request(db_execute("SELECT ID AS DELIVERY_GROUP_ID,TITLE FROM DELIVERY_GROUP ORDER BY TITLE"));
        if(count($types_array)==1 && !$_REQUEST['DELIVERY_GROUP_ID'])
            $_REQUEST['DELIVERY_GROUP_ID'] = $types_array[1]['DELIVERY_GROUP_ID'];
        if($_REQUEST['DELIVERY_GROUP_ID']!='new')
            $delete_button = "<INPUT style='width:100px;' type=button value="._('Delete')." onClick='javascript:window.location=\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete&DELIVERY_GROUP_ID=$_REQUEST[DELIVERY_GROUP_ID]\"'>";
    }
    if($_REQUEST['DELIVERY_GROUP_ID'] && $_REQUEST['DELIVERY_GROUP_ID']!='new')
    {
    	    $sql = "SELECT ID as DELIVERY_GROUP_ID,TITLE,SHORT_NAME,SORT_ORDER
                                    FROM DELIVERY_GROUP
                                    WHERE ID='$_REQUEST[DELIVERY_GROUP_ID]'";
            $QI = db_execute($sql);

            $array = db_request($QI);
            $array = $array[1];
            $course_title=$title = $array['TITLE'];
    }
    elseif($_REQUEST['DELIVERY_GROUP_ID']=='new')
            $title = _('New Mailing Group');
//END TITLES


//ADD AND CHANGE DELIVERY GROUP
    if($_REQUEST['DELIVERY_GROUP_ID'])
    {
                    echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&DELIVERY_GROUP_ID=$_REQUEST[DELIVERY_GROUP_ID]";
                    echo "&table=DELIVERY_GROUP method=POST>";
                    $_REQUEST['DrawAlign'] = 'LEFT';
                    if($after_delete === false)
                	    DisplayHeader('<B>'.$title.'</B>',$delete_button.' &nbsp; &nbsp;<INPUT style="width:100px;" type=submit value='._('Save').'>');
                    unset($_REQUEST['DrawAlign']);
                    if($after_delete === false)
                    {
	                    $header .= '<TABLE border=0 cellpadding=3 cellspacing=0 width=100%>';
    	        	    $header .= '<TR>';
        	            $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;" align=center>'.TextInput($array['TITLE'],'tables[DELIVERY_GROUP]['.$_REQUEST['DELIVERY_GROUP_ID'].'][TITLE]',_('Group Category Title'),' size=20') . '</TD>';
	                    $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">'.TextInput($array['SHORT_NAME'],'tables[DELIVERY_GROUP]['.$_REQUEST['DELIVERY_GROUP_ID'].'][SHORT_NAME]',_('Short Name'),' size=8 maxlength=8').'</TD>';
    	        	    $header .= '<TD style="border-width:2px;border-color:'.Preferences('HIGHLIGHT').';border-style:none none inset none ;">'.TextInput($array['SORT_ORDER'],'tables[DELIVERY_GROUP]['.$_REQUEST['DELIVERY_GROUP_ID'].'][SORT_ORDER]',_('Sort Order'),' size=4 maxlength=4').'</TD>';
        	            $header .= '</TR>';
                	    $header .= '</TABLE>';
                    }

    }
    else
        $header = false;

    if($header)
    {
        DisplayHeader($header);
        echo '</FORM>';
    }
//END ADD AND CHANGE TITLE DELIVERY GROUP

// DISPLAY DELIVERY GROUPS
            $Gridoutput_options = array('save'=>false,'search'=>false,'add'=>true,'xscroll'=>false);
            echo '<TABLE><TR>';
            $title_array = db_request(db_execute("SELECT ID as DELIVERY_GROUP_ID,TITLE,SHORT_NAME,SORT_ORDER FROM DELIVERY_GROUP ORDER BY SORT_ORDER"));
            if(count($title_array))
            {
                    if($_REQUEST['group_title_id'])
                    {
                            foreach($title_array as $key=>$value)
                            {
                                    if($value['DELIVERY_GROUP_ID']==$_REQUEST['DELIVERY_GROUP_ID'])
                                            $title_array[$key]['row_color'] = Preferences('HIGHLIGHT');
                            }
                    }
            }
            echo '<TD valign=top>';
            $columns = array('TITLE'=>_('Delivery Group'),'SHORT_NAME'=>_('Short Name'),'SORT_ORDER'=>_('Sort Order'));
            $link =array();
            $link['TITLE']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=$_REQUEST[servicefunction]";
            $link['TITLE']['variables'] = array('DELIVERY_GROUP_ID'=>'DELIVERY_GROUP_ID');
            $link['add']['link'] = "modloader.php?servicemod=$_REQUEST[servicemod]&DELIVERY_GROUP_ID=new";
            Gridoutput($title_array,$columns,_('Groups Of Delivery'),_('Amount of Groups Of Delivery'),$link,array(),$Gridoutput_options);
            echo '</TD>';
// END DISPLAY DELIVERY GROUPS
}

if($_REQUEST[DELIVERY_GROUP_ID] && $_REQUEST[DELIVERY_GROUP_ID]!='new')
{
//DISPLAY USER & STUDENTS IN DELIVERY GROUP
    echo '<TD valign=top align=center width="100%">';
        $students_array = db_request(db_execute("SELECT s.STUDENT_ID,NULL AS USER_ID,s.LAST_NAME,s.FIRST_NAME,s.MIDDLE_NAME,'student' AS PROFILE FROM STUDENTS s,STUDENT_IN_DELIVERY_GROUP sidg WHERE s.student_id=sidg.student_id and sidg.delivery_group_id='$_REQUEST[DELIVERY_GROUP_ID]';"));
        $users_array = db_request(db_execute("SELECT NULL AS STUDENT_ID,u.USER_ID,u.LAST_NAME,u.FIRST_NAME,u.MIDDLE_NAME,'user' AS PROFILE FROM USERS u,USER_IN_DELIVERY_GROUP sidg WHERE u.user_id=sidg.user_id and sidg.delivery_group_id='$_REQUEST[DELIVERY_GROUP_ID]';"));
        $people_in_list = array_merge($students_array,$users_array);
        $people_in_list = reindex($people_in_list);
        $link['remove'] = array('link'=>"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=delete_people&DELIVERY_GROUP_ID=$_REQUEST[DELIVERY_GROUP_ID]",'variables'=>array('STUDENT_ID'=>'STUDENT_ID','USER_ID'=>'USER_ID','mess_profile'=>'PROFILE'));
        unset($link['add']);
        Gridoutput($people_in_list,array('LAST_NAME'=>_('LAST_NAME'),'FIRST_NAME'=>_('FIRST_NAME'),'MIDDLE_NAME'=>_('MIDDLE_NAME'),'PROFILE'=>_('PROFILE')),_('Peoples In Group'),_('Amount of People In Delivery Group'),$link,array(),array('search'=>false));
    echo '</TD>';
//END DISPLAY USER & STUDENTS IN DELIVERY GROUP
}
echo '</TR></TABLE>';
//END EXISTS GROUPS & USERS



//START VIEW FOR STUDENTS AND USERS FOR ADD
if($_REQUEST[DELIVERY_GROUP_ID] && $_REQUEST[DELIVERY_GROUP_ID]!='new')
{
//DISPLAY TAB PROFILE
    if($_REQUEST['mess_profile']=='student')
    {
        $tabl .= $button->createButton(_('Students'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction='.$_REQUEST['servicefunction'].'&DELIVERY_GROUP_ID='.$_REQUEST[DELIVERY_GROUP_ID].'&mess_profile=student');
        $tabl .= $button->createText(_('Users'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction='.$_REQUEST['servicefunction'].'&DELIVERY_GROUP_ID='.$_REQUEST[DELIVERY_GROUP_ID].'&mess_profile=user');
    }
    elseif($_REQUEST['mess_profile']=='user')
    {
        $tabl .= $button->createText(_('Students'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction='.$_REQUEST['servicefunction'].'&DELIVERY_GROUP_ID='.$_REQUEST[DELIVERY_GROUP_ID].'&mess_profile=student');
        $tabl .= $button->createButton(_('Users'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction='.$_REQUEST['servicefunction'].'&DELIVERY_GROUP_ID='.$_REQUEST[DELIVERY_GROUP_ID].'&mess_profile=user');
    }
    else
    {
        $tabl .= $button->createText(_('Students'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction='.$_REQUEST['servicefunction'].'&DELIVERY_GROUP_ID='.$_REQUEST[DELIVERY_GROUP_ID].'&mess_profile=student');
        $tabl .= $button->createText(_('Users'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction='.$_REQUEST['servicefunction'].'&DELIVERY_GROUP_ID='.$_REQUEST[DELIVERY_GROUP_ID].'&mess_profile=user');
    }
    echo TabsHeader($tabl);
//END DISPLAY TAB PROFILE
    
    if($_REQUEST['mess_profile']=='user' || $_REQUEST['mess_profile']=='student')
    {
        //FORM FOR ADD
        if($_REQUEST['users_search_servicefunction']=='list')
        echo '<FORM action="modloader.php?servicemod='.$_REQUEST['servicemod'].'&servicefunction=add_'.$_GET[mess_profile].'&DELIVERY_GROUP_ID='.$_REQUEST[DELIVERY_GROUP_ID].'&mess_profile='.$_GET[mess_profile].'&users__servicefunction=list&DrawAlign=CENTER" method="POST">';
        //SETTINGS FOR SERCH
        $addition['link'] = array('FULL_NAME'=>false);
        $addition['SELECT'] = ",CAST (NULL AS CHAR(1)) AS CHECKBOX";
		$addition['functions'] = array('CHECKBOX'=>'_makeChooseCheckbox');
		$addition['columns_before'] = array('CHECKBOX'=>'</A><INPUT type=checkbox value=Y name=controller onclick="checkAll(this.form,this.form.controller.checked,\''.$_GET[mess_profile].'\');"><A>');
        $addition['action'] = "&mess_profile=".$_GET[mess_profile]."&DELIVERY_GROUP_ID=".$_REQUEST['DELIVERY_GROUP_ID'];
        $addition['options']['onclick']="check_clicked(this);";
		//END SETTINGS FOR SERCH
        //VIEW SERCH
            /*if($_GET[profile]=='user')
                $_REQUEST['users_search_servicefunction']='list';
            elseif($_GET[profile]=='student')
*/
               // $_REQUEST['search_servicefunction']='list';
		Widgets('all');
        Search($_GET[mess_profile].'_id',$addition);
				//Widgets('all');
			//$prof_pid=$_GET['profile']."_id";
			//var_dump($_GET['']);
			//echo "text for test!!";


  
 
        //END VIEW SERCH
        echo "<BR><CENTER>".$submitButton->createIButton(_('Add '.$profile.' to delivery group'))."</CENTER>";
        if($_REQUEST['users_search_servicefunction']=='list')
            echo '</FORM>';
        //END FORM FOR ADD
    }
}

function _makeChooseCheckbox($value,$title)
{	global $THIS_array;

	return "<INPUT type=checkbox name=".$_GET['mess_profile']."[".$THIS_array[strtoupper($_GET['mess_profile']).'_ID']."] value=Y>";
}
function reindex($arrays)
{
    $i = 1;
    foreach ($arrays as $index => $value) {
        $new_array[$i]=$value;
        $i++;
    }
    return $new_array;
}
?>