<?php

use Barryvdh\DomPDF\PDF as PDF;
// use Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\View;

class AnnualPlansController extends \BaseController
{

  /**
   * Checks whether a user has permission to view a page in this controller
   *
   * @var User $user        Authenticated user
   */
  private function userHasAccess($program_id)
  {
    $user = Auth::user();

    switch ($user->role) {
      case '3':
        $programs = $user->programs->lists('id');

        // If program does not belong to user, show 403
        if (!in_array($program_id, $programs))
          return false;

        break;

      case '2':
        $programs = Program::where('school_id', $user->school_id)->lists('id');

        // If program is not in user's school, show 403
        if (!in_array($program_id, $programs))
          return false;

        break;
      case '4':
        return false;
    }

    return true;
  }

  public function viewAllPlans($program_id)
  {
    $program = Program::find($program_id);
    $title = "Annual Plans for " . $program->name;

    $annual_plans = DB::select("select semester_start, semester_end, program_id, annual_plans.id, academic_year from annual_plans, annual_cycle   where annual_plans.annual_cycle_id = annual_cycle.id and program_id ={$program_id} order by semester_start desc");


    return View::make('local.managers.shared.view-annual-plans', compact('title', 'program_id', 'annual_plans'));
  }

  /**
   * Lists annual plans by year and program
   * @var string $title     Title for page
   * @var Program $programs Collection of programs user has access to
   * @var User $user        Authenticated user
   * @var Quinquennium $quinquenniums      All current or past quinquenniums
   * @var Quinquennium $current_quinquennium      Current quinquennium
   */

  public function postReport()
  {
    $program_id = Input::get('program_id') + 0;
    $realized = Input::get('realized');
    $logrado = Input::get('logrado');
    $continued = Input::get('continued');
    $semester = Input::get('semester');
    $typ_objective = Input::get('typ_objective');
    $transformative = Input::get('transformative');
    $comments = Input::get("comments");
    $annual_id = Input::get("annual_id") + 0;
    $id = Auth::user()['id'];

    for ($i = 0; $i < count($semester); $i++) {
      $real = $realized[$i] + 0;
      $logr = $logrado[$i] + 0;
      $cont = $continued[$i] + 0;
      $obj = $typ_objective[$i] + 0;
      $trans = $transformative[$i] + 0;
      $sem = $semester[$i] + 0;
      $comment = $comments[$i];
      //if it was continued
      if ($real == 1) $real = 2;
      else $real = 1;
      if ($cont == 1) $cont = $sem + 1;
      else $cont = "NULL";
      $annual_trans_id = DB::select("select id from annual_plan_transformative where annual_plan_id ={$annual_id} and trans_id = {$trans} and typ_semester_objective_id = {$obj}")[0]->id;


      $queryUpdate = DB::select("select * from annual_report_transformative where annual_trans_id = {$annual_trans_id}");
      if (!count($queryUpdate)) {
        DB::insert("insert into annual_report_transformative (accomplished, cycle_of_life, semester_used, semester_continue, annual_trans_id, supervised_coordinator_id, comments) values ({$logr},{$real},{$sem},{$cont},{$annual_trans_id}, {$id}, '{$comment}')");
      } else {
        DB::update("update annual_report_transformative set accomplished = {$logr}, cycle_of_life ={$real}, semester_used ={$sem}, semester_continue={$cont}, supervised_coordinator_id={$id}, comments = '{$comment}' where annual_trans_id ={$annual_trans_id}");
      }
    }
    return;
  }
  /*public function index()
  {
    $title = 'Annual Plans';
    $user = Auth::user();
    $quinquenniums = Quinquennium::where('start_date', '<=', date('Y-m-d'))->get();
    $current_quinquennium = Quinquennium::where('start_date', '<=', date('Y-m-d'))
      ->where('end_date', '>=', date('Y-m-d'))
      ->first();

    switch ($user->role) {
      case '1':
        $programs = Program::all();
        break;
      case '2':
        $programs = Program::where('school_id', $user->school_id)->get();
        break;
      case 3:
        $programs = $user->programs;
        break;
      default:
        App::abort('404');
        break;
    }

    return View::make('local.managers.shared.index_annual_plans', compact('title', 'quinquenniums', 'programs', 'current_quinquennium'));
  }*/
  public function adminIndex()
  {
    //Log::info("Entre" . json_encode($this));

    $title = "Annual Plans";
    $programs = Program::orderBy('name', "ASC")->get();
    $annual_cycle = DB::table('annual_cycle')
      ->orderBy('academic_year', "DESC")
      ->get();
    $report = 0;

    return View::make('local.managers.admins.appraisal-program', compact('title', 'programs', 'annual_cycle', 'report'));
  }

  public function adminReportIndex()
  {
    $title = "Annual Reports";
    $programs = Program::orderBy('name', "ASC")->get();
    $annual_cycle = DB::table('annual_cycle')
      ->orderBy('academic_year', "DESC")
      ->get();
    $report = 1;

    return View::make('local.managers.admins.appraisal-program', compact('title', 'programs', 'annual_cycle', 'report'));
  }

  //fetch submitted

  public function  fetchSubmitted()
  {
    $annual_cycle = Input::get('annual_cycle');
    $report = Input::get('report');
    return DB::table("annual_plans")
      ->join('paths_for_annual_plans as pa', 'pa.annual_plan_id', '=', 'annual_plans.id')
      ->where('report', $report)
      ->where('annual_cycle_id', $annual_cycle)
      ->get();
  }



  public function showPlan($program_id, $typ_id = null)
  {
    $program = Program::find($program_id);
    $title = "Annual Plans for " . $program->name;
    //$typ_parts = DB::select("select * from typ_parts");

    //     $current_typ = DB::select("select * from three_year_plan where year_start <=" . date('Y') . " and year_end >=" . date('Y'))[0];
    $current_typ_arr = DB::select("select * from three_year_plan where year_start <=" . date('Y') . " and year_end >=" . date('Y'));
    // 	var_dump($current_typ);exit();
    if (!empty($current_typ_arr)) $current_typ = $current_typ_arr[0];
    else {
      $current_typ = new stdClass();
      $current_typ->id = 0;
    }


    //$program = Program::where('id', '=', $program_id)->first();

    //Dame los annual plans que esten dentro del three year plan


    $annual_plans = DB::table('annual_cycle')
      ->join('annual_plans', 'annual_cycle_id', '=', 'annual_cycle.id')
      ->join('typ_semester_outcome', function ($j) {
        $j->on('typ_semester_outcome.semester_id', '=', 'annual_cycle.semester_start')
          ->orOn('typ_semester_outcome.semester_id', '=', 'annual_cycle.semester_end');
      })
      ->join('typ_program', function ($j) {
        $j->on('typ_program.program_id', '=', 'annual_plans.program_id')
          ->on('typ_program.id', '=', 'typ_semester_outcome.typ_program_id');
      })
      ->where('annual_plans.program_id', $program_id)
      ->orderBy('semester_start', 'desc')
      ->select('annual_cycle.academic_year', 'annual_plans.*')
      ->distinct()
      ->get();
    /*$annual_plans = DB::select("
    
    select 
      academic_year, 
      semester_start, 
      semester_end, 
      program_id, 
      annual_plans.id as id 
    from annual_plans 
    join annual_cycle on annual_cycle_id = annual_cycle.id 
    where program_id = {$program_id} 
    and(
      semester_start in(
        select semester_id 
        from typ_semester_outcome 
        join typ_program on typ_semester_outcome.typ_program_id = typ_program.id 
        where program_id = {$program_id} )
      or semester_end in(
        select semester_id 
        from typ_semester_outcome 
        join typ_program on typ_semester_outcome.typ_program_id = typ_program.id 
        where program_id = {$program_id} )
      )
      order by semester_start desc");*/
    // $annual_plans = DB::select("select academic_year, semester_start, semester_end, program_id, annual_plans.id as id from annual_plans, annual_cycle where program_id = {$program_id} and annual_cycle.id = annual_plans.annual_cycle_id order by annual_plans.id desc ");
    // Log::info($annual_plans);
    $outcomes = array();
    $allSemesterOrder = array();
    //     Log::info($annual_plans);
    /*foreach ($annual_plans as $an_plan) {
      Log::info($an_plan->id);
      $outcomes[$an_plan->id]["first"] = DB::select("select * from outcomes where id in (select outcome_id from typ_semester_outcome where semester_id = {$an_plan->semester_start} and typ_program_id in (select id from typ_program where program_id ={$an_plan->program_id} and three_year_plan_id ={$current_typ->id} ))");
      $allSemesterOrder[$an_plan->id]["first"] = DB::select("select * from semesters where id = {$an_plan->semester_start}")[0];
      $outcomes[$an_plan->id]["second"] = DB::select("select * from outcomes where id in (select outcome_id from typ_semester_outcome where semester_id ={$an_plan->semester_end} and typ_program_id in (select id from typ_program where program_id ={$an_plan->program_id} and three_year_plan_id = {$current_typ->id} ))");
      $allSemesterOrder[$an_plan->id]["second"] = DB::select("select * from semesters where id = {$an_plan->semester_end}")[0];
    }*/
    //$alltyp = DB::select('select * from three_year_plan order by id desc');
    //$current_typ = $current_typ->id;

    return View::make('local.managers.shared.annual-plans', compact('title', 'annual_plans', 'current_typ', 'program', 'outcomes', 'allSemesterOrder', 'alltyp'));
  }

