<?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
        $usable_templates = DB::table('templates')
            ->join('template_criterion', 'template_criterion.template_id', '=', 'templates.id')
            ->join('criterion_objective_outcome', 'criterion_objective_outcome.criterion_id', '=', 'template_criterion.criterion_id')
            ->join('program_criterion_objective_outcome', 'criterion_objective_outcome.id', '=', 'program_criterion_objective_outcome.cri_obj_out_id')
            ->where('objective_id', '<>', 0)
            ->where('program_criterion_objective_outcome.program_id', $activity->course->program->id)
            ->groupBy('template_id')
            ->lists('template_id');
        $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)
                        ->orWhere('program_id', '=', $activity->course->program->id);
                }
            })
            ->join('template_criterion', 'template_criterion.template_id', '=', 'templates.id')
            ->join('criterion_objective_outcome', 'template_criterion.criterion_id', '=', 'criterion_objective_outcome.criterion_id')
            ->where('objective_id', '<>', 0)
            ->groupBy("templates.id")
            ->select('templates.*')
            //->join('program_criterion_objective_outcome_id','')
            //->whereIn('templates.id', $usable_templates)

            ->orderBy('name', 'ASC')->get();

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



        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

        $titles = Input::get('titles');
        $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($titles);
        $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();
            $activity_id = Input::get("activity_id");


            $rubricId = $rubric->id;
            foreach ($criteria as $index => $criterion_id) {
                DB::insert("insert into rubric_criterion (`rubric_id`,`criterion_id`, `position`) values ({$rubricId},{$criterion_id}, {$index})");
                DB::commit();






                DB::insert("insert into `activity_criterion` (`activity_id`,`criterion_id`, `weight`) values ({$activity_id}, {$criterion_id}, {$defaultWeight})");
                DB::commit();
            }

            foreach ($titles as $index => $id) {
                DB::insert("insert into `rubric_title` (`rubric_id`, `title_id`, `position`) values ({$rubricId}, {$id}, {$index} )");
                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()
    {

        $rubric = Rubric::find(Input::get('id'));

        $titles = Input::get('titles');
        $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($titles);
        $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;
        }*/


        $rubric->save();

        $activity->save();

        // 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 rubric_criterion where rubric_id ={$rubric->id}");
        DB::delete("delete from activity_criterion where activity_id = {$activity->id}");
        DB::delete("delete from rubric_title where rubric_id = {$rubric->id}");
        foreach ($criteria as $index => $criterion_id) {


            $result =  DB::insert("insert into rubric_criterion (`rubric_id`, `criterion_id`, `position`) values ({$rubric->id}, {$criterion_id}, {$index}) ");
            $result2 = DB::insert("insert into `activity_criterion` (`activity_id`,`criterion_id`, `weight`) values ({$activity->id}, {$criterion_id}, {$defaultWeight})");
            if (!($result || $result2)) {
                DB::rollBack();
                Session::flash('status', 'danger');
                Session::flash('message', 'Rubric could not be created.');
                return action('ActivitiesController@show', array($activity->id));
            }
        }

        foreach ($titles as $index => $id) {
            DB::insert("insert into rubric_title (`rubric_id`, `title_id`, `position`) values ({$rubric->id},{$id},{$index}) ");
        }
        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
        //         Log::info("actv".$activity);
        $course = Course::where('id', '=', $activity->course_id)->firstOrFail();
        //         Log::info("user".$course->user_id);

        // If activity does not belong to the requesting user, display 403
        if ($course->user_id != Auth::id())
            App::abort('403', 'Access Forbidden');
        //         Log::info("rubric".$activity->rubric);
        // exit();
        $rubric = Rubric::where('id', '=', $activity->rubric[0]->id)->firstOrFail();
        $rubric_criterion = DB::table('criteria')
            ->join('rubric_criterion', 'rubric_criterion.criterion_id', '=', 'criteria.id')
            ->where('rubric_criterion.rubric_id', '=', $activity->rubric[0]->id)
            ->get();
        Log::info($rubric_criterion);

        $rubric->titles = DB::table('titles')
            ->join('rubric_title', 'rubric_title.title_id', '=', 'titles.id')
            ->where('rubric_title.rubric_id', $rubric->id)
            ->lists('text');

        foreach ($rubric_criterion as $single_cr) {
            $single_cr->scales = json_encode(DB::table('scales')
                ->join('criterion_scale', 'criterion_scale.scale_id', '=', 'scales.id')
                ->where('criterion_scale.criterion_id', '=', $single_cr->criterion_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($rubric_criterion);

        $title = $activity->name . ': ' . $rubric->name;
        return View::make('local.professors.viewrubric', compact('rubric', 'activity', 'rubric_criterion', '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();
        $rubric_criterion = DB::table('criteria')
            ->join('rubric_criterion', 'rubric_criterion.criterion_id', '=', 'criteria.id')
            ->where('rubric_criterion.rubric_id', '=', $rubric->id)
            ->get();
        $rubric->titles = DB::table('titles')
            ->join('rubric_title', 'rubric_title.title_id', '=', 'titles.id')
            ->where('rubric_title.rubric_id', $rubric->id)
            ->orderBy('position')
            ->lists('text');

        foreach ($rubric_criterion as $single_cr) {
            $single_cr->scales = DB::table('scales')
                ->join('criterion_scale', 'criterion_scale.scale_id', '=', 'scales.id')
                ->where('criterion_scale.criterion_id', '=', $single_cr->criterion_id)
                ->orderBy('position')
                ->lists('description');
            $single_cr->outcomes = 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');
        }
        $title = $rubric->name;
        $role = Auth::user()->role;
        return View::make('local.managers.shared.view_rubric_limited', compact('rubric', 'rubric_criterion', '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();
        $rubric_criterion = DB::table('criteria')
            ->join('rubric_criterion', 'rubric_criterion.criterion_id', '=', 'criteria.id')
            ->where('rubric_criterion.rubric_id', '=', $activity->rubric[0]->id)
            ->get();
        $rubric->titles = DB::table('titles')
            ->join('rubric_title', 'rubric_title.title_id', '=', 'titles.id')
            ->where('rubric_title.rubric_id', $rubric->id)
            ->orderBy('position')
            ->lists('text');

        foreach ($rubric_criterion as $single_cr) {
            $single_cr->scales = json_encode(DB::table('scales')
                ->join('criterion_scale', 'criterion_scale.scale_id', '=', 'scales.id')
                ->where('criterion_scale.criterion_id', '=', $single_cr->criterion_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'));
        }
        $title = $activity->name . ': ' . $rubric->name;
        return View::make('local.professors.downloadrubric', compact('rubric', 'rubric_criterion', '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[0]->id)->firstOrFail();
        $rubric_criterion = DB::table('criteria')
            ->join('rubric_criterion', 'rubric_criterion.criterion_id', '=', 'criteria.id')
            ->where('rubric_criterion.rubric_id', '=', $activity->rubric[0]->id)
            ->get();
        $rubric->titles = DB::table('titles')
            ->join('rubric_title', 'rubric_title.title_id', '=', 'titles.id')
            ->where('rubric_title.rubric_id', $rubric->id)
            ->orderBy('position')
            ->lists('text');

        foreach ($rubric_criterion as $single_cr) {
            $single_cr->scales = json_encode(DB::table('scales')
                ->join('criterion_scale', 'criterion_scale.scale_id', '=', 'scales.id')
                ->where('criterion_scale.criterion_id', '=', $single_cr->criterion_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'));
        }

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

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

        Log::info($rubric);

        $rubric["criteria"] = DB::table("criteria")

            ->where("criteria.id", '=', Input::get('criterion_id'))

            ->select('name', '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);
        //    }
    }
}