<?php
echo "<style>.hilite{background-color:".Preferences('ROLLOVER_HIGHLIGHT').";}</style>";
echo "<script>";
echo "function hilite_checked(cb, row){if(cb.checked){row.className+=' hilite'}else{row.className=row.className.replace(/hilite/g,'')};}; function check_clicked(row){var cb=row.firstChild.firstChild; cb.checked=!cb.checked; hilite_checked(cb, row); }; function CheckAll_hilite(form,value,name_like){for(i=0;i<form.elements.length;i++){	if(form.elements[i].type=='checkbox' && form.elements[i].name!='controller' && form.elements[i].name.substr(0,name_like.length)==name_like){hilite_checked(form.elements[i], form.elements[i].parentNode.parentNode);}}}";
echo "function checkAll(form,value,name_like){if(value==true)checked = true;else checked = false;for(i=0;i<form.elements.length;i++){if(form.elements[i].type=='checkbox' && form.elements[i].name!='controller' && form.elements[i].name.substr(0,name_like.length)==name_like)form.elements[i].checked = checked;}}";
echo "</script>";
echo GetBaseJavaFunc();
include_once($staticpath.'classes/Button.php');
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;
$button = new Button;

if(!$_REQUEST['include'])
		$_REQUEST['include']='sms';

if($_REQUEST['include']=='sms')
	{
		$header .= $button->createButton(_('Send SMS'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&include=sms');
		$header .= $button->createText(_('Send EMAIL'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&include=mail');
	}
else
	{
		$header .= $button->createText(_('Send SMS'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&include=sms');
		$header .= $button->createButton(_('Send EMAIL'),'modloader.php?servicemod='.$_REQUEST['servicemod'].'&include=mail');
	}

//собственно отправка
if($_REQUEST['servicefunction']=='save')
{
    
	if(count($_REQUEST['groups']))
	{
		$_SESSION['message']=$_REQUEST['message'];
		$error=$sucsess='';
                $user_contact = db_request(db_execute("SELECT USER_ID,LAST_NAME,FIRST_NAME,CFIELD_40001 as MAIL,CFIELD_40002 AS PHONE FROM USERS"),array(),array('USER_ID'));
                $student_contact = db_request(db_execute("SELECT STUDENT_ID,LAST_NAME,FIRST_NAME,CFIELD_50012 as MAIL,CFIELD_50002 AS PHONE FROM STUDENTS"),array(),array('STUDENT_ID'));
		foreach($_REQUEST['groups'] as $group_id=>$yes)
		{
			//'['.$student_id.'] SEND {'.$_REQUEST['message'].'} TO '.$_REQUEST['student_mail'][$student_id].'=>'.$yes.'<br>'
                        $students_array = db_request(db_execute("SELECT s.STUDENT_ID,NULL AS USER_ID,'student' AS PROFILE FROM STUDENTS s,STUDENT_IN_DELIVERY_GROUP sidg WHERE s.student_id=sidg.student_id and sidg.delivery_group_id='$group_id';"));
                        $users_array = db_request(db_execute("SELECT NULL AS STUDENT_ID,u.USER_ID,'user' AS PROFILE FROM USERS u,USER_IN_DELIVERY_GROUP sidg WHERE u.user_id=sidg.user_id and sidg.delivery_group_id='$group_id';"));
                        $people_in_list = array_merge($students_array,$users_array);
			if($_REQUEST['include']=='sms')
			{
                                foreach($people_in_list as $key=>$value)
                                {
                                    if($value['PROFILE']=='student')
                                    {
                                        $phone = $student_contact[$value['STUDENT_ID']][1]['PHONE'];
                                    }
                                    elseif($value['PROFILE']=='user')
                                    {
                                        $phone = $user_contact[$value['USER_ID']][1]['PHONE'];
                                    }
                                    if($phone)
                                        SendSMS($phone, $_REQUEST['message']);
                                    else
                                        $error .=_('No phone').'<br>';
                                }
			}
			elseif($_REQUEST['include']=='mail')
			{
                            foreach($people_in_list as $key=>$value)
                            {
				if($value['PROFILE']=='student')
                                {
//                                  $to_address = $student_contact[$value['STUDENT_ID']][1]['MAIL'];
                                    $to_name=$student_contact[$value['STUDENT_ID']][1]['LAST_NAME'].' '.$student_contact[$value['STUDENT_ID']][1]['FIRST_NAME'];
                                }
                                elseif($value['PROFILE']=='user')
                                {
//                                  $to_address = $user_contact[$value['USER_ID']][1]['MAIL'];
                                    $to_name=$user_contact[$value['USER_ID']][1]['LAST_NAME'].' '.$user_contact[$value['USER_ID']][1]['FIRST_NAME'];
                                }
                                    $to_address='atomov@ais-company.ru';
                                    //$to_address=$_REQUEST['student_mail'][$student_id];

                                    //$from_address = 'tomasphp@gmail.com';
                                    $from_address = $_Mail['from'];
                                    //$from_name = 'ais-company.com';
                                    $from_name = $_Mail['from_name'];
                                    $subject= $_REQUEST['title'];
                                    $letter_text = $_REQUEST['message']."\n";
                                    if(SendEmail($to_address, $to_name, $from_address, $from_name, $subject, $letter_text, $options))
                                        $sucsess .= 'Письмо успешно отправлено на ящик  '.$array[1]['MAIL'].' '.$to_address.'<br>';
                                    else
                                        $sucsess .= 'Ошибка отправки письма на ящик  '.$array[1]['MAIL'].'<br>';
                            }
			}
		}
		if(empty($error))$sucsess='Сообщениея для группы упешно отправлены';
	}
	else
		$error = _('No select group');
}
//вывод результатов
if($_REQUEST['servicefunction']!='search_servicefunction' || $error)
{
	DisplayHeader(".:".ProgramTitle().":.");
	if($error)
	{
		DisplayHeader('<IMG SRC=images/x.gif> '.$error);
		$list = '<INPUT TYPE=BUTTON id=backbutton VALUE = '._('Back').' onclick="javascript:history.go(-1);">';
		Prompt(_('Error'),'<FONT color="red">'.$error.'</FONT>',ErrorMessage($errors,'error').'<BR>'.$sucsess,'','Cel',null,null,'get',false);
	}
	if(!empty($sucsess))
	{
		DisplayHeader('<IMG SRC=images/check.gif> '.$sucsess);
		$list = '<INPUT TYPE=BUTTON id=backbutton VALUE = '._('Success').' onclick="location.href=\'modloader.php?servicemod=mod_messaging/MassSendMessageUsers.php\'">';
		Prompt(_('Success'),'<FONT color="blue">'.$sucsess.'</FONT>',ErrorMessage('','error').'<BR>','','Cel',null,null,'get',false);
		unset($_SESSION['message']);
	}
}
//if(!$error && empty($sucsess))
{
if(!isset($_REQUEST['CREATEPDF']) && $_REQUEST['search_servicefunction']!='search')
	echo TabsHeader($header,$save_button);
//Вывод поля для e-mail'a
if($_REQUEST['search_servicefunction'] == 'list')
	{
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=save&include=$_REQUEST[include] method=POST>";
				if($_REQUEST['include']=='mail')
				{
                                        echo _('Email Subject').'<INPUT TYPE="text" NAME="title" style="width:700px;"/><BR />';
					include_once($staticpath."js/fckeditor/fckeditor.php");
					$oFCKeditor = new FCKeditor('message',null,800);
					$oFCKeditor->BasePath = 'js/fckeditor/';
					$oFCKeditor->ToolbarSet = 'Letterhead';
					$oFCKeditor->Width = '800px';
					$oFCKeditor->Height = '300px';
					$oFCKeditor->Value = $_SESSION['message'];
					echo '<BR><CENTER>'.$oFCKeditor->Create().'</CENTER>';
					echo '<BR><CENTER>'.$submitButton->createIButton(_('Save')).'</CENTER>';
				}
				elseif($_REQUEST['include']=='sms')
				{
					echo '<BR><CENTER><TEXTAREA NAME="message" cols="50" rows="5" style="border:1;border-color:#F00;">'.$_SESSION['message'].'</TEXTAREA></CENTER>';
					echo '<BR><CENTER>'.$submitButton->createIButton(_('Save')).'</CENTER>';
				}
		echo '</CENTER><BR>';
        }

        $Gridoutput_options = array('save'=>false,'search'=>false,'add'=>true,'xscroll'=>false);
        $title_array = db_request(db_execute("SELECT ID as DELIVERY_GROUP_ID,NULL AS CHECKBOX,TITLE,SHORT_NAME,SORT_ORDER FROM DELIVERY_GROUP ORDER BY SORT_ORDER"));
            if(count($title_array))
            {
                    if($_REQUEST['DELIVERY_GROUP_ID'])
                    {
                            foreach($title_array as $key=>$value)
                            {

                                if($value['DELIVERY_GROUP_ID']==$_REQUEST['DELIVERY_GROUP_ID'])
                                {
                                    $title_array[$key]['row_color'] = Preferences('HIGHLIGHT');
                                }


                            }
                    }
            }
            foreach($title_array as $key=>$value)
                $title_array[$key]['CHECKBOX']='<INPUT type=checkbox name=groups['.$value[DELIVERY_GROUP_ID].'] value=Y>';
            $all = '</A><INPUT type=checkbox value=Y name=controller onclick="checkAll(this.form,this.form.controller.checked,\'groups\');"><A>';
            $one = "";
            $columns = array('CHECKBOX'=>$all,'TITLE'=>_('Delivery Group'),'SHORT_NAME'=>_('Short Name'),'SORT_ORDER'=>_('Sort Order'));
            $link =array();
            $link['TITLE']['link'] = "modloader.php?servicemod=mod_messaging/GroupsOfDelivering.php&servicefunction=$_REQUEST[servicefunction]";
            $link['TITLE']['variables'] = array('DELIVERY_GROUP_ID'=>'DELIVERY_GROUP_ID');
            unset($link['add']);
            Gridoutput($title_array,$columns,_('Groups Of Delivery'),_('Amount of Groups Of Delivery'),$link,array(),$Gridoutput_options);
            echo "<script>CheckAll_hilite(document.forms[1],true,'groups')</script></FORM>";
}
?>