  public function fetchInfo()
  {
    //     Log::info(Input::get('id'));
    $an_plan = DB::table("annual_plans")
      ->join('annual_cycle', 'annual_cycle.id', '=', 'annual_plans.annual_cycle_id')
      ->where('annual_plans.id', '=', Input::get('id'))
      ->select('annual_plans.id as id', 'program_id', 'academic_year', 'semester_start', 'semester_end', 'is_submitted')
      ->first();

    $years = explode('-', $an_plan->academic_year);
    $current_typ_program = DB::table('typ_program')
      ->join('typ_semester_outcome', 'typ_semester_outcome.typ_program_id', '=', 'typ_program.id')


      ->where('program_id', $an_plan->program_id)
      ->where(function ($query) use (&$an_plan) {
        $query->where('semester_id', $an_plan->semester_start)
          ->orWhere('semester_id', $an_plan->semester_end);
      })
      ->select('typ_program.*')
      ->first();
    //     Log::info(array($an_plan));
    //     Log::info(array($current_typ_program));

    //DB::select("select * from typ_program where program_id = {$an_plan->program_id} and three_year_plan_id in (select id from three_year_plan where year_start <= {$years[0]} and year_end>= {$years[1]})")[0];


    $json_to_send = [];
    $json_to_send["annual_plans"] = $an_plan;

    $json_to_send["outcomes"]["first"] = DB::table('outcomes')
      ->join('typ_semester_outcome', 'typ_semester_outcome.outcome_id', '=', 'outcomes.id')
      ->join('typ_semester_objectives', 'typ_semester_outcome.id', '=', 'typ_semester_objectives.typ_semester_outcome_id')
      ->join('typ_semester_courses', 'typ_semester_objectives.id', '=', 'typ_semester_courses.typ_semester_objective_id')
      ->where('semester_id', $an_plan->semester_start)
      ->where('typ_program_id', $current_typ_program->id)

      ->select('outcomes.*', 'typ_semester_outcome.id as typ_semester_outcome_id')
      ->groupBy('typ_semester_outcome_id')
      ->get();

    //DB::select("select * from outcomes where id in (select outcome_id from typ_semester_outcome where semester_id = {$an_plan->semester_start} and typ_program_id = {$current_typ_program->id})");
    $json_to_send["allSemesterOrder"]["first"] = DB::select("select * from semesters where id = {$an_plan->semester_start}")[0];
    $json_to_send["outcomes"]["second"] = DB::table('outcomes')
      ->join('typ_semester_outcome', 'typ_semester_outcome.outcome_id', '=', 'outcomes.id')
      ->join('typ_semester_objectives', 'typ_semester_outcome.id', '=', 'typ_semester_objectives.typ_semester_outcome_id')
      ->join('typ_semester_courses', 'typ_semester_objectives.id', '=', 'typ_semester_courses.typ_semester_objective_id')

      ->where('semester_id', $an_plan->semester_end)
      ->where('typ_program_id', $current_typ_program->id)
      ->select('outcomes.*', 'typ_semester_outcome.id as typ_semester_outcome_id')
      ->groupBy('typ_semester_outcome_id')
      ->get();

    //DB::select("select * from outcomes where id in (select outcome_id from typ_semester_outcome where semester_id ={$an_plan->semester_end} and typ_program_id  = {$current_typ_program->id})");



    $json_to_send["allSemesterOrder"]["second"] = DB::select("select * from semesters where id = {$an_plan->semester_end}")[0];
    return json_encode($json_to_send);
  }
  /**
   * Page to create a new plan for the current quinquennium
   * @var string $title     Title for page
   * @var Program $programs Collection of programs user has access to
   * @var Outcome $outcomes      List of outcomes ordered by name
   * @var User $user      Currently logged user
   * @var Course $courses      Courses for a particular program
   */
  public function fetchTYP($program_id)
  {
    $typ_info = array();
    $semester = DB::select("select * from semesters where id=?", array(Input::get('semester')))[0];

    $typ_semester_outcome_id = Input::get('typ_semester_outcome_id');
    //$typ_info['courses'] = DB::select("select * from courses where id in (select course_id from typ_semester_courses where typ_semester_outcome_id in (select id from typ_semester_outcome where semester_id ={$semester->id} and typ_program_id in (select id from typ_program where program_id ={$program_id} )and outcome_id = ?))", array(Input::get('id')));
    //foreach ($typ_info['courses'] as $course) {
    //  $typ_info['courses_objective'][$course->id] = DB::select("select * from objectives where id in (select objective_id from typ_semester_objectives where typ_semester_course_id in (select id from typ_semester_courses where typ_semester_outcome_id in (select id from typ_semester_outcome where semester_id = {$semester->id} and typ_program_id in (select id from typ_program where program_id ={$program_id}))and course_id ={$course->id}))");
    //  foreach ($typ_info['courses_objective'][$course->id] as $objective) {
    //    $typ_info['criteria'][$objective->id] = DB::select("select * from criteria where id in (select criterion_id from criterion_objective_outcome where outcome_id = ? and objective_id = {$objective->id})", array(Input::get('id')));
    //  }
    //}
    //$typ_info['courses'] = DB::select("select * from courses where id in (select course_id from typ_semester_courses where typ_semester_objective_id in (select id from typ_semester_objectives where typ_semester_outcome_id in (select id from type_semester_outcome where semester_id ={$semester->id} and typ_program_id in (select id from typ_program where program_id ={$program_id} )and outcome_id = ?)))", array(Input::get('id')));
    //$typ_info['unique_objective'] = DB::select("select * from objectives where id in (select distinct objective_id from typ_semester_objectives where  typ_semester_outcome_id in (select id from typ_semester_outcome where semester_id = {$semester->id} and outcome_id =? and typ_program_id in (select id from typ_program where program_id ={$program_id})))", array(Input::get('id')));
    //foreach ($typ_info['unique_objective'] as $objective) {
    //  $typ_info['courses_objective'][$objective->id] = DB::select("select * from courses where id in (SELECT course_id from typ_semester_courses where typ_semester_outcome_id in (select id from typ_semester_outcome where semester_id={$semester->id} and outcome_id =? and typ_program_id in (select id from typ_program where program_id = {$program_id})) and id in (select typ_semester_course_id from typ_semester_objectives where objective_id  = {$objective->id}))", array(Input::get('id')));
    //  $typ_info['criteria'][$objective->id] = DB::select("select * from criteria where id in (select criterion_id from criterion_objective_outcome where outcome_id = ? and objective_id = {$objective->id})", array(Input::get('id')));
    //}
    $annual_plan = DB::select("select annual_plans.id from annual_plans, annual_cycle where annual_plans.annual_cycle_id = annual_cycle.id and (semester_start = {$semester->id} or semester_end ={$semester->id}) and program_id ={$program_id}")[0];
    //$typ_info['expected_target'] = DB::select("select * from target_outcomes_program where program_id = {$program_id} and semester_id = {$semester->id}");
    $typ_info['expected_target'] = DB::table('target_outcomes_program')
      ->where('program_id', $program_id)
      ->where('semester_id', $semester->id)
      ->first();
    if (!$typ_info['expected_target']) {
      DB::beginTransaction();

      DB::table('target_outcomes_program')->insert(
        array(
          'program_id' => $program_id,
          'semester_id' => $semester->id,
          'expected_target' => 70.00
        )
      );
      DB::commit();
      $typ_info['expected_target'] = DB::table('target_outcomes_program')
        ->where('program_id', $program_id)
        ->where('semester_id', $semester->id)
        ->first();
    }

    $typ_info['objectives'] = DB::select("select * from objectives where id in (select objective_id from typ_semester_objectives where typ_semester_outcome_id in(select id from typ_semester_outcome where outcome_id = ? and semester_id = {$semester->id} and typ_program_id in (select id from typ_program where program_id ={$program_id})))", array(Input::get('id')));
    $typ_info['transformative_actions'] = DB::select("select * from transformative_actions where by_professor =0 and is_custom=0");
    foreach ($typ_info['objectives'] as $objective) {

      $typ_info['courses'][$objective->id] = DB::select("select c.id, c.number, c.name, c.code, typ.id typ_course_id from courses c, typ_semester_courses typ, (select course_id, id  from typ_semester_courses where typ_semester_objective_id in (select id from typ_semester_objectives where objective_id ={$objective->id} and typ_semester_outcome_id in (select id from typ_semester_outcome where outcome_id =? and semester_id ={$semester->id} and typ_program_id in(select id from typ_program where program_id ={$program_id})))) rel where typ.course_id =c.id and rel.course_id = c.id and typ.id = rel.id ", array(Input::get('id')));

      $typ_info['criteria'][$objective->id] = DB::select("select * from criteria where deleted_at IS NULL and id in (select criterion_id from criterion_objective_outcome join program_criterion_objective_outcome on program_criterion_objective_outcome.cri_obj_out_id = criterion_objective_outcome.id where outcome_id = ? and program_id  = {$program_id} and objective_id = {$objective->id})", array(Input::get('id')));
      //       Log::info($typ_info['criteria'][$objective->id]);
      $typ_info['typ_objective_id'][$objective->id] = DB::select("select id from typ_semester_objectives where objective_id = {$objective->id} and typ_semester_outcome_id in (select id from typ_semester_outcome where outcome_id =? and semester_id ={$semester->id} and typ_program_id in (select id from typ_program where program_id ={$program_id}))", array(Input::get('id')));
      //       Log::info($typ_info['typ_objective_id'][$objective->id]);
      $typ_info['typ_objective_id'][$objective->id] = $typ_info['typ_objective_id'][$objective->id][0];

      //       Log::info($typ_info['typ_objective_id'][$objective->id]->id);
      //       Log::info($annual_plan->id);
      //  $typ_info['annual_plans_transformative'][$objective->id] = DB::select(
      //    "select trans_id from annual_plan_transformative
      //     where annual_plan_id={$annual_plan->id} 
      //     and typ_semester_objective_id ={$typ_info['typ_objective_id'][$objective->id]->id}"
      //  );
      foreach ($typ_info['courses'][$objective->id] as $course) {
        $typ_info['selected_criteria'][$objective->id][$course->typ_course_id] = DB::select("select criteria_id, typ_semester_course_id typ_course_id from annual_plan_objective where annual_plan_id ={$annual_plan->id} and typ_semester_course_id ={$course->typ_course_id} ");
        $typ_info['annual_plans_transformative'][$objective->id][$course->typ_course_id] = DB::table('annual_plan_transformative')
          ->select('trans_id')
          ->where('annual_plan_id', $annual_plan->id)
          ->where('typ_semester_course_id', $course->typ_course_id)
          ->get();
        //Log::info($course->typ_course_id);
        $typ_info['custom_transformative'][$objective->id][$course->id] = DB::table('transformative_actions')
          ->join('ta_course', 'ta_course.ta_id', '=', 'transformative_actions.id')
          ->join('transformative_objective', 'transformative_objective.ta_id', '=', 'transformative_actions.id')
          ->where('is_custom', 1)
          ->where('by_professor', 0)
          ->where('ta_course.course_number', $course->number)
          ->where('ta_course.course_code', $course->code)
          ->where('transformative_objective.objective_id', $objective->id)
          ->get();
      }
    }
    $typ_info['annual_plan'] = $annual_plan;
    //     Log::info($typ_info);

    $typ_info['transformative_actions_for_outcome'] = DB::table('transformative_actions')
      ->join('transformative_typ_outcome', 'transformative_typ_outcome.trans_id', '=', 'transformative_actions.id')
      ->where('transformative_typ_outcome.typ_semester_outcome_id', $typ_semester_outcome_id)

      ->get();
    $typ_info['categories'] = "<option value='0'>Nothing Selected</option>";

    $types = DB::table('transformative_actions')
      ->select('type_of_TA', 'is_custom')
      ->where('type_of_TA', '<>', '')
      ->where(function ($query) use (&$program_id) {
        $query->whereNull('program_id')
          ->orWhere('program_id', $program_id);
      })
      ->where('by_professor', 0)
      ->groupBy('type_of_TA')
      ->get();
    $optGroupGeneral = "<optgroup label='General Transformative Actions'>";
    $optGroupCustom = "<optgroup label ='Program Custom Actions'>";
    foreach ($types as $type) {

      if ($type->is_custom) {
        $optGroupCustom .= "<option value = '" . $type->type_of_TA . "' data-is-custom = '1'>" . $type->type_of_TA . "</option>";
      } else {
        $optGroupGeneral .= "<option value = '" . $type->type_of_TA . "' data-is-custom = '0'>" . $type->type_of_TA . "</option>";
      }
    }
    $typ_info['categories'] .= $optGroupGeneral . '</optgroup>';
    $typ_info['categories'] .= $optGroupCustom . '</optgroup>';


    $typ_info['categories'] .= '<option value ="new"> New Type of Transformative Action</option>';
    return json_encode($typ_info);
  }
  public function deleteTA()
  {
    $annual_id = Input::get('annual_id') + 0;
    $typ_id = Input::get('typ_id') + 0;
    $trans_id = Input::get('TA_id') + 0;

    DB::delete("delete from `annual_plan_transformative` where annual_plan_id ={$annual_id} and typ_semester_course_id ={$typ_id} and trans_id={$trans_id}");
    return;
  }

