<?php

// Event::listen('illuminate.query', function($sql, $params)
// {
//     print_r($sql);

//     echo '<pre>';
//     print_r($params);
//     echo "</pre>";
// });

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/


// Route model bindings
Route::model('template', 'Template');
Route::model('program', 'Program');
Route::model('five_year_plan', 'FiveYearPlan');


// Composers
View::composer(array(
    'local.professors._navigation',
    'local.managers.admins._navigation',
    'local.managers.sCoords._navigation',
    'local.managers.pCoords._navigation',
    ), function($view)
{
    // Get user's courses' numbers
    $courses = Auth::user()->courses;

    $schools = School::orderBy('name', 'asc')->get();
    $view->with('courses', $courses)->with('schools', $schools);
});

View::composer(array(
    'local.professors.*',
    'local.managers.admins._navigation',
    'local.managers.sCoords._navigation',
    'local.managers.pCoords._navigation',
    'local.managers.shared.limited-course',
    'local.managers.shared.school',
    'local.managers.shared.school-uhs',
    'local.managers.shared.programs',
    'local.managers.shared.program',
    'local.managers.shared.rubrics',
    'global.view-learning-outcomes-criteria',
    'global.view-learning-outcomes-criteria'), function($view)
    {
        $view->with('role', Auth::user()->role);
    });


/*
 * Login/logout routes
 */

/** Use modified guest filter to redirect logged in user */
Route::get('/', array('before' => 'guest', 'uses' => 'AuthController@showLogin'));
Route::post('/login', array('uses'=>'AuthController@login'));

/**
 * Protected Routes
 */
