<?php
include_once($staticpath."/classes/Button.php");
include_once($staticpath.'classes/InputButton.php');
$submitButton = new InputButton;


//die('bvdjskbfvkjdsbj');
if(!$_REQUEST['servicefunction'] && $_REQUEST['search_servicefunction']!='list')
	unset($_SESSION['ScdTotalSchedRemove.php']);



//die('sdkgmnklngkn');
if($_REQUEST['servicefunction']=='save')
{
	if($_SESSION['ScdTotalSchedRemove.php'])
	{
		$END_DATE = $_REQUEST['year'].'-'.$_REQUEST['month'].'-'.$_REQUEST['day'];
    
    //print_r($END_DATE);die;
		if(!VerifyDate($END_DATE))
			BackPrompt(_('The date you entered is not valid'));
		$course_mp = db_request(db_execute("SELECT SCHOOL_TERM_ID FROM COURSE_SECTIONS WHERE 
        COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'"));
		
  //print_r($course_mp);die('sdgfdsg');
    
    $course_mp = $course_mp[1]['SCHOOL_TERM_ID'];
		$course_mp_table = get_school_termTable(get_school_term($course_mp,'MP_TABLE'));
		
    
    //print_r($course_mp_table);die('sfsgerg');
    
		if($course_mp_table!='FY' && $course_mp!=$_REQUEST['school_term_id'] && strpos(get_child_school_term($course_mp_table,$course_mp),"'".$_REQUEST['school_term_id']."'")===false)
			BackPrompt(_("The scheduling of a student into this course during the school term is impossible, because this course meets on ").get_school_term($course_mp).'.');
		
		$mp_table = get_school_termTable(get_school_term($_REQUEST['school_term_id'],'MP_TABLE'));

    
    
    //die('dbfjkdbfgjkdbgvjdkbjb');
    
		$current_array = db_request(db_execute("SELECT STUDENT_ID FROM STUDENT_SCHEDULE WHERE COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."' "));
   // print_r($current_array);die;
    if($current_array[$student_id] || $_REQUEST['student'])
    
    
    // print_r($current_array[$student_id]);die;
		{
    
   
			$is_student = true;
			foreach($_REQUEST['student'] as $student_id=>$yes)
			{
           
            
            
                                               /*****IOMAD UNENROLLMENT API*/
            
            /*student_id ,student name start**/
             $stud_id=db_request(db_execute("SELECT * FROM STUDENT_SCHEDULE WHERE  STUDENT_ID='".$student_id."'  
             AND COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'"));
    
              $s_id=$stud_id[1]['STUDENT_ID'];
           // print_r($s_id);die;
            /***student_id*/
          
          
            
             $stud_name=db_request(db_execute("SELECT USERNAME FROM STUDENTS WHERE STUDENT_ID='".$s_id."'"));
            
             $s_name=$stud_name[1]['USERNAME'];
            
            /*student_name,student_id end**/
            
            
            /***Fetching course_section_id,course_id,course_name start**/
            $course_section_id=db_request(db_execute("SELECT COURSE_SECTION_ID FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".$s_id."'"));
            
            $csec_id=$course_section_id[1]['COURSE_SECTION_ID'];
          // print_r($c_id);die;
            
             $course_id=db_request(db_execute("SELECT COURSE_ID FROM STUDENT_SCHEDULE WHERE COURSE_SECTION_ID='".$csec_id."'AND STUDENT_ID='".$s_id."'"));
             $c_id=$course_id[1]['COURSE_ID'];
            
            
             $course_name=db_request(db_execute("SELECT TITLE FROM COURSES WHERE COURSE_ID='".$c_id."'"));
            
              $c_name=$course_name[1]['TITLE'];
            
                     /***Fetching course_section_id,course_id,course_name end****/

            
            
               $imd_courseSQL = "SELECT * FROM mdl_course WHERE idnumber ='".$c_id ."' ";
            
           // print_r($imd_courseSQL);die;
                                   // print_r($imd_courseSQL);die('dfgdfgdhf');
                                    $IomadCourse = pg_query($iomadDBconn, $imd_courseSQL);
                					$imd_courseID = pg_fetch_all($IomadCourse)[0]['id']; 
            
                            $imd_usersSQL = "SELECT * FROM mdl_user WHERE username ='".$s_name."' "; 
                                    $IomadUser = pg_query($iomadDBconn, $imd_usersSQL);
                					$imd_StudentID = pg_fetch_all($IomadUser)[0]['id'];
            
           
                                    $enrollment_Iomad = array();
                                   
                					$form2_data =   db_request(db_execute("select * from form2 where id='9'"));
                					$enrollment_Iomad['domain'] = $form2_data[1]['URL'] ;
                					$enrollment_Iomad['token'] = $form2_data[1]['TOKEN'] ; 
                					$enrollment_Iomad['function'] = "enrol_manual_unenrol_users"; 
                					$enrollment_Iomad['course_id'] =  $imd_courseID ; 
                					$enrollment_Iomad['user_id'] = $imd_StudentID ; 
                					include_once($staticpath.'iomadAPI/enroll.php');
                				          /**************UNENROLLMENT API END*****/  
                                    
            
            
            
				//Update the Schedule table with the new END DATE
				$sql = "UPDATE STUDENT_SCHEDULE SET END_DATE = '".$END_DATE."' WHERE STUDENT_ID='".$student_id."' AND COURSE_SECTION_ID='"
                .$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'";
				db_execute($sql);
	
            //Delete from the Schedule table if END DATE is before Start Date
				if(!$current_array[$student_id])
				{
					$start_end_array = db_request(db_execute("SELECT START_DATE,END_DATE FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".$student_id."' AND COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."' AND END_DATE<START_DATE"));
					
              //print_r($start_end_array);die('fdgsdfgsd');
                
                if(count($start_end_array))
					{
						db_execute("DELETE FROM STUDENT_SCHEDULE WHERE STUDENT_ID='".$student_id."' AND COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'");
				
                
                
         
                db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS-1 WHERE COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'");
					}
				}
			}
        
    
    
    
        
        //die('dskfndsklgnsdlbgk');
			db_execute("UPDATE COURSE_SECTIONS SET FILLED_SEATS=FILLED_SEATS-1 WHERE COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'");
			unset($_REQUEST['servicefunction']);
			unset($_SESSION['ScdTotalSchedRemove.php']);
			unset($error);
			$note = _("This course has been successully terminated from the selected students' schedules.");
			$is_course = true;			
		}
		else
		{
		$is_student = false;
		$is_course = true;
	//	BackPrompt(_('You must choose a Course'));
	        if(!$is_student)
                        $error = _("This course has not been terminated from the selected students' schedules.");
                }
	}
	else
	{
		$is_course = false;
		$is_student = true;
                $error = _("No courses were choosen.");
	}
}


if($_REQUEST['servicefunction']!='choose_course')
{
	DisplayHeader(".:".ProgramTitle().":.");
	if($note)
		DisplayHeader('<IMG SRC=images/check.gif> '.$note);
        if($error && !$is_course)
                {
                        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">You have not choosen any Course Section!</FONT>',ErrorMessage($errors,'error').'<BR>'.$list,'','Cel',null,null,'get',false);
                }
        if($error && !$is_student)
                {
                        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">You have not choosen any student!</FONT>',ErrorMessage($errors,'error').'<BR>'.$list,'','Cel',null,null,'get',false);
                }

                                                                        	
	if($_REQUEST['search_servicefunction']=='list')
	{
		echo "<FORM action=modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=save method=POST>";
		DisplayHeader('',$submitButton->createSButton(_('Terminate Course for Selected Students')));
	
		echo '<CENTER><TABLE bgcolor=#'.Preferences('HIGHLIGHT_BACKGROUND').'><TR><TD><fieldset style="border:1px solid gray;"><legend><B>'._('Course to Terminate').'</B></legend><TABLE height=50><TR><TD><DIV id=course_div>';
		if($_SESSION['ScdTotalSchedRemove.php'])
		{
			$course_title = db_request(db_execute("SELECT TITLE FROM COURSES WHERE COURSE_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_id']."'"));
			$course_title = $course_title[1]['TITLE'];
			$period_title = db_request(db_execute("SELECT TITLE FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'"));
			$period_title = $period_title[1]['TITLE'];
	
			echo "$course_title - $period_title";
		}
		echo '</DIV>'."<A HREF=# onclick='window.open(\"modloader.php?servicemod=$_REQUEST[servicemod]&servicefunction=choose_course\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'>"._('Choose a Course')."</A></TD></TR></TABLE></fieldset></TD>";
		echo '<TD><fieldset style="border:1px solid gray;"><legend><B>'._('Course termination date').'</B></legend><TABLE height=50><TR><TD>'.PrepareDate(get_db_date(),'').'</TD></TR></TABLE></fieldset></TD>';
	
		echo '<TD><fieldset style="border:1px solid gray;"><legend><B>'._('School Term').'</B></legend><TABLE height=50><TR><TD>';
		echo '<SELECT name=school_term_id><OPTION value=0>'._('Full Year').'</OPTION>';
		$semesters_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,TITLE,NULL AS SEMESTER_ID FROM SCHOOL_SEMESTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		$quarters_array = db_request(db_execute("SELECT SCHOOL_TERM_ID,TITLE,SEMESTER_ID FROM SCHOOL_QUARTERS WHERE SCHOOL_YEAR='".get_school_year()."' AND SCHOOL_ID='".get_school_id()."' ORDER BY SORT_ORDER"));
		foreach($semesters_array as $mp)
			echo "<OPTION value=$mp[SCHOOL_TERM_ID]>".$mp['TITLE'].'</OPTION>';
		foreach($quarters_array as $mp)
			echo "<OPTION value=$mp[SCHOOL_TERM_ID]>".$mp['TITLE'].'</OPTION>';
		echo '</SELECT>';
		echo '</TD></TR></TABLE></fieldset></TD></TR>';
	
		echo '</TABLE></CENTER><BR>';
	}	
}



//die('dsjfhjdhgerhgi');
if(!$_REQUEST['servicefunction'])
{
	if($_REQUEST['search_servicefunction']!='list')
		unset($_SESSION['ScdTotalSchedRemove.php']);
	$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,\'student\');CheckAll_hilite(this.form,this.form.controller.checked,\'student\')"><A>');
	$addition['new'] = true;
	$addition['options']['onclick']="check_clicked(this);";
/*	Widgets('course');
	Widgets('request');
	Widgets('activity');
*/
	Widgets('all');
	Search('student_id',$addition);
	if($_REQUEST['search_servicefunction']=='list')
	{
		echo '<BR><CENTER>'.$submitButton->createSButton(_('Terminate Course for Selected Students')).'</CENTER>';
		echo "</FORM>";
	}

}

if($_REQUEST['servicefunction']=='choose_course')
{
	if($_REQUEST['course_id'])
	{
		$weights_array = db_request(db_execute("SELECT COURSE_CREDIT_TITLE FROM COURSE_CREDITS WHERE COURSE_ID='$_REQUEST[course_id]'"));
		if(count($weights_array)==1)
			$_REQUEST['course_credits'] = $weights_array[1]['COURSE_CREDIT_TITLE'];
	}
	
	if(!$_REQUEST['course_section_id'])
		include 'modules/mod_curriculum/ScdCourseProperties.php';
	else
	{
		$_SESSION['ScdTotalSchedRemove.php']['subject_id'] = $_REQUEST['subject_id'];
		$_SESSION['ScdTotalSchedRemove.php']['course_id'] = $_REQUEST['course_id'];
		$_SESSION['ScdTotalSchedRemove.php']['course_credits'] = $_REQUEST['course_credits'];
		$_SESSION['ScdTotalSchedRemove.php']['course_section_id'] = $_REQUEST['course_section_id'];
	
		$course_title = db_request(db_execute("SELECT TITLE FROM COURSES WHERE COURSE_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_id']."'"));
		$course_title = $course_title[1]['TITLE'];
		$period_title = db_request(db_execute("SELECT TITLE FROM COURSE_SECTIONS WHERE COURSE_SECTION_ID='".$_SESSION['ScdTotalSchedRemove.php']['course_section_id']."'"));
		$period_title = $period_title[1]['TITLE'];
	
		echo "<script language=javascript>opener.document.getElementById(\"course_div\").innerHTML = \"$course_title - $_REQUEST[course_credits]<BR>$period_title\"; window.close();</script>";
	}
}

function _makeChooseCheckbox($value,$title)
{	global $THIS_array;
	
	return "<INPUT onchange='hl_cb(this)' type=checkbox name=student[".$THIS_array['STUDENT_ID']."] value=Y>";
}

?>