  public function postTA()
  {
    $annual_id = Input::get('annual_id') + 0;
    $TA_id = Input::get('TA_id') + 0;
    $typ_id = Input::get('typ_course_id') + 0;
    $old_ta = Input::get('old_ta') + 0;
    $id = Auth::user()['id'];
    $date = date('Y-m-d');
    $date = strtotime($date);


    $query = DB::select("select * from annual_plan_transformative where annual_plan_id ={$annual_id} and trans_id ={$old_ta} and typ_semester_course_id ={$typ_id}");

    if (!count($query)) {
      DB::insert("insert into `annual_plan_transformative` (`annual_plan_id`,`trans_id`, `typ_semester_course_id`, `proposing_coordinator_id`, `proposed_date`) values({$annual_id},{$TA_id},{$typ_id}, {$id}, now() ) ");
      return "Insert Successful";
    } else {
      if ($TA_id == 0) {
        DB::delete("delete from annual_plan_transformative where trans_id={$TA_id} and annual_plan_id ={$annual_id} and typ_semester_course_id ={$typ_id}");
        return "deleted";
      } else {
        DB::update("update annual_plan_transformative set trans_id = {$TA_id}, proposing_coordinator_id = {$id}, proposed_date = now() where trans_id={$old_ta} and annual_plan_id ={$annual_id} and typ_semester_course_id ={$typ_id}");
        return "updated";
      }
    }
  }

