<?php

class RubricsController extends \BaseController
{

    /**
     * Show the form for creating a new rubric
     *
     * @return Response
     */
    public function newRubric($activity_id)
    {
        $activity = Activity::find($activity_id);

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

        $title = 'Rubric for <em>' . $activity->name . '</em>';

        // Select templates that belong to everyone or belong to the activity's course's school
        $templates = Template::where('is_visible', '=', 1)
            ->where(function ($query) use ($activity) {
                if (Auth::user()->role != 1) {
                    $query
                        ->where('school_id', $activity->course->program->school->id)
                        ->orWhere('school_id', '=', NULL);
                }
            })
            ->orderBy('name', 'ASC')->get();

        $rubrics = Auth::user()->rubrics;
        $outcomes = Outcome::orderBy('name', 'ASC')->get();
        $criteria = Criterion::orderBy('name', 'ASC')->get();
        $rubric = $activity->rubric;
        Log::info($rubric);



        return View::make('local.professors.rubrics', compact('title', 'templates', 'outcomes', 'criteria', 'rubrics', 'activity', 'rubric'));
    }

    public function newOtherMethod($activity_id)
    {
        $activity = Activity::find($activity_id);

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

        $title = 'Rubric for <em>' . $activity->name . '</em>';

        // Select templates that belong to everyone or belong to the activity's course's school
        $templates = Template::where('is_visible', '=', 1)
            ->where(function ($query) use ($activity) {
                if (Auth::user()->role != 1) {
                    $query
                        ->where('school_id', $activity->course->program->school->id)
                        ->orWhere('school_id', '=', NULL);
                }
            })
            ->orderBy('name', 'ASC')->get();

        $rubrics = Auth::user()->rubrics;
        $outcomes = Outcome::orderBy('name', 'ASC')->get();
        $criteria = Criterion::orderBy('name', 'ASC')->get();
        $rubric = $activity->rubric;

        return View::make('local.professors.rubrics', compact('title', 'templates', 'outcomes', 'criteria', 'rubrics', 'activity', 'rubric'));
    }

    /**
     * Save a new rubric
     *
     * @return Response
     */
    public function create()
    {

        DB::beginTransaction();


        // Get rubric contents

        $scales = Input::get('scales');
        $criteria = Input::get('criteria');

        // Process rubric
        $rubric = new Rubric;
        $rubric->name = Input::get('name');

        $rubric->expected_percentage = Input::get('expected_percentage');
        $rubric->expected_points = Input::get('expected_points');
        $rubric->user_id = Auth::id();
        $rubric->num_scales = count($scales[0]);
        $rubric->max_score = Input::get('max_score');
        $defaultWeight = round(100 / count($criteria), 2);

        if ($rubric->save()) {

            // Process activity
            //             $activity = Activity::find(Input::get('activity_id'));
            //             $activity->rubric_id = $rubric->id;
            //             $activity->save();

            DB::table('rubric_activity')->insert(array('activity_id' => Input::get('activity_id'), 'rubric_id' => $rubric->id));
            DB::commit();

            $rubricId = $rubric->id;
            foreach ($criteria as $index => $criterion_id) {
                DB::insert("insert into criterion_rubric (`rubric_id`,`criterion_id`) values ({$rubricId},{$criterion_id})");
                DB::commit();
                $rubric_criterion_id = DB::table('criterion_rubric')->where('rubric_id', '=', $rubricId)
                    ->where('criterion_id', '=', $criterion_id)->first();



                for ($i = 0; $i < count($scales[$index]); $i++) {
                    $scale =  Scale::where('description', '=', $scales[$index][$i])->first();
                    Log::info($scale);
                    if ($scale) {
                        DB::insert("insert into `rubric_criteria_scale` (`rubric_criterion_id`, `scale_id`, `position`) values ({$rubric_criterion_id->id},{$scale->id}, {$i})");
                        DB::commit();
                    } else {
                        $scale = new Scale;
                        $scale->description = $scales[$index][$i];

                        if ($scale->save()) {
                            DB::insert("insert into `rubric_criteria_scale` (`rubric_criterion_id`, `scale_id`, `position`) values ({$rubric_criterion_id->id},{$scale->id}, {$i})");
                            DB::commit();
                        } else {
                            Session::flash('status', 'danger');
                            Session::flash('message', 'Rubric could not be created.');
                        }
                    }
                }

                $activity_id = Input::get("activity_id");
                DB::insert("insert into `activity_criterion` (`activity_id`,`criterion_id`, `weight`) values ({$activity_id}, {$criterion_id}, {$defaultWeight})");
                DB::commit();
            }
            Session::flash('status', 'success');
            Session::flash('message', 'Rubric assigned.');

            return action('ActivitiesController@show', array(Input::get('activity_id')));
        } else {
            DB::rollBack();
            Session::flash('status', 'danger');
            Session::flash('message', 'Error creating Rubric. Try again later.' . $e);
        }
    }


