/**
 * This function is used by the remove_course_userdata function in moodlelib.
 * If this function exists, remove_course_userdata will execute it.
 * This function will remove all posts from the specified forum.
 * @param data the reset options
 * @return void
 */
function scheduler_reset_userdata($data)
{
    global $CFG, $DB;
    $status = array();
    $componentstr = get_string('modulenameplural', 'scheduler');
    $sqlfromslots = 'FROM {scheduler_slots} WHERE schedulerid IN ' . '(SELECT sc.id FROM {scheduler} sc ' . ' WHERE sc.course = :course)';
    $params = array('course' => $data->courseid);
    $strreset = get_string('reset');
    if (!empty($data->reset_scheduler_appointments) || !empty($data->reset_scheduler_slots)) {
        $slots = $DB->get_recordset_sql('SELECT * ' . $sqlfromslots, $params);
        $success = true;
        foreach ($slots as $slot) {
            // delete calendar events
            $success = $success && scheduler_delete_calendar_events($slot);
            // delete appointments
            $success = $success && $DB->delete_records('scheduler_appointment', array('slotid' => $slot->id));
        }
        $slots->close();
        // Reset gradebook.
        $schedulers = $DB->get_records('scheduler', $params);
        foreach ($schedulers as $scheduler) {
            scheduler_grade_item_update($scheduler, 'reset');
        }
        $status[] = array('component' => $componentstr, 'item' => get_string('resetappointments', 'scheduler'), 'error' => !$success);
    }
    if (!empty($data->reset_scheduler_slots)) {
        if ($DB->execute('DELETE ' . $sqlfromslots, $params)) {
            $status[] = array('component' => $componentstr, 'item' => get_string('resetslots', 'scheduler'), 'error' => false);
        }
    }
    return $status;
}
    // MUST STAY HERE, JUST BEFORE deleteallunused
    case 'deleteunused':
        $teacherClause = " AND s.teacherid = {$USER->id} ";
        /************************************ Deleting unused slots (all teachers) ************************************/
    /************************************ Deleting unused slots (all teachers) ************************************/
    case 'deleteallunused':
        if (!isset($teacherClause)) {
            $teacherClause = '';
        }
        if (has_capability('mod/scheduler:manageallappointments', $context)) {
            $sql = "\n                SELECT\n                    s.id,\n                    s.id\n                FROM\n                    {$CFG->prefix}scheduler_slots AS s\n                LEFT JOIN\n                    {$CFG->prefix}scheduler_appointment AS a\n                ON\n                    s.id = a.slotid\n                WHERE\n                    a.studentid IS NULL\n                    {$teacherClause}\n            ";
            $unappointed = get_records_sql($sql);
            $unappointedList = implode(',', array_keys($unappointed));
            delete_records_select('scheduler_slots', "schedulerid = {$cm->instance} AND id IN ({$unappointedList})");
        }
        break;
        /************************************ Deleting current teacher's slots ***************************************/
    /************************************ Deleting current teacher's slots ***************************************/
    case 'deleteonlymine':
        if ($slots = get_records_select('scheduler_slots', "schedulerid = {$cm->instance} AND teacherid = {$USER->id}", '', 'id,id')) {
            foreach ($slots as $aSlot) {
                scheduler_delete_calendar_events($aSlot);
            }
            delete_records('scheduler_slots', 'schedulerid', $cm->instance, 'teacherid', $USER->id);
            $slotList = implode(',', array_keys($slots));
            delete_records_select('scheduler_appointment', "slotid IN ({$slotList})");
            unset($slots);
        }
        break;
}
/*************************************************************************************************************/
            $vars = array('SITE' => $SITE->shortname, 'SITE_URL' => $CFG->wwwroot, 'COURSE_SHORT' => $COURSE->shortname, 'COURSE' => $COURSE->fullname, 'COURSE_URL' => $CFG->wwwroot . '/course/view.php?id=' . $COURSE->id, 'MODULE' => $scheduler->name, 'USER' => fullname($student), 'DATE' => userdate($slot->starttime, get_string('strftimedate')), 'TIME' => userdate($slot->starttime, get_string('strftimetime')), 'DURATION' => $slot->duration);
            $notification = compile_mail_template('applied', $vars);
            $notificationHtml = compile_mail_template('applied_html', $vars);
            email_to_user($teacher, $student, get_string('newappointment', 'scheduler', $SITE->shortname), $notification, $notificationHtml);
        }
    }
}
// *********************************** Disengage alone from the slot ******************************/
if ($action == 'disengage') {
    $appointments = get_records_select('scheduler_appointment', "studentid = {$USER->id} AND attended = 0");
    if ($appointments) {
        foreach ($appointments as $appointment) {
            $oldslot = get_record('scheduler_slots', 'id', $appointment->slotid);
            scheduler_delete_appointment($appointment->id, $oldslot, $scheduler);
            // notify teacher
            if ($scheduler->allownotifications) {
                $student = get_record('user', 'id', $USER->id);
                $teacher = get_record('user', 'id', $oldslot->teacherid);
                include_once $CFG->dirroot . '/mod/scheduler/mailtemplatelib.php';
                $vars = array('SITE' => $SITE->shortname, 'SITE_URL' => $CFG->wwwroot, 'COURSE_SHORT' => $COURSE->shortname, 'COURSE' => $COURSE->fullname, 'COURSE_URL' => $CFG->wwwroot . '/course/view.php?id=' . $COURSE->id, 'MODULE' => $scheduler->name, 'USER' => fullname($student), 'DATE' => userdate($oldslot->starttime, get_string('strftimedate')), 'TIME' => userdate($oldslot->starttime, get_string('strftimetime')), 'DURATION' => $oldslot->duration);
                $notification = compile_mail_template('cancelled', $vars);
                $notificationHtml = compile_mail_template('cancelled_html', $vars);
                email_to_user($teacher, $student, get_string('cancelledbystudent', 'scheduler', $SITE->shortname), $notification, $notificationHtml);
            }
        }
        // delete calendar events for that slot
        scheduler_delete_calendar_events($oldslot);
        // renew all calendar events as some appointments may be left for other students
        scheduler_add_update_calendar_events($oldslot, $course);
    }
}
/**
* This function decides if a slot should have calendar events associated with it, 
* and calls the update/delete functions if neccessary.
* it must be passed the complete scheduler_slots record to function correctly.
* The course parameter should be the record that belongs to the course for this scheduler.
* @param object $slot the slot instance
* @param object $course the actual course
*/
function scheduler_events_update($slot, $course)
{
    $slotDoesntHaveAStudent = !count_records('scheduler_appointment', 'slotid', $slot->id);
    $slotWasAttended = count_records('scheduler_appointment', 'slotid', $slot->id, 'attended', 1);
    if ($slotDoesntHaveAStudent || $slotWasAttended) {
        scheduler_delete_calendar_events($slot);
    } else {
        scheduler_add_update_calendar_events($slot, $course);
    }
}