  public function CreateOrEdit($program_id)
  {

    $semester_id = Input::get('semester_id');
    $expected_target = Input::get('expected_target');

    $exist = DB::select("select * from target_outcomes_program where program_id = {$program_id} and semester_id = {$semester_id}");


    if ($exist) {
      //update
      DB::update("update target_outcomes_program set expected_target = {$expected_target}, updated_at = now() where program_id = {$program_id} and semester_id = {$semester_id}");
    } else {
      //create a new one
      DB::insert("insert into target_outcomes_program (program_id, semester_id, expected_target, created_at, updated_at) values({$program_id}, {$semester_id}, '{$expected_target}', '{now()}', '{now()}')");
    }
    return;
  }
  public function transformativeReport()
  {
    $json_to_send = array();
    $annual_id = Input::get('an_id');
    $transformative_action_info = DB::select("select * from transformative_actions where id in (select distinct trans_id from annual_plan_transformative where annual_plan_id = {$annual_id}) ");
    foreach ($transformative_action_info as $trans) {
      $json_to_send['Trans_act'][$trans->id] = $trans;
      $json_to_send['outcomes'][$trans->id] = DB::select("select * from outcomes where id in (select outcome_id from typ_semester_outcome where id in(select typ_semester_outcome_id from typ_semester_objectives where id in (select typ_semester_objective_id from annual_plan_transformative where trans_id ={$trans->id} and annual_plan_id = {$annual_id})))");

      foreach ($json_to_send['outcomes'][$trans->id] as $outcome) {
        $json_to_send['typ_objective'][$outcome->id][$trans->id] = DB::select("select * from typ_semester_objectives where typ_semester_outcome_id in (select id from typ_semester_outcome where outcome_id ={$outcome->id}) and id in (select typ_semester_objective_id from annual_plan_transformative where annual_plan_id ={$annual_id} and trans_id = {$trans->id})");
        foreach ($json_to_send['typ_objective'][$outcome->id][$trans->id] as $typ) {
          $json_to_send['objective'][$outcome->id][$typ->id][$trans->id] = DB::select("select * from objectives where id = {$typ->objective_id}")[0];
          $json_to_send['coordinator'][$outcome->id][$typ->id][$trans->id] = DB::select("select * from users where id in (select proposing_coordinator_id from annual_plan_transformative where typ_semester_objective_id = {$typ->id} and annual_plan_id = {$annual_id} and trans_id = {$trans->id})")[0];
          $json_to_send['proposed_date'][$outcome->id][$typ->id][$trans->id] = DB::select("select proposed_date from annual_plan_transformative where typ_semester_objective_id = {$typ->id} and annual_plan_id = {$annual_id} and trans_id = {$trans->id} ")[0];
          $json_to_send['all_info_report'][$outcome->id][$typ->id][$trans->id] = DB::select("select art.accomplished, art.cycle_of_life, semesters.name, art.semester_continue,  art.annual_trans_id, art.supervised_coordinator_id  from annual_report_transformative art, (select id from annual_plan_transformative where typ_semester_objective_id = {$typ->id} and annual_plan_id = {$annual_id} and trans_id = {$trans->id} ) apt, semesters  where art.annual_trans_id = apt.id and semesters.id = art.semester_used")[0];
        }
      }


      if ($trans->user_id) {
        $json_to_send['suggested'][$trans->id] = DB::select("select * from users where id = {$trans->user_id}");
      }
    }
    return json_encode($json_to_send);
  }

  public function deleteCriteria()
  {
    $criteria = Input::get('criteria') + 0;
    $typ_course_id = Input::get('typ_course_id') + 0;
    $annual_plan = Input::get('annual_plan') + 0;
    $old_criteria = Input::get('old_criteria') + 0;
    $message = '';

    DB::delete("delete from annual_plan_objective where annual_plan_id ={$annual_plan} and typ_semester_course_id ={$typ_course_id} and criteria_id={$criteria}");
    return;
  }

  public function fetchAllTables()
  {
    $annual_plan = array();
    $an_id = Input::get('id');
    $program_id = Input::get('program_id');

    $an_semesters = DB::select("select semester_start, semester_end, program_id from annual_plans, annual_cycle where annual_plans.annual_cycle_id = annual_cycle.id and annual_plans.id ={$an_id} and program_id ={$program_id}")[0];

    $annual_plan['first']['outcomes'] = DB::select("select * from outcomes where id in (select outcome_id from typ_semester_outcome where semester_id = {$an_semesters->semester_start} and typ_program_id in(select id from typ_program where program_id ={$an_semesters->program_id}))");

    $annual_plan['second']['outcomes'] = DB::select("select * from outcomes where id in (select outcome_id from typ_semester_outcome where semester_id = {$an_semesters->semester_end} and typ_program_id in(select id from typ_program where program_id ={$an_semesters->program_id}))");

    $annual_plan['first']['semester'] = array('id' => $an_semesters->semester_start);
    $annual_plan['second']['semester'] = array('id' => $an_semesters->semester_end);
    foreach ($annual_plan['first']['outcomes'] as $outcomes) {

      $annual_plan['first']['objectives'][$outcomes->id] = DB::select("select * from objectives where id in (select objective_id from typ_semester_objectives where typ_semester_outcome_id in(select id from typ_semester_outcome where outcome_id = {$outcomes->id} and semester_id = {$an_semesters->semester_start} and typ_program_id in (select id from typ_program where program_id ={$an_semesters->program_id})))");
      //Log::info($outcomes->id);
      //       Log::info($annual_plan['first']['objectives'][$outcomes->id]);
      foreach ($annual_plan['first']['objectives'][$outcomes->id] as $objective) {
        $annual_plan['first']['typ_objective_id'][$objective->id] = DB::select("select id from typ_semester_objectives where objective_id = {$objective->id} and  typ_semester_outcome_id in (select id from typ_semester_outcome where outcome_id ={$outcomes->id} and semester_id ={$an_semesters->semester_start} and typ_program_id in(select id from typ_program where program_id ={$an_semesters->program_id})) ")[0];
        $annual_plan['first']['courses'][$objective->id] = DB::select("select typ.id typ_course_id, typ.course_id, c.code, c.number, c.name from (select course_id, id from typ_semester_courses where typ_semester_objective_id = {$annual_plan['first']['typ_objective_id'][$objective->id]->id}) typ, courses c where c.id = typ.course_id");
        foreach ($annual_plan['first']['courses'][$objective->id] as $course) {
          $annual_plan['first']['criteria'][$objective->id][$course->typ_course_id] = DB::select("select * from criteria where  id in(select criteria_id from annual_plan_objective where annual_plan_id = {$an_id} and typ_semester_course_id = {$course->typ_course_id} )");
          $annual_plan['first']['trans_actions'][$objective->id][$course->typ_course_id] = DB::select("select * from transformative_actions where id in (select trans_id from annual_plan_transformative where typ_semester_course_id = {$course->typ_course_id})");
        }

        //         Log::info($objective->id);
        /*$annual_plan['first']['trans_actions'][$objective->id] = DB::select("select * from transformative_actions where id in (select trans_id from annual_plan_transformative where typ_semester_objective_id ={$annual_plan['first']['typ_objective_id'][$objective->id]->id})");
        foreach ($annual_plan['first']['trans_actions'][$objective->id] as $trans) {
          Log::info($annual_plan['first']['typ_objective_id'][$objective->id]->id);
          Log::info($trans->id);
          Log::info($an_id);
          $annual_plan['fill_info'][$annual_plan['first']['typ_objective_id'][$objective->id]->id][$trans->id] = DB::select("select * from annual_report_transformative where annual_trans_id in (select id from annual_plan_transformative where trans_id = {$trans->id} and typ_semester_objective_id ={$annual_plan['first']['typ_objective_id'][$objective->id]->id} and annual_plan_id = {$an_id} )");
          if (count($annual_plan['fill_info'][$annual_plan['first']['typ_objective_id'][$objective->id]->id][$trans->id])) {
            Log::info("entró");
            $annual_plan['fill_info'][$annual_plan['first']['typ_objective_id'][$objective->id]->id][$trans->id] =  $annual_plan['fill_info'][$annual_plan['first']['typ_objective_id'][$objective->id]->id][$trans->id][0];
          }
        }*/
      }
    }
    foreach ($annual_plan['second']['outcomes'] as $outcomes) {
      $annual_plan['second']['objectives'][$outcomes->id] = DB::select("select * from objectives where id in (select objective_id from typ_semester_objectives where typ_semester_outcome_id in(select id from typ_semester_outcome where outcome_id = {$outcomes->id} and semester_id = {$an_semesters->semester_end} and typ_program_id in (select id from typ_program where program_id ={$an_semesters->program_id})))");
      foreach ($annual_plan['second']['objectives'][$outcomes->id] as $objective) {
        $annual_plan['second']['typ_objective_id'][$objective->id] = DB::select("select id from typ_semester_objectives where objective_id = {$objective->id} and  typ_semester_outcome_id in (select id from typ_semester_outcome where outcome_id ={$outcomes->id} and semester_id ={$an_semesters->semester_end} and typ_program_id in(select id from typ_program where program_id ={$an_semesters->program_id})) ")[0];

        $annual_plan['second']['courses'][$objective->id] = DB::select("select typ.id typ_course_id, typ.course_id, c.code, c.number, c.name from (select course_id, id from typ_semester_courses where typ_semester_objective_id = {$annual_plan['second']['typ_objective_id'][$objective->id]->id}) typ, courses c where c.id = typ.course_id");
        foreach ($annual_plan['second']['courses'][$objective->id] as $course) {
          $annual_plan['second']['criteria'][$objective->id][$course->course_id] = DB::select("select * from criteria where id in(select criteria_id from annual_plan_objective where annual_plan_id = {$an_id} and typ_semester_course_id ={$course->typ_course_id})");
          $annual_plan['second']['trans_actions'][$objective->id][$course->typ_course_id] = DB::select("select * from transformative_actions where id in (select trans_id from annual_plan_transformative where typ_semester_course_id = {$course->typ_course_id})");
        }
        /*
        $annual_plan['second']['trans_actions'][$objective->id] = DB::select("select * from transformative_actions where id in (select trans_id from annual_plan_transformative where typ_semester_objective_id ={$annual_plan['second']['typ_objective_id'][$objective->id]->id})");
        Log::info($annual_plan['second']['typ_objective_id'][$objective->id]->id);
        foreach ($annual_plan['second']['trans_actions'][$objective->id] as $trans) {

          $annual_plan['fill_info'][$annual_plan['second']['typ_objective_id'][$objective->id]->id][$trans->id] = DB::select("select * from annual_report_transformative where annual_trans_id in (select id from annual_plan_transformative where trans_id = {$trans->id} and typ_semester_objective_id ={$annual_plan['second']['typ_objective_id'][$objective->id]->id} and annual_plan_id = {$an_id} )");
          Log::info("lol");
          if (count($annual_plan['fill_info'][$annual_plan['second']['typ_objective_id'][$objective->id]->id][$trans->id])) {
            Log::info("entró");
            $annual_plan['fill_info'][$annual_plan['second']['typ_objective_id'][$objective->id]->id][$trans->id] =  $annual_plan['fill_info'][$annual_plan['second']['typ_objective_id'][$objective->id]->id][$trans->id][0];
          }
        }*/
      }
    }

    return json_encode($annual_plan);
  }

