<?php

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();
		$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();
		$outcomes_achieved = json_decode($course->outcomes_achieved, true);
        $outcomes_attempted = json_decode($course->outcomes_attempted, true);

        // 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 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();
		foreach($outcomes as $outcome)
		{
			$outcomes_attempted[$outcome->id]=$outcome->courses_attempted(array($course));
			$outcomes_achieved[$outcome->id]=$outcome->courses_achieved(array($course));
		}

// 		$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();
        foreach ($activities as $activity )
        {
        	if($activity->rubric_id!=NULL)
    		{
    			$rubrics[]=$activity->rubric;
    		}
        }

		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)
        	->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]=$outcome->courses_attempted($grouped_courses);
			$outcomes_achieved[$outcome->id]=$outcome->courses_achieved($grouped_courses);
		}
		
		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();
// 
//             // 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();

		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();

        $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_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();

		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();

            // 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
        {

        }
    }


}