<?php

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class TransformativeActionsController extends \BaseController
{

  // load the Tranformative actions page
  public function editTA()
  {
    $title = "Transformative Action";
    $role = Auth::user()['role'];
    $outcomes = Outcome::orderBy('name', 'ASC')->lists('name', 'id');

    $schools = School::orderBy('name', 'ASC')->get();
    $criteria = Criterion::withTrashed()->orderBy('name', 'ASC')->get();
    $programs = Program::orderBy('name', 'ASC')->get();
    $user_id = auth::user()->id;

    switch ($role) {
      case 3:
        $program_id = DB::table('program_user')
          ->where('user_id', $user_id)
          ->select('program_id')
          ->lists('program_id');

        break;

      case 2:
        $program_id = DB::table('programs')
          ->where('school_id', Auth::user()->school_id)
          ->lists('id');
        break;
    }
    /*$program_id = DB::table('program_user')
      ->where('user_id', $user_id)
      ->select('program_id')
      ->get();
    $program_id = $program_id[0]->program_id; */ //program id 15 debido al user 8
    $outcomes = Outcome::orderBy('name', 'ASC')
      ->where('deactivation_date', '=', '0000-00-00')
      ->orWhereNull('deactivation_date')
      ->get();
    $objectives = array();
    $types = DB::table('transformative_actions')
      ->select('type_of_TA')
      ->where('type_of_TA', '<>', '')
      ->distinct()
      ->get();
    // if user is program coordinator

    //1 edit panel: load the TA that
    //    are custom ('transformative_actions.by_professor' == 0)
    //    were approved in past ('transformative_actions.is_custom' == 1)
    $ta_edit_panel = DB::table('transformative_actions')
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 0)
      ->orderBy('at_text', 'ASC')
      ->get();
    //2 approve panel: load TAs that
    //    can be approved ('transformative_actions.by_professor' == 1)
    $ta_approval_panel = DB::table('transformative_actions')
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 1)
      ->orderBy('at_text', 'ASC')
      ->get();
    //2.1 approve panel: load the filter options.
    // the "->where()" should be the same from $ta_approval_panel,
    //  but with aditional joins and different select
    //
    // get the names of the professors
    $professor_filter_approvePanel = DB::table('transformative_actions')
      ->join('users', 'users.id', '=', 'transformative_actions.user_id')
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 1)
      ->select('users.*')
      ->groupBy('transformative_actions.user_id')
      ->orderBy('users.first_name', 'ASC')
      ->get();
    // get the courses from asociated with a TA
    $course_filter_approvePanel = DB::table('ta_course')
      ->join('transformative_actions', 'transformative_actions.id', '=', 'ta_course.ta_id')
      ->join('courses', function ($join) {
        $join->on('courses.number', '=', 'ta_course.course_number');
        $join->on('courses.code', '=', 'ta_course.course_code');
      })
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 1)
      ->select('courses.*')
      ->groupBy('courses.number', 'courses.code', 'courses.name')
      ->orderBy('courses.name', 'ASC')
      ->orderBy('courses.code', 'ASC')
      ->get();
    // get the outcome asociated with a TA
    $outcome_filter_approvePanel = DB::table('transformative_actions')
      ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
      ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
      ->join('outcomes', 'outcomes.id', '=', 'objective_outcome.outcome_id')
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 1)
      ->select('outcomes.*')
      ->groupBy('outcomes.id')
      ->orderBy('outcomes.name', 'ASC')
      ->get();
    //3 edit panel: load the filter options.
    // the "->where()" should be the same from $ta_edit_panel,
    //  but with aditional joins and different select
    //
    $professor_filter_editPanel = DB::table('transformative_actions')
      ->join('users', 'users.id', '=', 'transformative_actions.user_id')
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 0)
      ->select('users.*')
      ->groupBy('transformative_actions.user_id')
      ->orderBy('users.first_name', 'ASC')
      ->get();
    $course_filter_editPanel =  DB::table('ta_course')
      ->join('transformative_actions', 'transformative_actions.id', '=', 'ta_course.ta_id')
      ->join('courses', function ($join) {
        $join->on('courses.number', '=', 'ta_course.course_number');
        $join->on('courses.code', '=', 'ta_course.course_code');
      })
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 0)
      ->select('courses.*')
      ->groupBy('courses.number', 'courses.code', 'courses.name')
      ->orderBy('courses.name', 'ASC')
      ->orderBy('courses.code', 'ASC')
      ->get();
    $outcome_filter_editPanel = DB::table('transformative_actions')
      ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
      ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
      ->join('outcomes', 'outcomes.id', '=', 'objective_outcome.outcome_id')
      ->where('transformative_actions.is_custom', 1)
      ->whereIn('transformative_actions.program_id', $program_id)
      ->where('transformative_actions.by_professor', 0)
      ->select('outcomes.*')
      ->groupBy('outcomes.id')
      ->orderBy('outcomes.name', 'ASC')
      ->get();
    // 4 create panel: search all courses
    $courses_create = DB::table('courses')
      ->whereIn('courses.program_id', $program_id)
      ->select('courses.*')
      ->groupBy('courses.number', 'courses.code',  'courses.name')
      ->orderBy('courses.name', 'ASC')
      ->orderBy('courses.code', 'ASC')
      ->get();
    /*
    // if user is profesor
    elseif ($role == 4) {
      // 1 the user can only edit TA that need approval and has been submited by the same user
      $ta_edit_panel = DB::table('transformative_actions')
        ->where('transformative_actions.is_custom', 1)
        ->where('transformative_actions.program_id', $program_id)
        ->where('transformative_actions.user_id', Auth::user()->id)
        ->where('transformative_actions.by_professor', 1)
        ->select('transformative_actions.*')
        ->orderBy('at_text', 'ASC')
        ->get();
      // 2 approve panel: dont load TA since professors cant approve them
      $ta_approval_panel = array();
      // 3 edit panel: load professor filter for his courses
      $professor_filter_editPanel = array();
      $course_filter_editPanel =  DB::table('ta_course')
        ->join('transformative_actions', 'transformative_actions.id', '=', 'ta_course.ta_id')
        ->join('courses', 'courses.id', '=', 'ta_course.course_id')
        ->where('transformative_actions.is_custom', 1)
        ->where('transformative_actions.user_id', Auth::user()->id)
        ->where('transformative_actions.program_id', $program_id)
        ->where('transformative_actions.by_professor', 1)
        ->select('courses.*')
        ->groupBy('courses.name', 'courses.code')
        ->orderBy('courses.name', 'ASC')
        ->orderBy('courses.code', 'ASC')
        ->get();
      $outcome_filter_editPanel = DB::table('transformative_actions')
        ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
        ->join('criterion_objective_outcome', 'criterion_objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
        ->join('outcomes', 'outcomes.id', '=', 'criterion_objective_outcome.outcome_id')
        ->where('transformative_actions.is_custom', 1)
        ->where('transformative_actions.user_id', Auth::user()->id)
        ->where('transformative_actions.program_id', $program_id)
        ->where('transformative_actions.by_professor', 1)
        ->select('outcomes.*')
        ->groupBy('outcomes.id')
        ->orderBy('outcomes.name', 'ASC')
        ->get();
      // these arent used by professors
      $professor_filter_approvePanel = array();
      $course_filter_approvePanel = array();
      $outcome_filter_approvePanel = array();

      // 4 create panel: search courses given by the professor
      $courses_create = DB::table('courses')
        ->where('courses.program_id', $program_id)
        ->where('courses.user_id', Auth::user()->id)
        ->select('courses.*')
        ->groupBy('courses.name', 'courses.code')
        ->orderBy('courses.name', 'ASC')
        ->orderBy('courses.code', 'ASC')
        ->get();
    }
*/
    return View::make('local.managers.admins.transformativeAction', compact(
      'title',
      'role',
      'types',
      'outcomes',
      'schools',
      'criteria',
      'programs',
      'outcomes',
      'objectives',
      'ta_edit_panel',
      'ta_approval_panel',
      'courses_create',
      'professor_filter_approvePanel',
      'course_filter_approvePanel',
      'outcome_filter_approvePanel',
      'professor_filter_editPanel',
      'outcome_filter_editPanel',
      'course_filter_editPanel'
    ));
  }

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


    $trimmed = trim(preg_replace('/\t+/', '', Input::get('text')));

    Log::info('trimmed 1 -->' . $trimmed . '<--');

    // if ($trimmed == '') {
    //     $trimmed = NULL;
    // } else {
    //     $trimmed = json_encode(preg_split('/\r\n/', $trimmed));
    // }

    Log::info('trimmed 2 -->' . $trimmed . '<--');


    $clean_input['text'] = $trimmed;

    //////
    $trimmed = trim(preg_replace('/\t+/', '', Input::get('description')));

    Log::info('trimmed 3 -->' . $trimmed . '<--');

    // if ($trimmed == '') {
    //     $trimmed = NULL;
    // } else {
    //     $trimmed = json_encode(preg_split('/\r\n/', $trimmed));
    // }

    Log::info('trimmed 4 -->' . $trimmed . '<--');


    $clean_input['description'] = $trimmed;



    $clean_input['objectiveid'] = Input::get('objectiveid');
    $clean_input['courseid'] = Input::get('courseid');
    $clean_input['approval'] = Input::get('approval');
    $clean_input['type'] = Input::get('type_of_ta');
    $clean_input['ta_id'] = Input::get('ta_id');
    $clean_input['new_type'] = Input::get('new_type');

    return $clean_input;
  }

  private function makeValidator($clean_input)
  {

    /** Validation rules */
    return Validator::make(
      array(
        'text' => $clean_input['text'],
        'description' => $clean_input['description'],
        'objectiveid' => $clean_input['objectiveid'],
        'courseid' => $clean_input['courseid'],
        'approval' => $clean_input['approval'],
        'ta_id' => $clean_input['ta_id'],
        'type_of_ta' => $clean_input['type'],
      ),
      array(
        'text' => 'required|string',
        'description' => 'required|string',
        'objectiveid' => 'required|array',
        'courseid' => 'required|string',
        'approval' => 'integer',
        'ta_id' => 'integer',
        'type_of_ta' => 'required|string'
      )
    );
  }


  // Create a Transformative Action
  public function createTA()
  {
    $clean_input = $this->cleanInput();

    /** Validation rules */
    $validator = $this->makeValidator($clean_input);

    /** If validation fails */
    if ($validator->fails()) {
      /** Prepare error message */
      $message = '<p>Error(s) creating a new Transformative Action:</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);
      $role = Auth::user()['role'];
      return Redirect::to('transformativeAction')->withInput();
    } else {

      $user_id = Auth::user()->id;


      /*$program_id = DB::table('program_user')
        ->where('user_id', $user_id)
        ->select('program_id')
        ->get();
      $program_id = $program_id[0]->program_id;*/
      $role = Auth::user()['role'];
      $by_professor = 1;
      if ($role != 4) {
        $by_professor = 0;
      }
      Log::info($clean_input['courseid']);
      // $by_professor = $clean_input['approval'];

      $parentesis = array('(', ')');
      $course_code_number = str_replace($parentesis, '', $clean_input['courseid']);

      $course_code_number = explode(',', $course_code_number);

      $program_id = DB::table('courses')
        ->where('code', $course_code_number[0])
        ->where('number', $course_code_number[1])
        ->select('program_id')
        ->first()->program_id;


      $current_timestamp = date('Y/m/d H:i:s', time());
      if ($clean_input['new_type']) $type = $clean_input['new_type'];
      else $type = $clean_input['type'];
      // insert the TA
      $ta_id = DB::table('transformative_actions')->insertGetId(
        array(
          'at_text' => $clean_input['text'],
          'description' => $clean_input['description'],
          'is_custom' => 1,
          'user_id' => $user_id,
          'program_id' => $program_id,
          'created_at' => $current_timestamp,
          'by_professor' => $by_professor,
          'type_of_TA' => $type
        )
      );

      //
      // // insert the multiple TA_objective_program
      foreach ($clean_input['objectiveid'] as $objective_id) {
        DB::table('transformative_objective')->insert(
          array(
            'ta_id' => $ta_id,
            'objective_id' => $objective_id,


          )
        );
      }

      //
      // // insert the multiple TA_course
      DB::table('ta_course')->insert(
        array(
          'ta_id' => $ta_id,
          'course_number' => $course_code_number[1],
          'course_code' => $course_code_number[0],

        )
      );


      Session::flash('status', 'success');
      Session::flash('message', 'Transformative Action created: "' . $clean_input['text'] . '".');
      $role = Auth::user()['role'];
      return Redirect::to('transformativeAction')->withInput();
    }
  }

  // apporve a Transformative Action
  public function approveTA()
  {
    $role = Auth::user()['role'];
    if ($role != 3) {
      $message = 'Only Program Coordinators can approve a TA';
      Session::flash('status', 'danger');
      Session::flash('message', $message);
      return Redirect::to('transformativeAction')->withInput();
    }

    $ta_id = Input::get('ta_id');
    $text = Input::get('at_text');

    if ($ta_id == 0) {
      $message = 'Please select a Transformative Action</p>';

      Session::flash('status', 'danger');
      Session::flash('message', $message);

      $role = Auth::user()['role'];
      return Redirect::to('transformativeAction')->withInput();
    }

    $current_timestamp = date('Y/m/d H:i:s', time());

    if (Input::get('new_type')) {
      $type = Input::get('new_type');
    } else {
      $type = Input::get('type_of_ta');
    }

    // edit the TA
    DB::table('transformative_actions')
      ->where('id', $ta_id)
      ->update([
        'by_professor' => 0,
        'updated_at' => $current_timestamp,
        'type_of_TA' => $type
      ]);

    Session::flash('status', 'success');
    Session::flash('message', 'Approved the Transformative Action: "' . $text . '".');
    $role = Auth::user()['role'];
    return Redirect::to('transformativeAction')->withInput();
  }


  // update a Tranformative Action
  public function updateTA()
  {
    $clean_input = $this->cleanInput();

    /** Validation rules */
    $validator = $this->makeValidator($clean_input);

    /** If validation fails */
    if ($validator->fails()) {
      /** Prepare error message */
      $message = 'Error(s) updating the Transformative Action: <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);
      $role = Auth::user()['role'];
      return Redirect::to('transformativeAction')->withInput();
    } else {
      $parentesis = array('(', ')');
      $course_code_number = str_replace($parentesis, '', $clean_input['courseid']);

      $course_code_number = explode(',', $course_code_number);

      $program_id = DB::table('courses')
        ->where('code', $course_code_number[0])
        ->where('number', $course_code_number[1])
        ->select('program_id')
        ->first()->program_id;

      $user_id = auth::user()->id;
      /* $program_id = DB::table('program_user')
        ->where('user_id', $user_id)
        ->select('program_id')
        ->get();
      $program_id = $program_id[0]->program_id;*/
      $role = Auth::user()['role'];
      $by_professor = $clean_input['approval'];
      if ($role == 4) {
        $by_professor = 1;
      }

      // $by_professor = $clean_input['approval'];

      if ($clean_input['new_type']) $type = $clean_input['new_type'];
      else $type = $clean_input['type'];

      $current_timestamp = date('Y/m/d H:i:s', time());
      // edit the TA
      DB::table('transformative_actions')
        ->where('id', $clean_input['ta_id'])
        ->update([
          'by_professor' => $by_professor,
          'at_text' => $clean_input['text'],
          'description' => $clean_input['description'],
          'updated_at' => $current_timestamp,
          'type_of_TA' => $type

        ]);


      $ta_id = $clean_input['ta_id'];
      $new_objective_id = $clean_input['objectiveid'];
      $old_objective_id = DB::table('transformative_objective')
        ->where('ta_id', $ta_id)
        ->select('objective_id')
        ->lists('objective_id');

      //delete existing objective_id if it isnt in new_ids array
      foreach ($old_objective_id as $old_id) {
        if (in_array($old_id, $new_objective_id)) {
          //do nothing if a new id is already in atble
        } else {
          //if old id not in new id, delete
          DB::table('transformative_objective')
            ->where('ta_id', $ta_id)
            ->where('objective_id', $old_id)
            ->delete();
        }
      }

      //
      foreach ($new_objective_id as $new_id) {
        $result = DB::table('transformative_objective')
          ->where('objective_id', $new_id)
          ->select('objective_id')
          ->lists('objective_id');

        if (count($result) == 0) {
          //if the new_id does not exists, do nothing
          DB::table('transformative_objective')->insert(
            array(
              'ta_id' => $ta_id,
              'objective_id' => $new_id,
              // 'created_at' => $current_timestamp,
            )
          );
        } else {
          //if the new_id already exists, do nothing
        }
      }





      DB::update(
        "UPDATE `ta_course` set `course_number` = '{$course_code_number[1]}', `course_code` = '{$course_code_number[0]}' where ta_id = {$ta_id}"
      );

      /*$new_course_id = $clean_input['courseid'];

      $old_course_id = DB::table('ta_course')
        ->where('ta_id', $ta_id)
        ->select('course_id')
        ->lists('course_id');

      //delete existing course_id if it isnt in new_ids array
      foreach ($old_course_id as $old_id) {
        if (in_array($old_id, $new_course_id)) {
          //do nothing if a new id is already in atble
        } else {
          //if old id not in new id, delete
          DB::table('ta_course')
            ->where('ta_id', $ta_id)
            ->where('course_id', $old_id)
            ->delete();
        }
      }
      //add course_id if it isnt already inserted
      foreach ($new_course_id as $new_id) {
        $result = DB::table('ta_course')
          ->where('ta_id', $ta_id)
          ->where('course_id', $new_id)
          ->select('course_id')
          ->lists('course_id');

        if (count($result) == 0) {
          //if the new_id does not exists, do nothing
          DB::table('ta_course')->insert(
            array(
              'ta_id' => $ta_id,
              'course_id' => $new_id,
            )
          );
        } else {
          //if the new_id already exists, do nothing
        }
      } */

      Session::flash('status', 'success');
      Session::flash('message', 'Updated Transformative Action: "' . $clean_input['text'] . '".');
      $role = Auth::user()['role'];
      return Redirect::to('transformativeAction')->withInput();
    }
  }

  // delete a Transformative Action
  public function deleteTA()
  {
    $ta_id = array(Input::get('ta_id'));

    // si envia id 0, el backend se queja en la linea: $ta = $ta[0];
    // nunca deberia ocurrir, pero es un safity measure.
    if ($ta_id == 0) {
      $message = 'Please select a Transformative Action</p>';

      Session::flash('status', 'danger');
      Session::flash('message', $message);

      $role = Auth::user()['role'];
      return Redirect::to('transformativeAction')->withInput();
    }

    $ta = DB::table('transformative_actions')
      ->where('transformative_actions.is_custom', 1)
      ->where('id', $ta_id)
      ->get();
    $ta = $ta[0];

    $used = DB::table('annual_plan_transformative')
      ->where('id', $ta_id)
      ->get();

    $recommended = $ta->by_professor;
    // the TA can only be deleted if error if the TA is not currently as "Recommended"
    // and isnt used in an anual plan
    if ($recommended == 1 && count($used) == 0) {
      // delete the TA if it qualifies
      DB::delete("delete from transformative_actions where id = ?", $ta_id);

      $name = $ta->at_text;

      $message = 'The Transformative Action has been deleted:</p><ul>';
      $message .= '<li> ' . $name . ' </li>';
      $message .= '</ul>';

      Session::flash('status', 'success');
      Session::flash('message', $message);
      $role = Auth::user()['role'];
      return Redirect::to('transformativeAction')->withInput();
    }


    $message = 'Transformative Actions can only be deleted if:</p><ul>';
    $message .= '<li> It has a status of "Recommended"</li>';
    $message .= '<li> It is not currently used in a plan</li>';
    $message .= '</ul>';

    Session::flash('status', 'danger');
    Session::flash('message', $message);

    $role = Auth::user()['role'];
    return Redirect::to('transformativeAction')->withInput();
  }



  // load the information of a Tranformative Action when its
  //  selected on the approve or edit panel
  public function selectTA()
  {
    $ta_id = Input::get("ta_id");
    $user_role = Auth::user()->role;
    switch ($user_role) {
      case 1:

        $program_ids = DB::table('programs')->lists('id');
        break;
      case 2:
        $user_school = Auth::user()->school_id;
        $program_ids = DB::table('programs')
          ->where('school_id', $user_school)
          ->lists('id');
        break;

      case 3:
        $user_id = Auth::user()->id;
        $program_ids = DB::table('program_user')
          ->where('user_id', $user_id)
          ->select('program_id')
          ->lists('program_id');
        break;
    }
    //$program_id = DB::table('program_user')
    //  ->where('user_id', $user_id)
    //  ->select('program_id')
    //  ->get();
    //$program_id = $program_id[0]->program_id;

    $objectives = DB::table('transformative_actions')
      ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
      ->join('objectives', 'objectives.id', '=', 'transformative_objective.objective_id')
      ->where('transformative_actions.id', $ta_id)
      ->select('objectives.text as text', 'objectives.id as id')
      ->orderBy('objectives.text', 'ASC')
      ->get();
    $objective_ids = DB::table('transformative_actions')
      ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
      ->join('objectives', 'objectives.id', '=', 'transformative_objective.objective_id')
      ->where('transformative_actions.id', $ta_id)
      ->select('objectives.text as text', 'objectives.id as id')
      ->orderBy('objectives.text', 'ASC')
      ->lists('objectives.id');
    Log::info($ta_id);

    //$an_objective = $objectives[0]->id;
    $outcome_ids = DB::table('objective_outcome')
      ->whereIn('objective_outcome.objective_id', $objective_ids)
      ->select('objective_outcome.outcome_id')
      ->lists('outcome_id');
    //$outcome_id = $outcome_id[0]->outcome_id;
    Log::info("outcomes");
    Log::info($outcome_ids);
    $objectives_from_outcome = DB::table('objectives')
      ->join('objective_program', 'objective_program.objective_id', '=', 'objectives.id')
      ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'objectives.id')
      ->whereIn('objective_outcome.outcome_id', $outcome_ids)
      ->whereIn('objective_program.program_id', $program_ids)
      ->orderBy('objectives.text', 'ASC')
      ->select('objectives.text as text', 'objectives.id as id')
      ->distinct()
      ->get();

    $selected_courses = DB::table('ta_course')
      ->join('courses', function ($join) {
        $join->on('courses.number', '=', 'ta_course.course_number');
        $join->on('courses.code', '=', 'ta_course.course_code');
      })
      ->where('ta_id', $ta_id)
      ->orderBy('courses.name', 'ASC')
      ->orderBy('courses.code', 'ASC')
      ->select('courses.*')
      ->get();
    $name = DB::table('transformative_actions')
      ->where('id', $ta_id)
      ->select('at_text as name')
      ->lists('name');
    $description = DB::table('transformative_actions')
      ->where('id', $ta_id)
      ->select('description')
      ->lists('description');
    $status = DB::table('transformative_actions')
      ->where('id', $ta_id)
      ->select('by_professor as status')
      ->lists('status');
    $status = $status[0];
    $plans_count = DB::table('annual_plan_transformative')
      ->where('trans_id', $ta_id)
      ->get();
    $plans_count = count($plans_count);
    $can_be_deleted = false;
    if ($plans_count == 0 /*&& $status == 1*/) {
      $can_be_deleted = true;
    }
    return array(
      'objectives' => $objectives,
      'objectives_from_outcome' => $objectives_from_outcome,
      'selected_courses' => $selected_courses,
      'name' => $name,
      'description' => $description,
      'status' => $status,
      'can_be_deleted' => $can_be_deleted,
      'plans_count' => $plans_count,
    );
  }

  // load the available objectieves from an outcome when creating a Tranformative Action
  public function objectivesFromOutcome()
  {
    $user_role = Auth::user()->role;


    switch ($user_role) {
      case 1:

        $program_ids = DB::table('programs')->lists('id');
        break;

      case 2:
        $user_school = Auth::user()->school_id;
        $program_ids = DB::table('programs')
          ->where('school_id', $user_school)
          ->lists('id');
        break;
      case 3:
        $user_id = Auth::user()->id;
        $program_ids = DB::table('program_user')
          ->where('user_id', $user_id)
          ->select('program_id')
          ->lists('program_id');
        break;
    }

    //$program_id = DB::table('program_user')
    //  ->where('user_id', $user_id)
    //  ->select('program_id')
    //  ->get();
    //$program_id = $program_id[0]->program_id;
    $ta_id = Input::get("ta_id");
    $outcome_id = Input::get("outcome_id");

    $objectives = DB::table('objectives')
      ->join('objective_program', 'objective_program.objective_id', '=', 'objectives.id')
      ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'objectives.id')
      ->where('objective_outcome.outcome_id', $outcome_id)
      ->whereIn('objective_program.program_id', $program_ids)
      ->orderBy('objectives.text', 'ASC')
      ->select('objectives.text as text', 'objectives.id as id')
      ->distinct()
      ->get();

    return array(
      'objectives' => $objectives,
    );
  }

  // return Transformative Actions that meet the filter criterias
  public function filterTA()
  {
    $user_id = Auth::user()->id;
    $role = Auth::user()['role'];
    $professor_id = Input::get('professor_id');
    $course_id = Input::get('course_id');
    $outcome_id = Input::get('outcome_id');
    $panel_id = Input::get('panel_id');

    switch ($role) {
      case 1:
        $program_id = DB::table('programs')->lists('id');
        break;

      case 2:
        $program_id = DB::table('programs')->where('school_id', Auth::user()->school_id)
          ->lists('id');
        break;
      case 3:
        $program_id = DB::table('program_user')
          ->where('user_id', $user_id)
          ->select('program_id')
          ->get();
        $program_id = $program_id[0]->program_id;
        break;
    }


    // if the user is a coordinator filtering the approvePanel
    /*if ($role == '3' && $panel_id == 'approvePanel') {

      // if professor isnt a desired filter, search all professors
      if ($professor_id == 0) {
        $all_ta_users = DB::table('transformative_actions')
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 1)
          ->select('transformative_actions.user_id')
          ->get();
        $professor_id = array();
        foreach ($all_ta_users as $key => $user) {
          array_push($professor_id, $user->user_id);
        }
      } else {
        $professor_id = array($professor_id);
      }
      // if course isnt a desired filter, search all courses
      if ($course_id == 0) {
        $courses =  DB::table('ta_course')
          ->join('transformative_actions', 'transformative_actions.id', '=', 'ta_course.ta_id')
          ->join('courses', function ($join) {
            $join->on('courses.number', '=', 'ta_course.course_number');
            $join->on('courses.code', '=', 'ta_course.course_code');
          })
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 1)
          ->select('ta_course.course_number', 'ta_course.course_code')
          ->distinct()
          ->get();

        $course_id = array();
        foreach ($courses as $key => $course) {
          array_push($course_id["number"], $course->course_number);
          array_push($course_id["code"], $course->code);
        }
      } else {

        $parentesis = array('(', ')');
        $course_code_number = str_replace($parentesis, '', $course_id);

        $course_code_number = explode(',', $course_code_number);

        $course_id = array();
        $course_id['number'] = $course_code_number[1];
        $course_id['code'] = $course_code_number[0];
      }
      // if outcome isnt a desired filter, search all outcomes
      if ($outcome_id == 0) {
        $outcomes = DB::table('transformative_actions')
          ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
          ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
          ->join('outcomes', 'outcomes.id', '=', 'objective_outcome.outcome_id')
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 1)
          ->select('outcomes.id')
          ->groupBy('outcomes.id')
          ->get();
        $outcome_id = array();
        foreach ($outcomes as $key => $outcome) {
          array_push($outcome_id, $outcome->id);
        }
      } else {
        $outcome_id = array($outcome_id);
      }

      // search TA with filters

      $filtered_at = DB::table('transformative_actions')
        ->join('ta_course', 'ta_course.ta_id', '=', 'transformative_actions.id')
        ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
        ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
        ->where('transformative_actions.is_custom', 1)
        ->where('transformative_actions.program_id', $program_id)
        ->where('transformative_actions.by_professor', 1)
        ->whereIn('transformative_actions.user_id', $professor_id)
        ->whereIn('objective_outcome.outcome_id', $outcome_id)
        ->whereIn('ta_course.course_code', $course_id['code'])
        ->whereIn('ta_course.course_number', $course_id['number'])
        ->select('transformative_actions.*')
        ->groupBy('transformative_actions.id')
        ->orderBy('transformative_actions.at_text', 'ASC')
        ->get();
      return $filtered_at;
    }*/
    // if the user is a coordinator filtering the editPanel
    if ($panel_id == 'editPanel') {

      // if professor isnt a desired filter, search all professors
      if ($professor_id == 0) {
        $all_ta_users = DB::table('transformative_actions')
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 0)
          ->select('transformative_actions.user_id')
          ->get();
        $professor_id = array();
        foreach ($all_ta_users as $key => $user) {
          array_push($professor_id, $user->user_id);
        }
      } else {
        $professor_id = array($professor_id);
      }
      // if course isnt a desired filter, search all courses
      if ($course_id == 0) {
        $courses =  DB::table('ta_course')
          ->join('transformative_actions', 'transformative_actions.id', '=', 'ta_course.ta_id')
          ->join('courses', function ($join) {
            $join->on('courses.number', '=', 'ta_course.course_number');
            $join->on('courses.code', '=', 'ta_course.course_code');
          })
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 0)
          ->select('ta_course.course_number', 'ta_course.course_code')
          ->distinct()
          ->get();

        $course_id = array();
        foreach ($courses as $key => $course) {
          array_push($course_id["number"], $course->course_number);
          array_push($course_id["code"], $course->code);
        }
      } else {

        $parentesis = array('(', ')');
        $course_code_number = str_replace($parentesis, '', $course_id);

        $course_code_number = explode(',', $course_code_number);

        $course_id = array();
        $course_id['number'] = $course_code_number[1];
        $course_id['code'] = $course_code_number[0];
      }
      // if outcome isnt a desired filter, search all outcomes
      if ($outcome_id == 0) {
        $outcomes = DB::table('transformative_actions')
          ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
          ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
          ->join('outcomes', 'outcomes.id', '=', 'objective_outcome.outcome_id')
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 0)
          ->select('outcomes.id')
          ->groupBy('outcomes.id')
          ->get();
        $outcome_id = array();
        foreach ($outcomes as $key => $outcome) {
          array_push($outcome_id, $outcome->id);
        }
      } else {
        $outcome_id = array($outcome_id);
      }

      // search TA with filters
      $filtered_at = DB::table('transformative_actions')
        ->join('ta_course', 'ta_course.ta_id', '=', 'transformative_actions.id')
        ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
        ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
        ->where('transformative_actions.is_custom', 1)
        ->where('transformative_actions.program_id', $program_id)
        ->where('transformative_actions.by_professor', 0)
        ->whereIn('transformative_actions.user_id', $professor_id)
        ->whereIn('objective_outcome.outcome_id', $outcome_id)
        ->whereIn('ta_course.course_code', $course_id['code'])
        ->whereIn('ta_course.course_number', $course_id['number'])
        ->select('transformative_actions.*')
        ->groupBy('transformative_actions.id')
        ->orderBy('transformative_actions.at_text', 'ASC')
        ->get();
      return $filtered_at;
    }
    // if the user is a professor filtering the editPanel
    /*elseif ($role == '4' && $panel_id == 'editPanel') {

      // if course isnt a desired filter, search all courses
      if ($course_id == 0) {
        $courses = DB::table('ta_course')
          ->join('transformative_actions', 'transformative_actions.id', '=', 'ta_course.ta_id')
          ->join('courses', 'courses.id', '=', 'ta_course.course_id')
          ->where('transformative_actions.user_id', Auth::user()->id)
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 1)
          ->select('ta_course.course_number', 'ta_course.course_code')
          ->distinct()
          ->get();

        $course_id = array();
        foreach ($courses as $key => $course) {
          array_push($course_id["number"], $course->course_number);
          array_push($course_id["code"], $course->code);
        }
      } else {

        $parentesis = array('(', ')');
        $course_code_number = str_replace($parentesis, '', $course_id);

        $course_code_number = explode(',', $course_code_number);

        $course_id = array();
        $course_id['number'] = $course_code_number[1];
        $course_id['code'] = $course_code_number[0];
      }
      // if outcome isnt a desired filter, search all outcomes
      if ($outcome_id == 0) {
        $outcomes = DB::table('transformative_actions')
          ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
          ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
          ->join('outcomes', 'outcomes.id', '=', 'objective_outcome.outcome_id')
          ->where('transformative_actions.user_id', Auth::user()->id)
          ->where('transformative_actions.is_custom', 1)
          ->where('transformative_actions.program_id', $program_id)
          ->where('transformative_actions.by_professor', 1)
          ->select('outcomes.id')
          ->groupBy('outcomes.id')
          ->get();
        $outcome_id = array();
        foreach ($outcomes as $key => $outcome) {
          array_push($outcome_id, $outcome->id);
        }
      } else {
        $outcome_id = array($outcome_id);
      }

      // search TA with filters
      $filtered_at = DB::table('transformative_actions')
        ->join('ta_course', 'ta_course.ta_id', '=', 'transformative_actions.id')
        ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
        ->join('objective_outcome', 'objective_outcome.objective_id', '=', 'transformative_objective.objective_id')
        ->where('transformative_actions.user_id', Auth::user()->id)
        ->where('transformative_actions.is_custom', 1)
        ->where('transformative_actions.program_id', $program_id)
        ->where('transformative_actions.by_professor', 1)
        ->whereIn('objective_outcome.outcome_id', $outcome_id)
        ->whereIn('ta_course.course_code', $course_id['code'])
        ->whereIn('ta_course.course_number', $course_id['number'])
        ->select('transformative_actions.*')
        ->groupBy('transformative_actions.id')
        ->orderBy('transformative_actions.at_text', 'ASC')
        ->get();
      return $filtered_at;
    }*/
    return 'ilegal';
  }

  function postActivityCriterion($activity_id)
  {
    DB::beginTransaction();

    $existing_transformative_action = DB::table('transformative_actions')
      ->join('transformative_activity_criterion', 'transformative_activity_criterion.trans_action_id', '=', 'transformative_actions.id')
      ->join('activity_criterion', 'activity_criterion.id', '=', 'transformative_activity_criterion.activity_criterion_id')
      ->where('activity_id', $activity_id)
      ->delete();
    $activity_criterion = Input::get('trans_act');

    $trans = new TransformativeAction;

    $trans->user_id = Auth::user()['id'];
    $program_id = DB::table('activities')
      ->join('courses', 'activities.course_id', '=', 'courses.id')
      ->where('activities.id', $activity_id)
      ->lists('program_id');
    $trans->program_id = $program_id[0];
    $trans->is_custom = 1;
    $trans->by_professor = 1;

    $trans->at_text = Input::get('name_trans');
    $trans->description = Input::get('transforming_actions');

    $activity = DB::table('activities')
      ->where('id', $activity_id)
      ->first();
    $course_credentials = DB::table('courses')
      ->where('id', $activity->course_id)
      ->first();


    if ($trans->save()) {




      foreach ($activity_criterion as $single_ac) {
        $result = DB::insert("insert into `transformative_activity_criterion` (`trans_action_id`, `activity_criterion_id`) values ($trans->id, $single_ac)");
        if (!$result) {
          DB::rollback();
          Session::flash('status', 'danger');
          Session::flash('message', 'Error saving Formative Action. Try again later.');

          return Redirect::to("professor/activities/{$activity_id}");
        }
      }
      $criteria = DB::table('activity_criterion')
        ->whereIn('id', $activity_criterion)
        ->lists('criterion_id');

      $allObjectives = DB::table('criterion_objective_outcome')
        ->whereIn('criterion_id', $criteria)
        ->select('objective_id')
        ->distinct()
        ->lists('objective_id');


      foreach ($allObjectives as $objective) {
        $result2 = DB::insert("insert into `transformative_objective` (`ta_id`, `objective_id`) values ({$trans->id},{$objective})");
        if (!$result2) {
          DB::rollback();
          Session::flash('status', 'danger');
          Session::flash('message', 'Error saving Formative Action. Try again later.');

          return Redirect::to("professor/activities/{$activity_id}");
        }
      }
      $result3 = DB::insert("insert into `ta_course` (`ta_id`, `course_number`, `course_code`) values ({$trans->id}, '{$course_credentials->number}', '{$course_credentials->code}')");

      if (!($result3)) {
        DB::rollback();
        Session::flash('status', 'danger');
        Session::flash('message', 'Error saving Formative Action. Try again later.');
        return Redirect::to("professor/activities/{$activity_id}");
      }
      DB::commit();
      Session::flash('status', 'success');
      Session::flash('message', 'Formative Actions Saved.');

      return Redirect::to("professor/activities/{$activity_id}");
    } else {
      DB::rollback();
      Session::flash('status', 'danger');
      Session::flash('message', 'Error saving Formative Action. Try again later.');

      return Redirect::to("professor/activities/{$activity_id}");
    }
  }

  public function viewFormativeActions()
  {
    $title = "Formative Actions";
    $semesters = Session::get('semesters_ids');
    $semesters = DB::table('semesters')->whereIn('id', $semesters)->orderBy('start', 'ASC')->first();
    Log::info($semesters->start);
    $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();
    $semesters = DB::table('semesters')->where('is_visible', 1)->orderBy('end', 'DESC')->get();
    $role = Auth::user()->role;
    switch ($role) {
      case 1:
        $schools = DB::table('schools')->get();
        $programs = DB::table('programs')->get();
        break;

      case 2:
        $schools = DB::table('schools')->where('id', Auth::user()->school_id)->get();
        $programs = DB::table('programs')->where('school_id', $schools[0]->id)->get();
        break;
      case 3:
        $programs = DB::table('programs')
          ->join('program_user', 'programs.id', '=', 'program_user.program_id')
          ->where('user_id', Auth::user()->id)
          ->select('programs.*')
          ->get();
        $schools = DB::table('schools')->where('id', $programs[0]->school_id)->get();
        break;
    }

    return View::make('local.managers.shared.view_formative', compact('title', 'outcomes', 'schools', 'programs', 'semesters'));
  }

  public function fetchCourses()
  {

    $school = Input::get('schools');

    $programs = Input::get('programs');
    $semesters = Input::get('semesters');
    $outcome_id = Input::get('id');

    Log::info($programs);
    Log::info($semesters);


    /* if (in_array(0, $semesters)) {
      $semesters = DB::table('semesters')->where('is_visible', 1)->lists('id');
    }*/

    /*  if (in_array(0, $programs)) {

      $role = Auth::user()->role;

      switch ($role) {
        case 1:
          $programs = DB::table('programs')->lists('id');
          break;
        case 2:
          $programs = DB::table('programs')->where('school_id', Auth::user()->school_id)->lists('id');
          break;
        case 3:
          $programs = DB::table('program_user')->where('user_id', Auth::user()->id)->lists('program_id');
          break;
      }
    }*/

    $typ_semester_outcome = DB::table('typ_semester_outcome')
      ->where('semester_id', $semesters)
      ->where('outcome_id', $outcome_id)
      ->lists('id');


    //each row has objectives, repeated ta, but distinct activity_criterion_id
    /* $objective_ta = DB::table('typ_semester_objectives')
      ->join('transformative_objective as trob', 'trob.objective_id', '=', 'typ_semester_objectives.objective_id')
      ->join('objectives', 'trob.objective_id', '=', 'objective_id')
      ->join('transformative_actions', 'transformative_actions.id', 'trob.ta_id')
      ->whereIn('typ_semester_objectives.typ_semester_outcome_id', $typ_semester_outcome)
      ->select('transformative_actions.*')
      ->addSelect('objectives.*')
      ->distinct()
      ->get();

     $objective_ta = DB::table('typ_semester_objectives')
      ->join('transformative_objective as trob', 'trob.objective_id', '=', 'typ_semester_objectives.objective_id')
      ->join('objectives', 'trob.objective_id', '=', 'objective_id')
      ->join('transformative_actions', 'transformative_actions.id', 'trob.ta_id')
      ->whereIn('typ_semester_objectives.typ_semester_outcome_id', $typ_semester_outcome)
      ->select('transformative_actions.*')
      ->addSelect('objectives.*')
      ->distinct()
      ->lists();*/







    $grouped_courses = DB::table('courses')
      ->where('program_id', $programs)
      ->where('semester_id', $semesters)
      ->join('activities', 'activities.course_id', '=', 'courses.id')
      ->join('activity_criterion', 'activities.id', '=', 'activity_criterion.activity_id')

      ->join('transformative_activity_criterion as tac', 'tac.activity_criterion_id', '=', 'activity_criterion.id')
      ->select('courses.*')
      ->groupBy(array('courses.code', 'courses.name', 'courses.semester_id'))
      ->get();







    foreach ($grouped_courses as $course_name) {
      $course_name->sections = DB::table('courses')
        ->where('code', $course_name->code)
        ->where('name', $course_name->name)
        ->where('semester_id', $course_name->semester_id)
        ->where('program_id', $course_name->program_id)
        ->get();
      foreach ($course_name->sections as $section) {

        $section->activities = DB::table('activities')
          ->join('activity_criterion', 'activities.id', '=', 'activity_criterion.activity_id')

          ->join('transformative_activity_criterion', 'transformative_activity_criterion.activity_criterion_id', '=', 'activity_criterion.id')
          ->join('criterion_objective_outcome', 'criterion_objective_outcome.criterion_id', '=', 'activity_criterion.criterion_id')
          ->join('transformative_actions', 'transformative_activity_criterion.trans_action_id', '=', 'transformative_actions.id')
          ->where('activities.course_id', $section->id)
          ->where('activities.draft', 0)
          ->where('activities.diagnostic', 0)
          ->where('criterion_objective_outcome.outcome_id', $outcome_id)
          ->select('activities.id as activity_id', 'activities.name')
          ->addSelect('transformative_actions.*', 'transformative_activity_criterion.trans_action_id as trans_action_id')
          ->groupBy('transformative_actions.id')
          ->get();

        //If section has activity that assessess outcome
        if (count($section->activities)) {
          $course_name->outcome_assessed = true;
        }

        foreach ($section->activities as $activity) {
          /*$activity->criterion = DB::table('transformative_activity_criterion')
          ->join('activity_criterion','activity_criterion.id','=','transformative_activity_criterion.activity_criterion_id')
          ->join('activities','activities.id','=','activity_criterion.activity_id')
          ->join('criteria','activity_criterion.criterion_id','=','criteria.id')
          ->where('activity_id', $activity->id)
          ->select('criteria')*/
          //Log::info($activity->trans_action_id);
          $activity->criterion_with_objective = DB::table('transformative_activity_criterion')
            ->join('activity_criterion', 'activity_criterion.id', '=', 'transformative_activity_criterion.activity_criterion_id')
            ->join('criteria', 'activity_criterion.criterion_id', '=', 'criteria.id')
            ->join('criterion_objective_outcome', 'criterion_objective_outcome.criterion_id', '=', 'criteria.id')
            ->join('objectives', 'objectives.id', '=', 'criterion_objective_outcome.objective_id')
            ->where('activity_id', $activity->activity_id)
            ->where('trans_action_id', $activity->trans_action_id)
            ->get();
          /*$activity->objectives = DB::table('transformative_objective')
            ->join('objectives', 'transformative_objective.objective_id', '=', 'objectives.id')
            ->where('ta_id', $activity->trans_action_id)
            ->get();*/

          /*foreach ($activity->objectives as $objective) {
            // Log::info($activity->activity_id);
            // Log::info($objective->objective_id);
            /* Log::info(DB::table('criterion_objective_outcome')
              ->join('activity_criterion', 'activity_criterion.criterion_id', '=', 'criterion_objective_outcome.criterion_id')
              ->join('criteria', 'criteria.id', '=', 'activity_criterion.criterion_id')
              ->where('activity_criterion.activity_id', $activity->activity_id)
              ->where('objective_id', $objective->objective_id)
              ->select('criteria.*')
              ->distinct()
              ->toSql());
            $objective->criterion = DB::table('criterion_objective_outcome')
              ->join('activity_criterion', 'activity_criterion.criterion_id', '=', 'criterion_objective_outcome.criterion_id')
              ->join('criteria', 'criteria.id', '=', 'activity_criterion.criterion_id')
              ->where('activity_criterion.activity_id', $activity->activity_id)
              ->where('objective_id', $objective->objective_id)
              ->select('criteria.*')
              ->distinct()
              ->get();
          }*/
        }
      }
    }
    return $grouped_courses;
  }
}