  public function postAnnualPlan()
  {
    $criteria = Input::get('criteria') + 0;
    $typ_course_id = Input::get('typ_course_id') + 0;
    $annual_plan = Input::get('annual_plan') + 0;
    $old_criteria = Input::get('old_criteria') + 0;
    $message = '';
    $query = DB::select("select * from annual_plan_objective where annual_plan_id ={$annual_plan} and typ_semester_course_id = {$typ_course_id} and criteria_id ={$old_criteria}");
    if (!count($query)) {
      $query = DB::select("select * from annual_plan_objective where annual_plan_id ={$annual_plan} and typ_semester_course_id = {$typ_course_id} and criteria_id ={$criteria}");

      if (!count($query)) {

        DB::insert("insert into `annual_plan_objective` (`annual_plan_id`, `typ_semester_course_id`, `criteria_id`) values ({$annual_plan}, {$typ_course_id}, {$criteria})");
        $message = "inserting was a success";
      } else {
        $message = "Duplicate entry, please choose another criteria.";
      }
    } else {
      $query = DB::select("select * from annual_plan_objective where annual_plan_id ={$annual_plan} and typ_semester_course_id = {$typ_course_id} and criteria_id ={$criteria}");

      if (!count($query)) {
        DB::update("update `annual_plan_objective` set criteria_id = {$criteria} where annual_plan_id = {$annual_plan} and typ_semester_course_id ={$typ_course_id} and criteria_id = {$old_criteria} ");
        $message = "Updating was a success";
      } else {
        $message = "Duplicate entry, please choose another criteria.";
      }
    }
    return $message;
  }
  public function create(Program $program)
  {
    $title = 'New Annual Plan for ' . $program->name;
    $user = Auth::user();
    $outcomes = Outcome::orderBy('name')->get();

    $current_quinquennium = Quinquennium::where('start_date', '<=', date('Y-m-d'))
      ->where('end_date', '>=', date('Y-m-d'))
      ->first();

    $courses = Course::select('id', 'code', 'number', 'name')
      ->where('program_id', $program->id)
      ->groupBy('name')
      ->orderBy('code', 'ASC')
      ->orderBy('number', 'ASC')
      ->orderBy('name', 'ASC')
      ->get();

    // Check if user can create a plan
    if (!$this->userHasAccess($program->id)) {
      return View::make('global.403');
    }

    return View::make('local.managers.shared.create_annual_plan', compact('title', 'program', 'current_quinquennium', 'outcomes', 'courses'));
  }

  function fetchAnnualReport()
  {
    $program_id = Input::get('program_id');
    $annual_plan_id = Input::get('annual_plan_id');
    $semester_start = Input::get('semester_start');
    $semester_end = Input::get('semester_end');
    $academic_year = Input::get('academic_year');

    $academic_year = (int) explode(",", $academic_year)[0];

    $course_codes = DB::table('annual_plan_objective as apo')
      ->join('typ_semester_courses as tyc', 'apo.typ_semester_course_id', '=', 'tyc.id')
      ->join('courses', 'tyc.course_id', '=', 'courses.id')
      ->where('annual_plan_id', $annual_plan_id)
      ->select('courses.code', 'courses.number')
      ->distinct()
      ->get();
    //     Log::info($course_codes);
    $all_courses_info = [];

    foreach ($course_codes as $index => $course_code) {
      //$all_courses_info['course_code'][] = $course_code->code . '_' . $course_code->number;
      $courses = Course::where(function ($query) use (&$semester_end, &$semester_start) {
        $query->where('semester_id', $semester_end)
          ->orWhere('semester_id', $semester_start);
      })
        ->where('code', $course_code->code)
        ->where('number', $course_code->number)
        ->where('program_id', $program_id)
        ->get();
      //Log::info("run number " . $index);
      //       Log::info($courses);
      foreach ($courses as $course) {
        $all_courses_info[$course_code->code . '_' . $course_code->number][] = $course->getReportObject();
      }
    }

    /*$course_codes = DB::table('typ_semester_courses')
      ->join('typ_semester_objectives as tso', 'tso.id', '=', 'typ_semester_courses.typ_semester_objective_id')
      ->join('courses', 'courses.id', '=', 'typ_semester_courses.course_id')
      ->join('typ_semester_outcome as typ_out', 'typ_out.id', '=', 'tso.typ_semester_outcome_id')
      ->join('typ_program', 'typ_out.typ_program_id', '=', 'typ_program.id')
      ->where(function ($query) use (&$semester_start, &$semester_end) {
        $query->where('typ_out.semester_id', $semester_start)
          ->orWhere('typ_out.semester_id', $semester_end);
      })
      ->where('typ_program.program_id', $program_id)
      ->select('courses.code', 'courses.number', 'typ_semester_courses.id as typ_sem_cou_id')
      ->distinct()
      ->get();*/




    /*foreach ($course_codes as $course_code) {

      $course_code->sections = DB::table('courses')
        ->join('activities', 'activities.course_id', '=', 'courses.id')
        ->join('activity_criterion', 'activity_criterion.activity_id', '=', 'activities.id')
        ->join('annual_plan_objective', 'annual_plan_objective.criteria_id', '=', 'activity_criterion.criterion_id')
        ->join('typ_semester_courses', 'typ_semester_courses.id', '=', 'annual_plan_objective.typ_semester_course_id')
        ->where('courses.code', $course_code->code)
        ->where('courses.number', $course_code->number)
        ->where('annual_plan_id', $annual_plan_id)
        ->where('annual_plan_objective.typ_semester_course_id', $course_code->typ_sem_cou_id)
        ->toSql();

      Log::info($course_code->sections);
    }*/

    return $all_courses_info;
  }
  public function selectProgramPlan()
  {

    $title = "Program Annual Reports";
    $programs = Auth::user()->school->programs;



    return View::make('local.managers.shared.annual_select', compact('title', 'programs'));
  }

  //Fetch report in annual_plan_report

