<?php

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redirect;

class
CoursesController extends \BaseController
{

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {

        $course = Course::with('semester')->where('id', $id)->first();
        Log::info($course->student_report_for_outcome);
        $title = $course->code . $course->number . '-' . $course->section . ' <span class="small attention">(' . $course->semester->code . ')</span>';

        // If course does not exist, display 404
        if (!$course)
            App::abort('404');

        // If course does not belong to the person
        if ($course->user_id != Auth::id())
            App::abort('403', 'Access forbidden.');

        $activities = $course->activities;
        $students = $course->students;

        //$outcomes = Outcome::orderBy('name', 'asc')->get();
        $semesters = Session::get('semesters_ids');
        $semesters = DB::table('semesters')->where('id', $course->semester_id)->orderBy('start', 'ASC')->first();

        $outcomes = Outcome::select(array('id', 'name', 'expected_outcome'))
            ->whereNull('deleted_at')
            ->whereRaw("(deactivation_date IS NULL or deactivation_date >= '{$semesters->start}')")
            ->orderBy('name', 'ASC')->get();
        $outcomes_achieved = $course->outcomes_ach();
        // $outcomes_attempted = json_decode($course->outcomes_attempted, true);

        $outcomes_attempted = $course->outcomes_att();
        // Get active semesters
        $active_semesters = array();
        $active_semesters_collection = Semester::select('id')->where('is_visible', 1)->where('start', '<=', date('Y-m-d H:i:s'))->where('end', '>=', date('Y-m-d H:i:s'))->get();
        foreach ($active_semesters_collection as $active_semester) {
            $active_semesters[] = $active_semester->id;
        }


        return View::make('local.professors.course', compact('title', 'course', 'activities', 'students', 'outcomes', 'outcomes_achieved', 'outcomes_attempted', 'active_semesters'));
    }

    public function editView()
    {
        $title = 'Create/Edit Course';
        switch (Auth::user()->role) {
            case 1:

                $programs = Program::with('school')->orderBy('name', 'asc')->get();
                $professors = User::select(array('users.id', 'first_name', 'surnames'))->orderBy('surnames', 'asc')->orderBy('first_name', 'asc')->get();
                break;
            case 2:
                $programs = Program::where("school_id", Auth::user()->school->id);
                $professors = User::fromSchool(Auth::user()->school->id)->select(array('users.id', 'first_name', 'surnames'))->orderBy('surnames', 'asc')->orderBy('first_name', 'asc')->get();
                break;
            case 3:
                $programs = Auth::user()->programs;
                $program_ids = Program::join('program_user', 'program_user.program_id', '=', 'programs.id')
                    ->where('program_user.user_id', Auth::user()->id)
                    ->lists('programs.id');

                $professors = User::fromPrograms($program_ids)->select(array('users.id', 'first_name', 'surnames'))->orderBy('surnames', 'asc')->orderBy('first_name', 'asc')->get();
                break;
        }
        //$users = User::select(array('id', 'first_name', 'surnames'))->orderBy('surnames', 'asc')->orderBy('first_name', 'asc')->get();
        $semesters = Semester::where('is_visible', '1')->orderBy('start', 'desc')->get();
        $modalities = DB::table("courses")
            ->groupBy("modality")
            ->lists("modality");

        return View::make('local.managers.shared.course_edit', compact('title', 'programs', 'professors', 'modalities', 'semesters'));
    }

    public function fetchCourses()
    {
        return Course::where('program_id', Input::get('program_id'))
            ->where('semester_id', Input::get('semester_id'))
            ->get();
    }

    private function cleanInput()
    {
        //$clean_input = array();

        $all_input = Input::all();

        $all_input["name"] = trim(preg_replace('/\t+/', '', Input::get('name')));




        return $all_input;
    }

    private function makeValidator($clean_input)
    {


        return Validator::make(
            array(
                'course_name' => $clean_input['name'],
                'course_code' => $clean_input['code'],
                'course_number'  => $clean_input['number'],
                'course_section' => $clean_input['section'],
                'program_id' => $clean_input['program'],
                'professor_id' => $clean_input['professor_id'],
                'semester_id' => $clean_input['semester_id'],

            ),
            array(
                'course_name' => 'required|string',
                'course_code' => 'required|string',
                'course_number' => "required|string",
                'course_section' => 'required|string',
                'program_id' => 'required|integer',
                "professor_id" => 'required|integer',
                "semester_id" => "required|integer"

            )

        );
    }


    public function create()
    {

        //$all_input = Input::all();

        // limpiar el input

        $all_input = $this->cleanInput();

        $validator = $this->makeValidator($all_input);

        /** If validation fails */
        if ($validator->fails()) {
            /** Prepare error message */
            $message = '<p>Error(s) creating a new Course:</p><ul>';

            foreach ($validator->messages()->all('<li>:message</li>') as $validationError) {
                $message .= $validationError;
            }

            $message .= '</ul>';

            /** Send error message and old data */
            Session::flash('status', 'danger');
            Session::flash('message', $message);
            return Redirect::to('editCourses')->withInput();
        }
        $name = $all_input['name'];
        $code = $all_input['code'];
        $number = $all_input['number'];
        $section = $all_input['section'];
        $program = $all_input['program'];
        $professor_id = $all_input['professor_id'];
        $semester_id = $all_input['semester_id'];
        //Input::file('students')//->move('course_student/', 'test.txt');



        Log::info($all_input);

        /** Instantiate new Objective */
        $course = new Course;
        $course->name = $name;
        $course->code = $code;
        $course->number = $number;
        $course->section = $section;
        $course->program_id = $program;
        $course->user_id = $professor_id;
        $course->semester_id = $semester_id;







        /** If Objective is saved, send success message */
        if ($course->save()) {

            //$students->move('./course_student', 'test.txt');

            if (Input::file('students') != '') {
                $student_nums = file(Input::file('students'));
            } else {
                $student_nums = false;
            }




            //para la validación. Si se encuentra un numero de estudiante incorrecto, 
            //set stu_not_found = true, 

            $stu_not_found = false;
            $stu_nf_list =  [];

            if ($student_nums) {
                foreach ($student_nums as $stu_num) {
                    //Log::info($stu_num);
                    //Log::info("Stunum");
                    $student_id = DB::select("select id from students where number = " . $stu_num);
                    /*DB::table("students")
                        ->where('number', '=', $stu_num)
                        ->first();
                    */
                    if (count($student_id)) {
                        $student_id = $student_id[0]->id;
                        DB::table("course_student")
                            ->insert(array(
                                'course_id' => $course->id,
                                'student_id' => $student_id,
                                'semester_id' => $course->semester_id
                            ));
                    } else {

                        $stu_not_found = true;
                        $stu_nf_list[] = $stu_num;



                        //$course->forceDelete();
                        //Session::flash('status', 'danger');
                        //Session::flash('message', '<p>Error Enrolling students. Please try again later.</p>');
                        //return Redirect::to('editCourses')->withInput();
                    }
                }
                Session::flash('status', 'success');
                Session::flash('message', 'Course created: "' . $course->name . '".');
                if ($stu_not_found) {

                    $error_msg = "<ul>";

                    foreach ($stu_nf_list as $stu_num) {
                        $error_msg .= "<li>" . $stu_num . "</li>";
                    }
                    $error_msg .= "</ul>";

                    Session::flash('status', 'warning');
                    Session::flash('message', '<p>Error Enrolling students these students</p>' . $error_msg .
                        '<p>But course ' . $course->name . ' was created</p>');
                    //return Redirect::to('editCourses')->withInput();
                }


                return Redirect::to('editCourses')->withInput();



                //fclose($student_nums);
            } else {

                Session::flash('status', 'Warning');
                Session::flash('message', '<p>Course ' . $course->name . ' created  but no student enrolled.</p>');
                return Redirect::to('editCourses')->withInput();
            }
        }

        /** If saving fails, send error message and old data */
        else {
            Session::flash('status', 'danger');
            Session::flash('message', '<p>Error creating course. Please try again later.</p>');
            return Redirect::to('editCourses')->withInput();
        }
    }

    public function updateCourseInfo()
    {

        $all_info = Input::all();
        $course = Course::findOrFail($all_info['select-course']);
        $course->name = $all_info['name'];
        $course->code = $all_info['code'];
        $course->section = $all_info['section'];
        $course->number = $all_info['number'];
        $course->program_id = $all_info['program'];
        $course->user_id = $all_info['professor_id'];
        $course->semester_id = $all_info['semester_id'];
        $course->modality = $all_info['modality'];

        if ($course->save()) {

            if (Input::file('students') != '') {
                $student_nums = file(Input::file('students'));
            } else {
                $student_nums = false;
            }
            //para la validación. Si se encuentra un numero de estudiante incorrecto, 
            //set stu_not_found = true, 

            $stu_not_found = false;
            $stu_nf_list =  [];

            if ($student_nums) {
                foreach ($student_nums as $stu_num) {

                    $if_stu_matriculado = DB::table('course_student')
                        ->where('student_id', $stu_num)
                        ->where('course_id', $course->id)
                        ->first();

                    //si está matriculado, pichea.
                    if ($if_stu_matriculado) {
                        continue;
                    }
                    $student_id = DB::select("select id from students where number = " . $stu_num);

                    if (count($student_id)) {
                        $student_id = $student_id[0]->id;
                        DB::table("course_student")
                            ->insert(array(
                                'course_id' => $course->id,
                                'student_id' => $student_id,
                                'semester_id' => $course->semester_id
                            ));
                    } else {

                        $stu_not_found = true;
                        $stu_nf_list[] = $stu_num;



                        //$course->forceDelete();
                        //Session::flash('status', 'danger');
                        //Session::flash('message', '<p>Error Enrolling students. Please try again later.</p>');
                        //return Redirect::to('editCourses')->withInput();
                    }
                }
                Session::flash('status', 'success');
                Session::flash('message', 'Course edited: "' . $course->name . '".');
                if ($stu_not_found) {

                    $error_msg = "<ul>";

                    foreach ($stu_nf_list as $stu_num) {
                        $error_msg .= "<li>" . $stu_num . "</li>";
                    }
                    $error_msg .= "</ul>";

                    Session::flash('status', 'warning');
                    Session::flash('message', '<p>Error Enrolling students these students</p>' . $error_msg .
                        '<p>But course ' . $course->name . ' was edited</p>');
                    //return Redirect::to('editCourses')->withInput();
                }


                return Redirect::to('editCourses')->withInput();



                //fclose($student_nums);
            } else {

                Session::flash('status', 'warning');
                Session::flash('message', '<p>Course ' . $course->name . ' edited  but no student enrolled.</p>');
                return Redirect::to('editCourses')->withInput();
            }
        }

        /** If saving fails, send error message and old data */
        else {
            Session::flash('status', 'danger');
            Session::flash('message', '<p>Error creating course. Please try again later.</p>');
            return Redirect::to('editCourses')->withInput();
        }



        return Redirect::to('editCourses')->withInput();
    }


    public function newShow($id)
    {
        $course = Course::findOrFail($id);
        $title = $course->name;
        $semesters = Semester::where('is_visible', '1')->orderBy('start', 'asc')->get();
        $is_active_semester = $semesters->filter(function ($semester) {
            return Semester::where('is_visible', 1)->where('start', '<=', date('Y-m-d H:i:s'))->where('end', '>=', date('Y-m-d H:i:s'))->get()->has($semester->id);
        });
        //        $active_semesters = Semester::select('id')->where('is_visible', 1)->where('start', '<=', date('Y-m-d H:i:s'))->where('end', '>=', date('Y-m-d H:i:s'))->get()->toArray()[0];
        $activities = $course->activities;

        //        var_dump($active_semesters);
        //        var_dump($course->semester->id);

        return View::make('local.managers.admins.new-course-show', compact('title', 'course', 'semesters', 'activities', 'is_active_semester'));
    }

    /**
     * Display the specified course, but with limited information.
     *
     * @param  int  $id
     * @return Response
     */
    public function showLimited($id)
    {
        $course = Course::with('semester')->where('id', $id)->first();
        $students = $course->students;
        $title = $course->code . $course->number . '-' . $course->section . ' <span class="small attention">(' . $course->semester->code . ')</span>';

        // If course does not exist, display 404
        if (!$course)
            App::abort('404');

        $activities = $course->activities;
        $students = $course->students;

        $level = DB::table('courses')
            ->join('programs', 'programs.id', '=', 'courses.program_id')
            ->where('courses.id', $id)
            ->select('programs.is_graduate')
            ->first();

        $outcomes = Outcome::active_by_semesters(array($course->semester), $level->is_graduate);
        // 		$outcomeCount = count((array)$outcomes);

        $course = Course::where('id', $id)->first();

        $results = $course->student_report_for_outcome;
        foreach ($outcomes as $outcome) {
            $outcomes_attempted[$outcome->id] = isset($results[$outcome->id]) ? $results[$outcome->id]['calculations']['student_attempted'] : 0;
            $outcomes_achieved[$outcome->id] = isset($results[$outcome->id]) ? $results[$outcome->id]['calculations']['student_achieved'] : 0;
        }

        // 		$outcomes = Outcome::orderBy('name', 'asc')->get();
        // 		$outcomes_achieved = json_decode($course->outcomes_achieved, true);
        //         $outcomes_attempted = json_decode($course->outcomes_attempted, true);

        $schools = School::all();

        $rubrics = array();
        Log::info($activities);
        foreach ($activities as $activity) {

            if (!empty($activity->rubric)) {
                $rubrics[] = $activity->rubric[0];
            }
        }

        return View::make('local.managers.shared.limited-course', compact('title', 'course', 'activities', 'students', 'outcomes', 'outcomes_achieved', 'outcomes_attempted', 'schools', 'rubrics', 'students'));
    }


    /**
     * Show grouped sections of a course
     */

    public function showGrouped($code, $number, $semester_code)
    {
        $title = $code . $number . ' (' . $semester_code . ')';
        $semester = Semester::where('code', $semester_code)->first();
        //         $selected_semesters = Semester::find(Session::get('semesters_ids'));
        $role = Auth::user()->role;
        $level = DB::table('courses')
            ->join('programs', 'programs.id', '=', 'courses.program_id')
            ->where('courses.code', $code)
            ->where('courses.number', $number)
            ->where('courses.semester_id', $semester->id)
            ->select('programs.is_graduate')
            ->first();
        //         var_dump($level); 
        //         exit();
        $grouped_courses = Course::where('code', $code)
            ->where('number', $number)
            ->where('semester_id', $semester->id)
            ->select("courses.*", DB::raw("1 as grouped"))
            ->groupBy(array('code', 'number'))->get();

        //         $outcomes = Outcome::orderBy('name', 'asc')->get();
        //         $outcomeCount = Outcome::all()->count();
        $outcomes = Outcome::active_by_semesters(array($semester), $level->is_graduate);
        $outcomeCount = count((array)$outcomes);


        foreach ($outcomes as $outcome) {
            $outcomes_attempted[$outcome->id] = 0;
            $outcomes_achieved[$outcome->id] = 0;
        }


        //foreach ($outcomes as $outcome) {
        //$outcomes_attempted[$outcome->id] = $outcome->courses_attempted($grouped_courses);
        //$outcomes_achieved[$outcome->id] = $outcome->courses_achieved($grouped_courses);

        //    $outcomes_achieved[$outcome->id]  = $results[$outcome->id]['calculations']
        //    $outcomes_attempted[$outcome->id] = $results[$outcome->id]['calculations']

        //}

        // var_dump($outcomes_attempted);
        // print "<br>";
        // var_dump($outcomes_achieved);
        // print "<br>";
        foreach ($grouped_courses as $index => $grouped_course) {
            //             // Blank outcomes for one course
            //             $outcomes_achieved = array_fill(1, $outcomeCount, 0);
            //             $outcomes_attempted = array_fill(1, $outcomeCount, 0);
            // 
            //             // Find sections for this course
            $sections = Course::where('code', $grouped_course->code)
                ->where('number', $grouped_course->number)
                ->where('semester_id', $grouped_course->semester_id)
                ->get();

            $results = $grouped_course->student_report_for_outcome;
            Log::info($results);
            foreach ($outcomes as $outcome) {
                $outcomes_attempted[$outcome->id] += isset($results[$outcome->id]) ? $results[$outcome->id]['calculations']['student_attempted'] : 0;
                $outcomes_achieved[$outcome->id] +=  isset($results[$outcome->id]) ? $results[$outcome->id]['calculations']['student_achieved'] : 0;
            }

            // 
            //             // For each of the sections, add the attempted and achieved criteria per outcome
            //             foreach ($sections as $section)
            //             {
            //                 if($section->outcomes_achieved!=NULL)
            //                 {
            //                     $section_outcomes_achieved =count($section->outcomes_attempted());
            // //                     var_dump($section_outcomes_achieved);
            // //                     exit();
            //                     $section_outcomes_attempted =count($section->outcomes_achieved());
            // //                     $section_outcomes_achieved =json_decode($section->outcomes_achieved, true);
            // //                     $section_outcomes_attempted =json_decode($section->outcomes_attempted, true);
            // 					foreach($outcomes as $outcome)
            // 					{
            // 						if(!isset($outcomes_achieved[$outcome->id]))$outcomes_achieved[$outcome->id]=0;
            // 						if(!isset($outcomes_attempted[$outcome->id]))$outcomes_attempted[$outcome->id]=0;
            //                         $outcomes_achieved[$outcome->id]+=$section_outcomes_achieved[$i];
            //                         $outcomes_attempted[$outcome->id]+=$section_outcomes_attempted[$i];					
            // 					
            // 					}
            // //                     for($i=1; $i<=count($outcomes_attempted); $i++)
            // //                     {
            // //                         $outcomes_achieved[$i]+=$section_outcomes_achieved[$i];
            // //                         $outcomes_attempted[$i]+=$section_outcomes_attempted[$i];
            // //                     }
            //                 }
            //             }
        }

        $section_ids = Course::where('code', $code)
            ->where('number', $number)
            ->where('semester_id', $semester->id)
            ->lists('id');

        //$activities = Activity::with('course')->whereNotNull('transforming_actions')->whereIn('course_id', $section_ids)->orderBy('name')->groupBy('transforming_actions')->get();

        $activities = Activity::with('course')->whereIn('course_id', $section_ids)
            ->join('activity_criterion as ac', 'ac.activity_id', '=', 'activities.id')

            //->leftJoin('transformative_activity_criterion as tac', 'ac.id', '=', 'tac.activity_criterion_id')
            //->join('transformative_actions as ta', 'ta.id', '=', 'tac.trans_action_id')
            ->select('activities.*')
            //->addSelect('ta.description as transforming_actions')
            ->distinct()
            ->orderBy('name')->get();

        return View::make('local.managers.shared.grouped_course', compact('role', 'title', 'grouped_courses', 'outcomes', 'outcomes_attempted', 'outcomes_achieved', 'sections', 'transforming_actions', 'activities'));
    }

    /**
     * Printable version for a course (grouped sections)
     */

    public function print_course($code, $number, $semester_code)
    {
        $title = $code . $number . ' (' . $semester_code . ')';
        $semester = Semester::where('code', $semester_code)->first();
        $role = Auth::user()->role;

        $grouped_courses = Course::where('code', $code)
            ->where('number', $number)
            ->where('semester_id', $semester->id)
            ->groupBy(array('code', 'number'))->get();

        //         Log::info($grouped_courses[0]->id);
        // exit();
        $level = DB::table('courses')
            ->join('programs', 'programs.id', '=', 'courses.program_id')
            ->where('courses.id', $grouped_courses[0]->id)
            ->select('programs.is_graduate')
            ->first();

        $outcomes = Outcome::active_by_semesters(array($semester), $level->is_graduate);


        //         $outcomes = Outcome::orderBy('name', 'asc')->get();
        $outcomeCount = Outcome::all()->count();

        foreach ($grouped_courses as $index => $grouped_course) {
            // Blank outcomes for one course
            $outcomes_achieved = array_fill(1, $outcomeCount, 0);
            $outcomes_attempted = array_fill(1, $outcomeCount, 0);

            // Find sections for this course
            $sections = Course::where('code', $grouped_course->code)
                ->where('number', $grouped_course->number)
                ->where('semester_id', $grouped_course->semester_id)
                ->get();

            // For each of the sections, add the attempted and achieved criteria per outcome
            foreach ($sections as &$section) {
                if ($section->outcomes_ach()) {
                    $section->outcomes_attempted = true;
                    $course_outcomes_achieved = $section->outcomes_ach();
                    $course_outcomes_attempted = $section->outcomes_att();
                    foreach ($course_outcomes_achieved as $outcome => $score) {
                        if (array_key_exists($outcome, $outcomes_achieved))
                            $outcomes_achieved[$outcome] += $score;
                        else $outcomes_achieved[$outcome] = $score;
                    }
                    foreach ($course_outcomes_attempted as $outcome => $score) {
                        if (array_key_exists($outcome, $outcomes_attempted))
                            $outcomes_attempted[$outcome] += $score;
                        else $outcomes_attempted[$outcome] = $score;
                    }
                }

                //                 if ($section->outcomes_achieved != NULL) {
                //                     $section_outcomes_achieved = json_decode($section->outcomes_achieved, true);
                //                     $section_outcomes_attempted = json_decode($section->outcomes_attempted, true);
                //                     for ($i = 1; $i <= count($outcomes_attempted); $i++) {
                //                         $outcomes_achieved[$i] += $section_outcomes_achieved[$i];
                //                         $outcomes_attempted[$i] += $section_outcomes_attempted[$i];
                //                     }
                //                 }
            }
        }

        $section_ids = Course::where('code', $code)
            ->where('number', $number)
            ->where('semester_id', $semester->id)
            ->lists('id');

        // Activities with transforming actions
        //         $activities = Activity::with('course')->whereNotNull('transforming_actions')->whereIn('course_id', $section_ids)->orderBy('name')->groupBy('transforming_actions')->get();
        $activities = Activity::with('course')->whereIn('course_id', $section_ids)->orderBy('name')->get();

        return View::make('local.managers.shared.print_course', compact('role', 'title', 'grouped_courses', 'outcomes', 'outcomes_attempted', 'outcomes_achieved', 'sections', 'activities'));
    }


    private function excelConv(&$value, $key)
    {
        Log::debug('CoursesController@excelConv');

        $value = iconv('UTF-8', 'Windows-1252//IGNORE', $value);
    }




    public function exportGrades($id)
    {
        // Find course
        $course = Course::find($id);

        // Set file name and open file
        $filename = 'olas_student_grades_' . $course->code . $course->number . $course->section . $course->semester->code . '_' . time() . '.csv';
        $file = fopen('exports/' . $filename, 'w');

        // To add an empty line to the csv
        $empty_line = array(' ');

        // Set section name at the top
        fputcsv($file, array($course->code . $course->number . $course->section . ' (' . $course->semester->code . ')'));
        fputcsv($file, $empty_line);

        // Individual activity tables -----------------------------------------

        // For each activity
        foreach ($course->assessedActivities as $activity) {
            // Set name

            $activity_name = iconv('UTF-8', 'Windows-1252//IGNORE', $activity->name);
            fputcsv($file, array($activity_name));

            // Get assessments
            //             $assessments = DB::table('assessments')
            //             	->join('students', 'assessments.student_id', '=', 'students.id')
            //             	->where('activity_id', '=', $activity->id)->orderBy('assessments.id', 'asc')->get();

            $assessments = DB::table('assessments')
                ->join('students', 'assessments.student_id', '=', 'students.id')
                ->join('activity_criterion', 'assessments.activity_criterion_id', '=', 'activity_criterion.id')
                ->where('activity_criterion.activity_id', '=', $activity->id)->orderBy('assessments.id', 'asc')->get();

            // Get rubric contents
            $rubric_contents = json_decode($activity->rubric->contents);

            $criterion_list = array('#', 'Name', 'School', 'Major');

            // Set criterion names
            foreach ($rubric_contents as $criterion) {
                $criterion_list[] = $criterion->name;
            }
            $criterion_list[] = 'Percentage';
            $criterion_list[] = 'Comments';

            // Change encoding to be compatible with Excel
            array_walk($criterion_list, array($this, 'excelConv'));

            fputcsv($file, $criterion_list);

            // Set student info and scores for each criterion
            foreach ($assessments as $assessment) {
                $student = Student::find($assessment->student_id);
                $scores = json_decode($assessment->scores, true);
                fputcsv($file, array_merge(
                    array($student->number, $student->name, $student->school_code, $student->conc_code),
                    $scores,
                    array($assessment->percentage, $assessment->comments)
                ));
            }
            fputcsv($file, $empty_line);
        }

        // Table with all activities and grades

        // Set headers for table
        $activity_list = array('#', 'Name', 'School', 'Major');
        foreach ($course->assessedActivities as $activity) {
            $activity_list[] = $activity->name;
        }
        $activity_list[] = 'Average';

        fputcsv($file, $empty_line);
        fputcsv($file, array('All Activities'));

        // Change encoding to be compatible with Excel
        array_walk($activity_list, array($this, 'excelConv'));

        fputcsv($file, $activity_list);

        // For each student, set info
        foreach ($activity->course->students as $student) {
            $student_record = array($student->number, $student->name, $student->school_code, $student->conc_code);

            $assessed_activities = $course->assessedActivities;
            // Iterate over activities, get percentages and add them to the record array
            foreach ($assessed_activities as $activity) {
                $percentage = DB::table('assessments')
                    ->select('percentage')
                    ->where('student_id', '=', $student->id)
                    ->where('activity_id', '=', $activity->id)->first();

                $student_record[] = $percentage->percentage;
            }

            // Average
            $student_record[] = array_sum(
                array_slice(
                    $student_record,
                    4,
                    count($assessed_activities)
                )
            ) / count($assessed_activities);

            fputcsv($file, $student_record);
        }

        // Close the file
        fclose($file);

        // Return response for download
        return Response::download('exports/' . $filename);
    }

    public function reassign()
    {
        $title = 'Course Management';
        $programs = Program::with('school')->orderBy('name', 'asc')->get();
        $users = User::select(array('id', 'first_name', 'surnames'))->orderBy('surnames', 'asc')->orderBy('first_name', 'asc')->get();
        $semesters = Semester::where('is_visible', '1')->orderBy('start', 'asc')->get();
        return View::make('local.managers.admins.reassign', compact('title', 'programs', 'users', 'semesters'));
    }

    public function update()
    {
        if (Input::get('reassign_program')) {
            $code = strtoupper(trim(str_replace('*', '%', Input::get('code'))));
            $number = strtoupper(trim(str_replace('*', '%', Input::get('number'))));
            $section = strtoupper(trim(str_replace('*', '%', Input::get('section'))));

            if (!$code && !$number && !$section) {
                Session::flash('status', 'danger');
                Session::flash('message', 'At least one field is required.');

                return Redirect::back()->withInput();
            }

            $update_query = Course::orderBy('code', 'asc')->orderBy('number', 'asc')->orderBy('section', 'asc');
            $fetch_query = Course::orderBy('code', 'asc')->orderBy('number', 'asc')->orderBy('section', 'asc');

            if ($code) {
                $update_query->where('code', 'LIKE', $code);
                $fetch_query->where('code', 'LIKE', $code);
            }

            if ($number) {
                $update_query->where('number', 'LIKE', $number);
                $fetch_query->where('number', 'LIKE', $number);
            }

            if ($section) {
                $update_query->where('section', 'LIKE', $section);
                $fetch_query->where('section', 'LIKE', $section);
            }
            // If section is blank, results can be grouped by code and number
            else {
                $fetch_query->groupBy(array('code', 'number'));
            }

            $affected_rows = $fetch_query->get();

            // If there are results
            if (!$affected_rows->isEmpty()) {
                // Try updating and flash success message if successful
                if ($update_query->update(array('program_id' => Input::get('program')))) {
                    Session::flash('courses', json_encode($affected_rows));
                    Session::flash('status', 'success');
                    Session::flash('message', 'Courses succesfully updated.');

                    if ($section) {
                        Session::flash('show_sections', true);
                    }
                } else {
                    Session::flash('status', 'danger');
                    Session::flash('message', 'Error reassigning courses to a program. Try again later.');
                }
            } else {
                Session::flash('status', 'warning');
                Session::flash('message', 'No courses matched your criteria. Try to broaden your search.');
            }

            return Redirect::back()->withInput();
        } elseif (Input::get('reassign_professor')) {

            $code = strtoupper(trim(str_replace('*', '%', Input::get('code_prof'))));
            $number = strtoupper(trim(str_replace('*', '%', Input::get('number_prof'))));
            $section = strtoupper(trim(str_replace('*', '%', Input::get('section_prof'))));
            $user = Input::get('user_prof');
            $semester = Input::get('semester_prof');


            if (!$code || !$number || !$section) {
                Session::flash('status', 'danger');
                Session::flash('message', 'Error assigning professor to a course. All fields are required.');

                return Redirect::back()->withInput();
            }

            $update_query = Course::where('code', '=', $code)
                ->where('number', '=', $number)
                ->where('section', '=', $section)
                ->where('semester_id', '=', $semester);
            $fetch_query = Course::where('code', '=', $code)
                ->where('number', '=', $number)
                ->where('section', '=', $section)
                ->orderBy('code', 'asc')
                ->orderBy('number', 'asc')
                ->orderBy('section', 'asc');

            $affected_rows = $fetch_query->get();

            // If there are results
            if (!$affected_rows->isEmpty()) {
                try {
                    // Try updating and flash success message if successful
                    $update_query->update(array('user_id' => $user));

                    Session::flash('status', 'success');
                    Session::flash('message', 'Successfully changed professor for ' . $code . $number . '-' . $section);
                } catch (Exception $e) {
                    Session::flash('status', 'danger');
                    Session::flash('message', 'An error occurred when changing professor for ' . $code . $number . '-' . $section) . '.';
                }
            } else {
                Session::flash('status', 'warning');
                Session::flash('message', 'No course matches your criteria. Try again with different values.');
            }

            return Redirect::back()->withInput();
        } else {
        }
    }
}