    /**
     * Return a specific template
     *
     * @return Template
     */
    public function fetch()
    {
        return Rubric::find(Input::get('id'));
    }

    /**
     * Update a rubric
     *
     * @return Response
     */
    public function update()
    {
        Log::info('entré???');
        $rubric = Rubric::find(Input::get('id'));

        $scales = Input::get('scales');
        $criteria = Input::get('criteria');

        // Process rubric
        $rubric->name = Input::get('name');

        $rubric->expected_percentage = Input::get('expected_percentage');
        $rubric->expected_points = Input::get('expected_points');

        $rubric->num_scales = count($scales[0]);
        $rubric->max_score = Input::get('max_score');
        $defaultWeight = round(100 / count($criteria), 2);


        DB::beginTransaction();


        // Get associated activity
        //$activity = Activity::where('rubric_id', '=', $rubric->id)->first();

        $activity_id = DB::table('activities')
            ->join('rubric_activity', 'rubric_activity.activity_id', '=', 'activities.id')
            ->where('rubric_id', '=', $rubric->id)
            ->first();

        $activity = Activity::where('id', '=', $activity_id->activity_id)->first();



        // If the associated activity has been assessed, delete the records
        if ($activity->outcomes_attempted != NULL) {
            DB::table('assessments')->where('activity_id', '=', $activity->id)->delete();
            $activity->criteria_achieved_percentage = NULL;
            $activity->criteria_achieved = NULL;
            $activity->outcomes_achieved = NULL;
            $activity->outcomes_attempted = NULL;
        }
        Log::info('entré3???');

        $rubric->save();
        Log::info("????");
        $activity->save();
        Log::info("????22");
        // Get all the course's activities
        Log::info($activity->course);
        $course = Course::find($activity->course->id);
        $activities = $course->activities;

        // Check if any assessed activities remain
        $remainingAssessed = false;
        foreach ($course->activities as $activity) {
            if ($activity->outcomes_attempted != NULL) {
                $remainingAssessed = true;
                break;
            }
        }
        Log::info('entré4???');

        //If there are still evaluated activities in the course, recalculate course outcomes
        if (!$activities->isEmpty() && $remainingAssessed) {
            // Variables to hold recalculated outcomes for the course
            $course_outcomes_attempted = array_fill(1, Outcome::all()->count(), 0);
            $course_outcomes_achieved = array_fill(1, Outcome::all()->count(), 0);

            // For each activity
            foreach ($activities as $activity) {
                // If activity has been assessed
                if ($activity->outcomes_attempted != NULL) {
                    // Get the achieved criteria
                    $criteria_achievement = json_decode($activity->criteria_achieved, true);
                    foreach ($criteria_achievement as $criterion_id => $criterion_achieved) {
                        // Find corresponding learning outcome;
                        $criterion = Criterion::find($criterion_id);
                        $outcome = Outcome::find($criterion->outcome_id);

                        // If criterion is achieved (1), add 1 to both arrays
                        if ($criterion_achieved === 1) {
                            $course_outcomes_attempted[$outcome->id] += 1;
                            $course_outcomes_achieved[$outcome->id] += 1;
                        }
                        // Else, only add to the attempted outcomes arrays
                        elseif ($criterion_achieved === 0) {
                            $course_outcomes_attempted[$outcome->id] += 1;
                        }
                    }
                }
            }
            Log::info('entré5???');
            // Update course
            $course->outcomes_achieved = json_encode($course_outcomes_achieved);
            $course->outcomes_attempted = json_encode($course_outcomes_attempted);
        } else {
            // Update course
            $course->outcomes_achieved = NULL;
            $course->outcomes_attempted = NULL;
        }

        $course->save();
        Log::info('entré6???');
        DB::delete("delete from criterion_rubric where rubric_id ={$rubric->id}");
        DB::delete("delete from activity_criterion where activity_id = {$activity->id}");
        foreach ($criteria as $index => $criterion_id) {
            if (

                DB::insert("insert into criterion_rubric (`rubric_id`, `criterion_id`) values ({$rubric->id}, {$criterion_id}) ")
                &&  DB::insert("insert into `activity_criterion` (`activity_id`,`criterion_id`, `weight`) values ({$activity->id}, {$criterion_id}, {$defaultWeight})")
            ) {

                $rubric_criterion_id =  DB::table('criterion_rubric')
                    ->where('rubric_id', '=', $rubric->id)
                    ->where('criterion_id', '=', $criterion_id)
                    ->first();

                foreach ($scales[$index] as $in => $scale) {
                    Log::info("AH2");
                    $new_scale =  Scale::where('description', '=', $scale)->first();

                    if ($new_scale) {
                        DB::insert("insert into `rubric_criteria_scale` (`rubric_criterion_id`, `scale_id`, `position`) values ({$rubric_criterion_id->id},{$new_scale->id}, {$in})");
                        DB::commit();
                    } else {
                        $new_scale = new Scale;
                        $new_scale->description = $scales[$index][$in];
                        if ($new_scale->save()) {
                            DB::insert("insert into `rubric_criteria_scale` (`rubric_criterion_id`, `scale_id`, `position`) values ({$rubric_criterion_id->id},{$new_scale->id}, {$in})");
                            DB::commit();
                        } else {
                            DB::rollBack();
                            Session::flash('status', 'danger');
                            Session::flash('message', 'Rubric could not be created.');
                            return action('ActivitiesController@show', array($activity->id));
                        }
                    }
                }
            } else {
                DB::rollBack();
                Session::flash('status', 'danger');
                Session::flash('message', 'Rubric could not be created.');
                return action('ActivitiesController@show', array($activity->id));
            }
        }
        Log::info('entré7???');

        DB::commit();


        Session::flash('status', 'success');
        Session::flash('message', 'Rubric updated.');

        return action('ActivitiesController@show', array($activity->id));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return Response
     */
    public function destroy()
    {
        $rubric = Rubric::find(Input::get('id'));

        if ($rubric->delete()) {
            Session::flash('status', 'success');
            Session::flash('message', 'Rubric deleted.');
        } else {
            Session::flash('status', 'danger');
            Session::flash('message', 'Error: The rubric could not be deleted. Try again later.');
        }

        return;
    }

    /**
     * Show a specific rubric
     *
     * @return Response
     */
    public function show($activity_id)
    {
        $activity = Activity::find($activity_id);
        // Get activity's course
        $course = Course::where('id', '=', $activity->course_id)->firstOrFail();

        // If activity does not belong to the requesting user, display 403
        if ($course->user_id != Auth::id())
            App::abort('403', 'Access Forbidden');
        Log::info($activity->rubric[0]->id);

        $rubric = Rubric::where('id', '=', $activity->rubric[0]->id)->firstOrFail();
        $criterion_rubric = DB::table('criteria')
            ->join('criterion_rubric', 'criterion_rubric.criterion_id', '=', 'criteria.id')
            ->where('criterion_rubric.rubric_id', '=', $activity->rubric[0]->id)
            ->get();
        Log::info($criterion_rubric);

        foreach ($criterion_rubric as $single_cr) {
            $single_cr->scales = json_encode(DB::table('scales')
                ->join('rubric_criteria_scale', 'rubric_criteria_scale.scale_id', '=', 'scales.id')
                ->where('rubric_criteria_scale.rubric_criterion_id', '=', $single_cr->id)
                ->orderBy('position')
                ->lists('description'));
            $single_cr->outcomes = json_encode(DB::table('outcomes')
                ->join('criterion_objective_outcome', 'outcomes.id', '=', 'criterion_objective_outcome.outcome_id')
                ->where('criterion_objective_outcome.criterion_id', '=', $single_cr->criterion_id)->lists('name'));
        }


        Log::info($criterion_rubric);

        $title = $activity->name . ': ' . $rubric->name;
        return View::make('local.professors.viewrubric', compact('rubric', 'activity', 'criterion_rubric', 'title', 'course'));
    }

    /**
     * Show a specific rubric without some course and user information
     *
     * @return Response
     */
    public function show_limited($rubric_id)
    {
        // If user is a professor, display 403.
        if (Auth::user()->role == 4)
            App::abort('403', 'Access Forbidden');

        $rubric = Rubric::where('id', '=', $rubric_id)->firstOrFail();
        $title = $rubric->name;
        $role = Auth::user()->role;
        return View::make('local.managers.shared.view_rubric_limited', compact('rubric', 'title', 'role'));
    }

    public function download($activity_id, $rubric_id)
    {
        $activity = Activity::find($activity_id);
        // Get activity's course
        $course = Course::where('id', '=', $activity->course_id)->firstOrFail();

        // If activity does not belong to the requesting user, display 403
        if ($course->user_id != Auth::id())
            App::abort('403', 'Access Forbidden');

        $rubric = Rubric::where('id', '=', $activity->rubric_id)->firstOrFail();
        $title = $activity->name . ': ' . $rubric->name;
        return View::make('local.professors.downloadrubric', compact('rubric', 'activity', 'title', 'course'));
    }

    public function printview($activity_id, $rubric_id)
    {
        $activity = Activity::find($activity_id);
        // Get activity's course
        $course = Course::where('id', '=', $activity->course_id)->firstOrFail();

        // If activity does not belong to the requesting user, display 403
        if ($course->user_id != Auth::id())
            App::abort('403', 'Access Forbidden');

        $rubric = Rubric::where('id', '=', $activity->rubric_id)->firstOrFail();
        $title = $activity->name . ': ' . $rubric->name;
        return View::make('local.professors.printrubric', compact('rubric', 'activity', 'title', 'course'));
    }

    public function fetchRubricCriterion()
    {
        $rubric = DB::table("rubric_criteria_scale")
            ->join('scales', 'scales.id', '=', 'rubric_criteria_scale.scale_id')
            ->where("rubric_criterion_id", '=', Input::get('rubric_criterion_id'))->get();
        Log::info($rubric);

        $rubric["criteria"] = DB::table("criteria")
            ->join("criterion_rubric", 'criterion_rubric.criterion_id', '=', 'criteria.id')
            ->where("criterion_rubric.id", '=', Input::get('rubric_criterion_id'))
            ->select('name', 'criterion_rubric.notes')
            ->first();
        return json_encode($rubric);

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

        //foreach ($rubric_contents as $key => $criterion) {
        //    if ($criterion->id == $criterion_id) {
        //        return json_encode($criterion);
        //    }
    }
}