  public function fetchReportWithOutcome()
  {
    $program_id = Input::get('program_id');
    $semester_id = Input::get('semester_id');
    $annual_plan_id = Input::get('annual_plan_id');
    $outcome_id = Input::get('outcome_id');
    $typ_semester_outcome_id = Input::get('typ_semester_outcome_id');

    $outcome = Outcome::where('id', $outcome_id)
      ->addSelect('outcomes.*', DB::raw("'{$typ_semester_outcome_id}' as typ_semester_outcome_id"), DB::raw("'{$semester_id}' as `semester_id`"), DB::raw("'{$program_id}' as `program_id`"))
      ->first();
    $outcome->objectives = $outcome->fetchObjectivesReport($semester_id, $program_id);
    $outcome->outcome_program_goal = DB::table('target_outcomes_program')
      ->where('program_id', $program_id)
      ->where('semester_id', $semester_id)
      ->first();
    $outcome->transforming_actions = DB::table('transformative_typ_outcome')
      ->join('transformative_actions', 'transformative_actions.id', '=', 'transformative_typ_outcome.trans_id')
      ->leftJoin('transformative_action_status', 'transformative_actions.id', '=', 'transformative_action_status.trans_id')
      ->where('typ_semester_outcome_id', $typ_semester_outcome_id)
      ->select('transformative_actions.*', 'transformative_action_status.*', 'transformative_actions.id as trans_id')
      ->get();
    $outcome->semester_info = DB::table('semesters')
      ->where('id', $semester_id)
      ->first();
    //     Log::info($typ_semester_outcome_id);
    $outcome->comments = $outcome->getCommentsAttribute();
    // $outcome->comments = "COMMENT";
    //Log::info("Comments");
    //Log::info(DB::table('typ_outcome_report_comments')
    //  ->where('typ_semester_outcome_id', $typ_semester_outcome_id)
    //  ->toSql());
    //Log::info($outcome->comments);
    $outcome->transformative_actions_categories_html = TransformativeAction::getCategoriesHtml($program_id);




    foreach ($outcome->objectives as $index => $objective) {
      //       Log::info("Ella son besties");
      //       Log::info(array($objective));
      $objective->courses = Objective::getPlanReport($objective);
    }

    return $outcome;
  }



  public function fetchObjectiveInfo()
  {
    $typ_objective_id = Input::get('typ_objective_id');
    $courses = DB::table('typ_semester_courses')
      ->join('courses', 'courses.id', '=', 'typ_semester_courses.course_id')

      ->select('courses.code', 'courses.number', 'courses.name', 'typ_semester_courses.id as typ_semester_course_id')
      ->where('typ_semester_objective_id', $typ_objective_id)
      ->distinct()
      ->get();
    foreach ($courses as $course) {
      /*$course->criteria_scale = DB::table('annual_plan_objective')
        ->join('criteria', 'criteria.id', '=', 'annual_plan_objective.criteria_id')
        ->join('criterion_scale', 'criterion_scale.criterion_id', '=', 'criteria.id')
        ->join('scales', 'scales.id', '=', 'criterion_scale.scale_id')
        ->select('criterion_scale.*', 'scales.*')
        ->where('typ_semester_course_id', $course->typ_semester_course_id)
        ->orderBy('position', 'ASC')
        ->get();*/
      $course->criteria = DB::table('annual_plan_objective')
        ->join('criteria', 'criteria.id', '=', 'annual_plan_objective.criteria_id')
        ->where('typ_semester_course_id', $course->typ_semester_course_id)
        ->select('criteria.*')
        ->get();
      foreach ($course->criteria as $criterion) {
        $criterion->scales = DB::table('criteria')
          ->join('criterion_scale', 'criterion_scale.criterion_id', '=', 'criteria.id')
          ->join('scales', 'scales.id', '=', 'criterion_scale.scale_id')
          ->select('criterion_scale.*', 'scales.*')
          ->where('criteria.id', $criterion->id)
          ->orderBy('position', 'ASC')
          ->get();
      }
    }
    return $courses;
  }

  /* public function submitAnnualPlan()
  {
    $annual_plan_id = Input::get('annual_plan_id');
    DB::table('annual_plans')->where('id', $annual_plan_id)->update(array(
      'is_submitted' => 1,
      'submitted_on' => date('Y-m-d H:i:s')
    ));
    return;
  }*/

  public function futureTransformative()
  {
    $at_text = Input::get('at_text');
    $description = Input::get('description');
    $future_typ_course_id = Input::get('future_typ_course_id');
    $future_semesters = Input::get('future_semesters');
    $type_of_ta = Input::get('type_of_TA');
    $is_custom = Input::get('is_custom');
    $program_id = Input::get('program_id');
    //$annual_plan_id = Input::get('annual_plan_id');
    $objective_id = Input::get('objective_id');
    $course_code = Input::get('course_code');
    $course_number = Input::get('course_number');
    $edit_ta_id = Input::get('edit_ta_id');

    if ($edit_ta_id) {
      DB::table('transformative_actions')
        ->where('id', $edit_ta_id)->update(array(
          'is_custom' => $is_custom,
          'at_text' => $at_text,
          'description' => $description,
          'type_of_TA' => $type_of_ta,
          'user_id' => Auth::user()->id,
          'program_id' => $program_id,
          //'by_professor' => 0,
          //'created_at' => date('Y-m-d H:i:s'),
          'updated_at' => date('Y-m-d H:i:s')
        ));
      DB::table('annual_plan_transformative')
        ->where('trans_id', $edit_ta_id)
        ->delete();
      foreach ($future_typ_course_id as $index => $typ_future_course_id) {
        $annual_plan = DB::table('annual_cycle')
          ->join('annual_plans', 'annual_plans.annual_cycle_id', '=', 'annual_cycle.id')
          ->where('program_id', $program_id)
          ->where(function ($query) use (&$future_semesters, &$index) {
            $query->where('semester_start', $future_semesters[$index])
              ->orWhere('semester_end', $future_semesters[$index]);
          })->first();
        DB::table('annual_plan_transformative')
          ->insert(array(
            'annual_plan_id' => $annual_plan->id,
            'trans_id' => $edit_ta_id,
            'typ_semester_course_id' => $typ_future_course_id,
            'proposing_coordinator_id' => Auth::user()->id,
            'proposed_date' => date('Y-m-d H:i:s')
          ));
      }
      $transformative_action = TransformativeAction::getTypCoursesWithSemesters($edit_ta_id);
      $transformative_action[0]->updated = 1;
      return $transformative_action;
    } else {
      $newTransId = DB::table('transformative_actions')
        ->insertGetId(array(
          'is_custom' => $is_custom,
          'at_text' => $at_text,
          'description' => $description,
          'type_of_TA' => $type_of_ta,
          'user_id' => Auth::user()->id,
          'program_id' => $program_id,
          'by_professor' => 0,
          'created_at' => date('Y-m-d H:i:s'),
          'updated_at' => date('Y-m-d H:i:s')
        ));
      DB::table('ta_course')->insert(array(
        'ta_id' => $newTransId,
        'course_number' => $course_number,
        'course_code' => $course_code
      ));
      DB::table('transformative_objective')->insert(array(
        'ta_id' => $newTransId,
        'objective_id' => $objective_id
      ));
      foreach ($future_typ_course_id as $index => $typ_future_course_id) {
        $annual_plan = DB::table('annual_cycle')
          ->join('annual_plans', 'annual_plans.annual_cycle_id', '=', 'annual_cycle.id')
          ->where('program_id', $program_id)
          ->where(function ($query) use (&$future_semesters, &$index) {
            $query->where('semester_start', $future_semesters[$index])
              ->orWhere('semester_end', $future_semesters[$index]);
          })->first();
        DB::table('annual_plan_transformative')
          ->insert(array(
            'annual_plan_id' => $annual_plan->id,
            'trans_id' => $newTransId,
            'typ_semester_course_id' => $typ_future_course_id,
            'proposing_coordinator_id' => Auth::user()->id,
            'proposed_date' => date('Y-m-d H:i:s')
          ));
      }


      return TransformativeAction::getTypCoursesWithSemesters($newTransId);
    }
  }