Route::group(array('before' => 'auth|has_access'), function()
{

    /**
     * Recalculate course outcomes
     *
    */

    Route::get('recalculateCourses', function()
    {

        DB::disableQueryLog();

        if(Auth::user()->id!=58)
            Redirect::action('AuthController@showLogin');

        try
        {
            $courses = Course::all();

            foreach ($courses as $course)
            {
                echo $course->id;
                // Recalculate course outcomes
                $activities = Activity::where('course_id', $course->id)
                    ->whereNotNull('outcomes_attempted')
                    ->where('draft', 0)
                    ->get();


                //If there are still evaluated activities in the course, recalculate course outcomes
                if(!$activities->isEmpty())
                {
                    $outcomeCount = Outcome::all()->count();

                    // Variables to hold recalculated outcomes for the course
                    $course_outcomes_attempted = array_fill(1, $outcomeCount, 0);
                    $course_outcomes_achieved = array_fill(1, $outcomeCount, 0);

                    // For each activity
                    foreach ($activities as $activity2)
                    {
                        // If activity has been assessed
                        if($activity2->outcomes_attempted!=NULL)
                        {
                            echo '<ul>';
                            // Get the achieved criteria
                            $criteria_achievement = json_decode($activity2->criteria_achieved, true);
                            foreach($criteria_achievement as $criterion_id=>$criterion_achieved)
                            {
                                // Find corresponding learning outcome;
                                $criterion = Criterion::withTrashed()->where('id', $criterion_id)->first();

                                print '<li>'.$criterion->id.'</li>';


                                $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;
                                }
                            }

                            echo '</ul>';

                        }
                    }

                    // Update course
                    DB::table('courses')
                    ->where('id', $course->id)
                    ->update(array(
                        'outcomes_attempted'=> json_encode($course_outcomes_attempted),
                        'outcomes_achieved'=> json_encode($course_outcomes_achieved),
                        'updated_at' => date('Y-m-d H:i:s'))
                    );
                }
                // Otherwise, set them all to NULL
                else
                {
                    DB::table('courses')
                    ->where('id', $course->id)
                    ->update(array(
                        'outcomes_attempted'=> NULL,
                        'outcomes_achieved'=> NULL,
                        'updated_at' => date('Y-m-d H:i:s'))
                    );
                }
            }

            return 'success';
        }
        catch(Exception $e)
        {
            return 'failure ('.$e->getLine().'): '.$e->getMessage();
        }
    });

    /**
    * Shared Routes
    */

    // Fetch all criteria associated to an outcome
    Route::post( 'fetchCriteria', array(
        'as' => 'fetchCriteria',
        'uses' => 'OutcomesController@fetchCriteria'
    ) );

    // Fetch a criterion for a rubric
    Route::post( 'fetchCriterion', array(
        'as' => 'fetchCriterion',
        'uses' => 'CriteriaController@fetchCriterion'
    ) );

    // Fetch a criterion for a rubric
    Route::post( 'fetchCriterionWithTrashed', array(
        'as' => 'fetchCriterionWithTrashed',
        'uses' => 'CriteriaController@fetchCriterionWithTrashed'
    ) );

    // Fetch a criterion for a rubric with custom content
    Route::post( 'fetchRubricCriterion', array(
        'as' => 'fetchRubricCriterion',
        'uses' => 'RubricsController@fetchRubricCriterion'
    ) );

    // Load a rubric template
    Route::post('loadTemplate', array('uses'=>'TemplatesController@fetch'));

    Route::post('filterSemesters', array('uses'=>'SemestersController@filterSemesters'));


    // Log out user
    Route::get('logout', 'AuthController@logout');

    // Edit and update user profile
    Route::get('profile', 'UsersController@edit');
    Route::post('profile/update', array('before' => 'csrf', 'uses'=>'UsersController@update'));

    // Allows users to give feeback
    Route::post('feedback/send', array('before' => 'csrf', 'uses'=>'FeedbackController@send'));
    Route::resource('feedback', 'FeedbackController',
                array('only' => array('create')));

    // Show users all learning outcomes and criteria
    Route::get('learning-outcomes-criteria', 'CriteriaController@index');
    Route::post('fetchOutcome', array('before' => 'csrf', 'uses'=>'OutcomesController@fetchOutcome'));

    // Show professor overview to users with courses
    Route::get('professor', 'ProfessorsController@overview');

    // Assessment reports for users' courses
    Route::get('my-assessment-reports', 'OutcomesController@professorAssessmentReports');
    Route::post('objectives/fetch', array('before' => 'csrf', 'uses'=>'ObjectivesController@fetch'));

    /**
     * Administrator Routes
     */
    Route::group( array('before' => 'admin'), function()
    {
        Route::get('/administrator', 'AdministratorsController@overview');
        Route::post( 'administrator/rubrics', array(
            'as' => 'rubrics',
            'before' => 'csrf',
            'uses' => 'CriteriaController@fetch'
        ) );
        Route::post('createOutcome', array('before' => 'csrf', 'uses'=>'OutcomesController@create'));
        Route::post('createCriterion', array('before' => 'csrf', 'uses'=>'CriteriaController@create'));

        Route::get('learning-outcomes', 'OutcomesController@index');
        // TODO: Change later
        Route::get('new-learning-outcomes', 'OutcomesController@newIndex');
        Route::post('learning-outcomes/update', array('before' => 'csrf', 'uses' => 'OutcomesController@update'));
        Route::post('crtiteria/update', array('before' => 'csrf', 'uses'=>'CriteriaController@update'));
        Route::delete('crtiteria/delete', array('before' => 'csrf', 'uses'=>'CriteriaController@destroy'));

        Route::get('administrator/users/{query?}', 'UsersController@index');

        Route::post('administrator/updateAccess', array('before' => 'csrf', 'uses'=>'UsersController@updateAccess'));
        Route::post('administrator/users/store', array('before' => 'csrf', 'uses'=>'UsersController@store'));


        Route::get('administrator/semesters', 'SemestersController@edit');
        Route::post('administrator/semesters/update', 'SemestersController@update');

        Route::get('assessment-report/{outcome_id}', 'OutcomesController@assessmentReport');
        // TODO: Change later
        Route::get('new-assessment-report/{outcome_id}', 'OutcomesController@newAssessmentReport');

        Route::get('template-list', 'TemplatesController@index');

        Route::get('template/{template}', 'TemplatesController@show');

        Route::get('courses/reassign', 'CoursesController@reassign');
        Route::post('courses/update', array('before' => 'csrf', 'uses'=>'CoursesController@update'));



    });

    /**
     * School Coordinator Routes
     */
    Route::group( array('before' => 'scoord'), function()
    {
        Route::get('school-coordinator', 'SchoolCoordinatorsController@overview');
        Route::get('school/{id}', 'SchoolsController@show');
        Route::get('program/{id}', 'ProgramsController@show');
        Route::get('programs', 'ProgramsController@index');
        Route::get('template-list', 'TemplatesController@schoolCoordinatorIndex');

        // Print school report
        Route::get('print_school/{id}', 'SchoolsController@print_school');

        // Assessment reports
        Route::get('school-assessment-report/{outcome_id}', 'OutcomesController@schoolAssessmentReport');
    });

    /**
     * Program Coordinator Routes
     */
    Route::group( array('before' => 'pcoord'), function()
    {
        Route::get('program-coordinator', 'ProgramCoordinatorsController@overview');

        Route::get('rubrics', 'TemplatesController@newTemplate');
        Route::post('saveTemplate', array('before' => 'csrf', 'uses'=>'TemplatesController@create'));
        Route::post('updateTemplate', array('before' => 'csrf', 'uses'=>'TemplatesController@update'));
        Route::post('deleteTemplate', array('before' => 'csrf', 'uses'=>'TemplatesController@destroy'));
        Route::get('criteria', 'CriteriaController@edit');
        Route::get('course/{id}', 'CoursesController@showLimited');
        Route::get('rubrics/{template_id}/download', 'TemplatesController@download');
        Route::post('program/fetch', array('before' => 'csrf', 'uses'=>'ProgramsController@fetch'));

        Route::get('printRubric/{id}', 'TemplatesController@printview' );
        Route::get('rubric/{rubric_id}', 'RubricsController@show_limited');
        Route::get('grouped_course/{code}/{number}/{semester_code}', 'CoursesController@showGrouped');

        // Print program report
        Route::get('print_program/{id}', 'ProgramsController@print_program');

        // Print course (grouped sections) report
        Route::get('print_course/{code}/{number}/{semester_code}', 'CoursesController@print_course');

        // Assessment reports
        Route::get('program-assessment-report/{outcome_id}/{program_id}', 'OutcomesController@programAssessmentReport');
        Route::get('assessment-reports', 'OutcomesController@managerAssessmentReports');

        // Learning Objectives
        Route::get('program/{program}/objectives', 'ObjectivesController@index');
        Route::post('updateObjective', array('before' => 'csrf', 'uses'=>'ObjectivesController@update'));
        Route::post('program/{id}/createObjective', array('before' => 'csrf', 'uses'=>'ObjectivesController@create'));
        Route::post('fetchObjective', array('before' => 'csrf', 'uses'=>'ObjectivesController@fetchObjective'));
        Route::post('fetchObjectivesForCriteria', array('before' => 'csrf', 'uses'=>'ObjectivesController@fetchObjectivesForCriteria'));

        // Five year plans
        Route::get('five-year-plans', 'FiveYearPlansController@index');
        Route::get('program/{program}/five-year-plans/create', 'FiveYearPlansController@create');
        Route::get('program/{program}/five-year-plans/{five_year_plan}', 'FiveYearPlansController@show');
        Route::get('program/{program}/five-year-plans/{five_year_plan}/edit', 'FiveYearPlansController@edit');
        Route::get('five-year-plans/{five_year_plan}/ms-word', 'FiveYearPlansController@msWord');
        Route::post('five-year-plans/store', array('before' => 'csrf', 'uses'=>'FiveYearPlansController@store'));
        Route::post('five-year-plans/update', array('before' => 'csrf', 'uses'=>'FiveYearPlansController@update'));


        // Annual plans
        Route::get('annual-plans', 'AnnualPlansController@index');
        Route::get('program/{program}/annual-plans/create', 'AnnualPlansController@create');
        Route::get('program/{program}/annual-plans/{five_year_plan}', 'AnnualPlansController@show');
        Route::get('program/{program}/annual-plans/{five_year_plan}/edit', 'AnnualPlansController@edit');
        Route::post('annual-plans/store', array('before' => 'csrf', 'uses'=>'AnnualPlansController@store'));
        Route::post('annual-plans/update', array('before' => 'csrf', 'uses'=>'AnnualPlansController@update'));

        Route::get('learning-outcomes/show/{id}', 'OutcomesController@show');
        // TODO: Change route name
        Route::get('learning-outcomes/newshow/{id}', 'OutcomesController@newShow');
        Route::get('learning-outcomes/newshowall', 'OutcomesController@newShowAll');
        Route::get('new-report/{id}', 'OutcomesController@newReport');
        Route::get('new-report-all', 'OutcomesController@newReportAll');

    });


    /**
     * Professor Routes
     */
    Route::group(array('prefix' => 'professor', 'before'=>'prof'), function()
    {
        Route::post('program', array('before' => 'csrf', 'uses'=>'ProfessorsController@program'));
        Route::get('activities/{activity_id}/rubrics', 'RubricsController@newRubric');
        Route::get('activities/{activity_id}/rubric', 'RubricsController@show');
        Route::get('activities/{activity_id}/rubric/{rubric_id}/download', 'RubricsController@download');
        Route::get('activities/{activity_id}/rubric/{rubric_id}/print', 'RubricsController@printview');
        Route::get('activities/{activity_id}/assess', 'ActivitiesController@assess');
        Route::get('activities/{activity_id}/view_assessment', 'ActivitiesController@viewAssessment');
        Route::get('activities/{activity_id}/print_assessment', 'ActivitiesController@printAssessment');
        Route::post('activities/saveAssessment', array('before'=>'csrf', 'uses'=>'ActivitiesController@saveAssessment'));
        Route::post('activities/deleteAssessment', array('before'=>'csrf', 'uses'=>'ActivitiesController@deleteAssessment'));
        Route::delete('activities/{activity_id}/delete', 'ActivitiesController@destroy');
        Route::post('activities/{activity_id}/update', array('before' => 'csrf', 'uses'=>'ActivitiesController@update'));
        Route::get('courses/{id}', 'CoursesController@show');
        Route::get('courses/{semester}/{id}/students/{number}', 'StudentsController@show');
        Route::get('courses/{semester}/{id}/students/{number}/print_report', 'StudentsController@printStudentReport');
        Route::get('activities/{id}', 'ActivitiesController@show');
        Route::post('activities/{id}', array('before' => 'csrf', 'uses'=>'ActivitiesController@create'));
        Route::get('students', 'StudentsController@students');
        Route::get('program', 'ProfessorsController@program');
        Route::get('personal-information', 'ProfessorsController@personalInformation');
        Route::get('manual', 'ProfessorsController@manual');
        Route::post('loadRubric', array('before' => 'csrf', 'uses'=>'RubricsController@fetch'));
        Route::post('saveRubric', array('before' => 'csrf', 'uses'=>'RubricsController@create'));
        Route::post('updateRubric', array('before' => 'csrf', 'uses'=>'RubricsController@update'));
        Route::post('deleteRubric', array('before' => 'csrf', 'uses'=>'RubricsController@destroy'));
        Route::get('learning-outcomes-criteria', 'CriteriaController@index');
        Route::get('export_grades/{id}', 'CoursesController@exportGrades');

        // Assessment reports
        Route::get('professor-assessment-report/{outcome_id}', 'OutcomesController@professorAssessmentReport');
        Route::get('professor-assessment-reports', 'OutcomesController@professorAssessmentReports');

        Route::get('general-studies-overview', 'ProfessorsController@generalStudiesOverview');


    });

});