  public function fetchTheAnnualPlan()
  {
    $outcome_id = Input::get('id');
    $semester_id = Input::get('semester');
    $typ_semester_outcome_id = Input::get('typ_semester_outcome_id');
    $program_id = Input::get('program_id');

    $outcome = Outcome::find($outcome_id);

    //El nombre es annual_plan_objective, fue cambiado como mil veces por Arlene y su combo
    // Así que está mal escrito. Sorry future programmer

    $array_to_send = [];
    $array_to_send['typ_objectives'] = DB::table('typ_semester_objectives')
      ->join('objectives', 'objectives.id', '=', 'typ_semester_objectives.objective_id')
      ->where('typ_semester_outcome_id', $typ_semester_outcome_id)
      ->select('objectives.*', 'typ_semester_outcome_id', 'typ_semester_objectives.id as typ_semester_objective_id')
      ->get();
    $array_to_send['typ_courses'] = DB::table('typ_semester_objectives')
      ->join('typ_semester_courses', 'typ_semester_courses.typ_semester_objective_id', '=', 'typ_semester_objectives.id')
      ->join('courses', 'courses.id', '=', 'typ_semester_courses.course_id')
      ->where('typ_semester_outcome_id', $typ_semester_outcome_id)
      ->select('courses.*', 'typ_semester_objective_id', 'typ_semester_courses.id as typ_semester_course_id')
      ->get();
    $array_to_send['courses_criteria'] = DB::table('typ_semester_objectives')
      ->join('typ_semester_courses', 'typ_semester_courses.typ_semester_objective_id', '=', 'typ_semester_objectives.id')
      ->join('annual_plan_objective', 'annual_plan_objective.typ_semester_course_id', '=', 'typ_semester_courses.id')
      ->join('criteria', 'criteria.id', '=', 'annual_plan_objective.criteria_id')
      ->select('typ_semester_course_id', 'annual_plan_objective.*', 'criteria.*')
      ->where('typ_semester_outcome_id', $typ_semester_outcome_id)
      ->groupBy('typ_semester_course_id')
      ->get();
    $array_to_send['courses_transformative_actions'] = DB::table('typ_semester_objectives')
      ->join('typ_semester_courses', 'typ_semester_courses.typ_semester_objective_id', '=', 'typ_semester_objectives.id')
      ->join('annual_plan_transformative', 'annual_plan_transformative.typ_semester_course_id', '=', 'typ_semester_courses.id')
      ->join('transformative_actions', 'transformative_actions.id', '=', 'annual_plan_transformative.trans_id')
      ->select('typ_semester_course_id', 'annual_plan_transformative.*', 'transformative_actions.*')
      ->where('typ_semester_outcome_id', $typ_semester_outcome_id)
      ->groupBy('typ_semester_course_id')
      ->get();
    $array_to_send['transformative_outcome'] = DB::table('transformative_actions')
      ->join('transformative_typ_outcome', 'transformative_actions.id', '=', 'transformative_typ_outcome.trans_id')
      ->where('typ_semester_outcome_id', $typ_semester_outcome_id)
      ->get();

    $array_to_send['expected_target'] = DB::table('target_outcomes_program')
      ->where('program_id', $program_id)
      ->where('semester_id', $semester_id)
      ->first();
    return $array_to_send;
  }

  public function addCommentsToOutcome()
  {
    $edit_id = Input::get('edit_id');
    $typ_semester_outcome_id = Input::get('typ_outcome_semester_id');
    $comments = Input::get('comments');

    //     Log::info(Input::all());

    if ($edit_id) {
      DB::table('typ_outcome_report_comments')
        ->where('id', $edit_id)->update(array(
          'user_id' => Auth::user()->id,
          'typ_semester_outcome_id' => $typ_semester_outcome_id,
          'comments' => $comments
        ));
    } else {
      $edit_id = DB::table('typ_outcome_report_comments')->insertGetId(array(
        'user_id' => Auth::user()->id,
        'typ_semester_outcome_id' => $typ_semester_outcome_id,
        'comments' => $comments
      ));
    }
    return $edit_id;
  }
  public function deleteCommentsFromOutcome()
  {
    $comment_id = Input::get('id');

    DB::table('typ_outcome_report_comments')->where('id', $comment_id)->delete();
    return;
  }

  //Print annual report
  public function printAnnualReport($annual_id = null, $submit = null)
  {


    //$download = 0;

    $annualPlan = AnnualPlan::find($annual_id);

    //$pdf =  new PDF();
    /*$pdf = new PDF(app('config'), app("Filesystem"), app('view'), '/storage/plan_pdf');
    $pdf = $pdf->loadView('local.managers.shared.print_annual_report', compact('annualPlan', 'download'))
      ->setOrientation("landscape")

      ->setPaper('legal', 'landscape');

    $pdf->save(app_path() . '/storage/annual_pdfs/' . date('d-m-Y') . '-for-' . $annualPlan->program->id . '.pdf');
    return $pdf->download(date('d-m-Y') . '-for-' . $annualPlan->program->id . '.pdf');
    */ //pdf = $pdf->setOrientation("landscape");
    //     Log::info("submit");
    //     Log::info($submit);
    return View::make('local.managers.shared.print_annual_report', compact('annualPlan', 'submit'));
  }

  public function postAnnualReport($annual_id)
  {

    $annualPlan = AnnualPlan::findOrFail($annual_id);
    $user_id = Auth::user()->id;

    //$pdf = new PDF(app('config'), app("Filesystem"), app('view'), '/storage/plan_pdf');
    //$pdf = $pdf->loadView('local.managers.shared.print_annual_report', compact('annualPlan'))
    //  ->setOrientation("landscape")

    //  ->setPaper('legal', 'landscape');
    $path = app_path() . '/views/annual_htmls/report-on-' . date('d-m-Y') . 'ac' . $annualPlan->annual_cycle_id . '-for-' . $annualPlan->program->id . '-by-' . $user_id . '.blade.php';
    //$pdf->save($path);
    //$name = date('d-m-Y') . '-for-' . $annualPlan->program->id . '.pdf';
    //$pdf->download($name);

    //is a path already there

    $it_exists = DB::table("paths_for_annual_plans")
      ->where('path_to_pdf', $path)
      ->first();

    if (isset($it_exists)) {
      return '200';
    }
    //$user_id = Auth::user()->id;
    DB::table("paths_for_annual_plans")
      ->where('annual_plan_id', $annual_id)
      ->where('user_id', $user_id)
      ->where('report', 1)
      ->update(array(
        'last' => 0
      ));

    DB::table('paths_for_annual_plans')->insert(array(
      "path_to_pdf" => $path,
      'annual_plan_id' => $annual_id,
      'last' => 1,
      'report' => 1,
      'user_id' => $user_id,
      'date_posted' => date('Y-m-d')
    ));



    return '200';
  }

  public function annualPlansShow($annual_report_or_plan, $program_id)
  {
    $role = Auth::user()->role;
    switch ($role) {
      case 1:
      case 2:
      case 3:
        $last = [1, 0];
        break;

      case 4:
        $last = [1];

        break;
      default:
        App::abort('404');
    }

    if ($annual_report_or_plan == "report") {
      $report = 1;
    } else if ($annual_report_or_plan == "plan") {
      $report = 0;
    } else {
      App::abort('404');
    }

    $title = "Annual Plans for " . Program::findOrFail($program_id)->name;
    $paths_with_users = DB::table('paths_for_annual_plans')
      ->join('annual_plans', 'annual_plans.id', '=', 'paths_for_annual_plans.annual_plan_id')
      ->join('annual_cycle', 'annual_cycle.id', '=', 'annual_plans.annual_cycle_id')
      ->join('users', 'users.id', '=', 'paths_for_annual_plans.user_id')
      ->where('report', $report)
      ->whereIn('last', $last)
      ->where('annual_plans.program_id', $program_id)
      ->orderBy('date_posted', 'desc')
      ->select('paths_for_annual_plans.path_to_pdf', 'users.*', 'date_posted', 'annual_cycle.*', 'paths_for_annual_plans.last', 'paths_for_annual_plans.id as path_id')
      ->get();

    return View::make('local.managers.shared.new_view_annual_plans', compact('paths_with_users', 'title', 'report', 'last', 'annual_report_or_plan', 'program_id'));
  }

  public function findHTML($type_of_annual, $path_id)
  {
    $path = DB::table('paths_for_annual_plans')->where('id', $path_id)->first();

    if (isset($path)) {
      //       Log::info($path->path_to_pdf);
      //       Log::info(app_path()); //. "/views/annual_htmls/");


      //FALTA COMO HACER PAl REPORT.
      // Este problema esta bien algarete. So si le doy str_replace(app_path() . '/views/annual_htmls/'),
      // si yo añado '/' al substring "htmls/" , me borra '/pla'. For no reason. 
      // so el plan, no se. 
      // 
      //

      //$path = str_replace(app_path() . '/views/annual_htmls/', '', $path->path_to_pdf);
      //$path = trim($path->path_to_pdf, app_path() . '/views/annual_');
      //$path = trim($path, "htmls");
      //$path = trim($path, '/'); //. "/views/annual_htmls/");
      //Log::info($path);

      //aqui tambien pasa una loquera
      $path = str_replace(app_path() . '/views/annual_htmls/', '', $path->path_to_pdf);


      $path = trim($path, ".blade.php");
      $dir =  '';

      if ($type_of_annual == "plan") {
        $dir = 'annual_htmls.pla';
      } else {
        $dir = "annual_htmls.";
      }
      return View::make($dir . $path);
    }
    Session::flash('status', 'warning');
    Session::flash('message', 'Error loading Annual Plan. Please try again later.');
    return Redirect::back();
  }



  public function downloadPDF($download, $path_id)
  {
    $pdf = new PDF(app('config'), app("Filesystem"), app('view'), '/storage/plan_pdf');

    $queryToPath = DB::table('paths_for_annual_plans')
      ->where('id', $path_id)
      ->first();

    //Log::info("ERES TU? creo que no");

    $path = storage_path($queryToPath->path_to_pdf);

    if ($download != "download") {
      return Response::make(file_get_contents($queryToPath->path_to_pdf), 200, [
        'Content-type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="' . $queryToPath->path_to_pdf . '"'

      ]);
    } else {


      return Response::download(
        file_get_contents($queryToPath->path_to_pdf),
        200,
        [
          'Content-type' => 'application/pdf',
          'Content-Disposition' => 'inline; filename="' . $queryToPath->path_to_pdf . '"'

        ]
      );
    }
    /*
[
      'Content-type' => 'application/pdf',
      'Content-Disposition' => 'inline; filename="' . $queryToPath->path_to_pdf . '"'
    ]
    */
    $annualPlan = AnnualPlan::findOrFail($queryToPath->annual_plan_id);

    // Log::info("ERES TU?");

    //return View::make('local.managers.shared.print_annual_report', compact('annualPlan'));
    $pdf = $pdf->loadView('local.managers.shared.print_annual_report', compact('annualPlan'))
      ->setOrientation("landscape")
      ->setPaper('legal', 'landscape');
    if ($download == "download")
      return $pdf->download(basename($queryToPath->path_to_pdf));

    else
      return $pdf->stream(basename($queryToPath->path_to_pdf));
  }



  public function checkIfPlanReady()
  {
    $annual_plan = AnnualPlan::findOrFail(Input::get("annual_id"));
    //     Log::info('annual_plan' . $annual_plan->courses);

    /*
      error = [
        [
        outcome, objective, course
      ]
        ]
    */
    $error_array = [];

    //     Log::info("Esto devuelve?");

    //     Log::info($annual_plan->courses);

    foreach ($annual_plan->courses as $index => $course) {

      //       Log::info('paired Criteria');
      //       Log::info($course->paired_criteria);
      if (count($course->paired_criteria) <= 0) {
        $outcome = $course->paired_objective->paired_outcome;
        $objective = $course->paired_objective;
        $array_to_be_appended = [
          "outcome_name" => $outcome->name,
          "objective_text" => $objective->text,
          "course_code" => $course->code . '-' . $course->number,
          'typ_semester_course_id' => $course->typ_semester_course_id,
          'typ_semester_objective_id' => $objective->typ_semester_objective_id,
          'typ_semester_outcome_id' => $outcome->typ_semester_outcome_id
        ];

        $error_array[] = $array_to_be_appended;
      }
    }

    return $error_array;
  }

  public function checkIfReady()
  {
    $annual_plan = AnnualPlan::find(Input::get('annual_id'));

    /*Error message schema
    
      courses_where_missing_data = [
        course_1=>[
          info, info
          objective => {
            typ_semester_objective_id,
            objective_text
          }
          outcome => {
            typ_semester_outcome_id,
            outcome_name
          }
        ]
      ]
    

    */

    $courses_where_missing_data = [
      'courses' => [],
      'outcomes' => []
    ];
    //     Log::info($annual_plan->courses_with_transformative_actions);
    foreach ($annual_plan->courses_with_transformative_actions as $course) {

      foreach ($course->proposed_transformative_actions as $ta) {
        if (!isset($ta->status)) {
          $objective = $course->paired_objective;
          $objective_info = [
            'typ_semester_objective_id' => $objective->typ_semester_objective_id,
            'text' => $objective->text
          ];
          $outcome = $objective->paired_outcome;
          $outcome_info = [
            'typ_semester_outcome_id' => $outcome->typ_semester_outcome_id,
            'name' => $outcome->name
          ];
          $array_to_be_appended = [
            'course_name' => $course->code . '-' . $course->number,
            'objective' => $objective_info,
            'outcome' => $outcome_info,
            'transformative_action_title' => $ta->at_text,
            'transformative_action_description' => $ta->description,
            'typ_semester_course_id' => $course->typ_semester_course_id
          ];
          $courses_where_missing_data['courses'][] = $array_to_be_appended;
        }
      }
    }
    foreach ($annual_plan->outcomes as $outcome) {
      foreach ($outcome->program_transformative_actions as $ta) {
        if (!isset($ta->status)) {
          $array_to_be_appended = [
            'typ_semester_outcome_id' => $outcome->typ_semester_outcome_id,
            'outcome_name' => $outcome->name,
            'transformative_action_title' => $ta->at_text,
            'transformative_action_description' => $ta->description
          ];
          $courses_where_missing_data['outcomes'][] = $array_to_be_appended;
        }
      }
    }
    return $courses_where_missing_data;
  }


  public function printAnnualPlan($annual_id, $submit = null)
  {
    $alphabet = range("A", "Z");
    $annualPlan = AnnualPlan::findOrFail($annual_id);
    Log::info(json_encode($annualPlan));
    $temp = $annualPlan->getCoursesAttribute();
    Log::info("cursos plan");
    Log::info(json_encode($temp));
    Log::info("termina cursos plan");

    $small_alphabet = range('a', 'z');
    return View::make('local.managers.shared.print_annual_plan', compact('annualPlan', 'alphabet', 'small_alphabet', 'submit'));
  }

  public function submitAnnualPlan($annual_id)
  {
    $alphabet = range("A", "Z");
    $small_alphabet = range('a', 'z');
    $annualPlan = AnnualPlan::findOrFail($annual_id);
    //     Log::info(json_encode($annualPlan));
    // Log::info($annualPlan->annual_cycle_id);
    $user_id = Auth::user()->id;
    //$pdf = new PDF(app('config'), app("Filesystem"), app('view'), '/storage/plan_pdf');
    //$pdf = $pdf->loadView('local.managers.shared.print_annual_plan', compact('annualPlan', 'alphabet', 'small_alphabet'))
    //  ->setOrientation("landscape")

    //  ->setPaper('legal', 'landscape');
    $path = app_path() . '/views/annual_htmls/plan-on-' . date('d-m-Y') . 'ac' . $annualPlan->annual_cycle_id . '-for-' . $annualPlan->program->id . '-by-' . $user_id . '.blade.php';
    //$pdf->save($path);
    $name = "plan-on-" . date('d-m-Y') . 'ac' . $annualPlan->annual_cycle_id . '-for-' . $annualPlan->program->id . '.blade.php';
    //$pdf->download($name);

    //is a path already there
    $submit = 1;
    $it_exists = DB::table("paths_for_annual_plans")
      ->where('path_to_pdf', $path)
      ->first();
    // Log::info(
    if (isset($it_exists)) {
      return '200';
    }

    DB::table("paths_for_annual_plans")
      ->where('annual_plan_id', $annual_id)
      ->where('report', 0)
      ->where('user_id', $user_id)

      ->update(array(
        'last' => 0
      ));

    DB::table('annual_plans')
      ->where('id', $annual_id)
      ->update(array(
        'is_submitted' => 1,
        'submitted_on' => date('Y-m-d H:i:s')

      ));

    DB::table('paths_for_annual_plans')->insert(array(
      "path_to_pdf" => $path,
      'annual_plan_id' => $annual_id,
      'last' => 1,
      'report' => 0,
      'user_id' => $user_id,
      'date_posted' => date('Y-m-d')
    ));


    return '200';
  }
}