<?php

class ObjectivesController extends \BaseController
{

  /**
   * Display a listing of the resource.
   *
   * @return Response
   */
  public function fetch()
  {
    try {
      $outcome_id = Input::get('outcome_id');
      $program_id = Input::get('program_id');
      $format = Input::get('format');


      $objectives = Objective::select('id', 'outcome_id', 'program_id', 'text');

      if ($outcome_id) {
        $objectives->where('outcome_id', $outcome_id);
      }

      if ($program_id) {
        $objectives->where('program_id', $program_id);
      }

      if ($format == 'select') {
        $string = '';
        foreach ($objectives->get() as $objective) {
          $string .= '<option value="' . $objective->id . '">' . $objective->text . '</option>';
        }

        echo $string;
        return;
      } else {
        return $objectives->get();
      }
    } catch (Exception $e) {
      echo $e->getMessage();
      return;
    }
  }

  /**
   * Edit the learning objectives per learning outcome for a program
   */
  public function index($program)
  {
    $role = Auth::user()->role;

    // Redirect users if they try to access forbidden page
    if ($role == 2 && $program->school_id != Auth::user()->school_id) {
      return Redirect::to('/');
    } else if ($role == 3 && !in_array($program->id, Auth::user()->programs->lists('id'))) {
      return Redirect::to('/');
    } else if ($role == 4) {
      return Redirect::to('/');
    }

    $title = 'Learning Objectives (' . $program->name . ')';
    $objectives = $program->objectives;

    // Eager load outcomes related to objectives
    // $program->load('outcomes');
    //
    $outcomes = Outcome::select('id', 'name')->get();

    return View::make('local.managers.shared.objectives.index', compact('title', 'objectives', 'role', 'program', 'outcomes'));
  }

  public function create()
  {
    try {
      $outcome_id = Input::get('outcome_id');
      $program_id = Input::get('program_id');
      $learning_objective = trim(Input::get('learning_objective'));


      $validator = Validator::make(
        array(
          'outcome_id' => $outcome_id,
          'program_id' => $program_id,
          'learning_objective' => $learning_objective
        ),
        array(
          'outcome_id' => 'required|integer',
          'program_id' => 'required|integer',
          'learning_objective' => 'required|min:1',
        )
      );

      if ($validator->fails()) {
        /** Prepare error message */
        $message = '<p>Error(s) creating a new Learning Objective: </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);
        return Redirect::back()->withInput();
      }

      DB::table('objectives')->insert(array(
        'outcome_id' => $outcome_id,
        'program_id' => $program_id,
        'text' => $learning_objective
      ));

      /** Send success message */
      Session::flash('status', 'success');
      Session::flash('message', 'New Learning Objective successfully created.');
      return Redirect::back();
    } catch (Exception $e) {
      /** Send error message and old data */
      Session::flash('status', 'danger');
      Session::flash('message', 'An error ocurred trying to create a new Learning Objective. Please try again later.' . $e->getMessage());
      return Redirect::back()->withInput();
    }
  }

  /**
   * Update objective
   */
  public function update()
  {
    try {
      $outcome_id = Input::get('edit_outcome_id');
      $objective_id = Input::get('edit_objective_id');
      $active = Input::get('edit_active');
      $learning_objective = trim(Input::get('edit_learning_objective'));

      $validator = Validator::make(
        array(
          'outcome_id' => $outcome_id,
          'objective_id' => $objective_id,
          'active' => $active,
          'learning_objective' => $learning_objective
        ),
        array(
          'outcome_id' => 'required|integer',
          'objective_id' => 'required|integer',
          'active' => 'required|integer|boolean',
          'learning_objective' => 'required|min:1',
        )
      );

      if ($validator->fails()) {
        /** Prepare error message */
        $message = '<p>Error(s) updating the Learning Objective: </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);
        return Redirect::back()->withInput();
      }

      DB::table('objectives')
        ->where('id', $objective_id)
        ->update(array(
          'outcome_id' => $outcome_id,
          'text' => $learning_objective,
          'active' => $active,
        ));

      /** Send success message */
      Session::flash('status', 'success');
      Session::flash('message', 'Learning Objective successfully updated.');
      return Redirect::back();
    } catch (Exception $e) {
      /** Send error message and old data */
      Session::flash('status', 'danger');
      Session::flash('message', 'An error ocurred trying to create a new Learning Objective. Please try again later.' . $e->getMessage());
      return Redirect::back()->withInput();
    }
  }

  /**
   * Check what this was for
   * @return [type] [description]
   */
  public function fetchObjective()
  {
    $validator = Validator::make(
      array(
        'objective_id' => Input::get('objective_id')
      ),
      array(
        'objective_id' => 'required|integer',
      )
    );

    if ($validator->fails()) {
      return '';
    }
    $res = DB::table('objectives')->where('id', Input::get('objective_id'))->first();

    return json_encode($res);
  }

  public function fetchObjectiveForCriteria()
  {
    $id = Input::get('id');

    //$objective = Objective::find($id);
    $objective = DB::table('objectives')
      ->where('id', $id)
      ->first();

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

    switch ($role) {
      case 1:
        $program_ids = DB::table('programs')->lists('id');
        # code...
        break;
      case 2:
        $program_ids = DB::table('programs')
          ->where('school_id', Auth::user()->school_id)
          ->lists('id');
        break;
      case 3:
      case 4:
        $program_ids = DB::table('program_user')
          ->where('user_id', Auth::user()->id)
          ->lists('program_id');


        break;
    }

    $criteria_scales = DB::table('criteria')
      ->join('criterion_objective_outcome as cobo', 'criterion_id', '=', 'criteria.id')
      ->join('program_criterion', 'cobo.criterion_id', '=', 'program_criterion.criterion_id')
      ->whereIn('program_id', $program_ids)
      ->where('objective_id', $objective->id)
      ->select('num_scales')
      ->orderBy('num_scales', 'DESC')
      ->distinct()
      ->lists('num_scales');
    $objective->criteria = [];
    foreach ($criteria_scales as $i => $num_scales) {

      $objective->criteria[$num_scales] = DB::table('criteria')
        ->join('criterion_objective_outcome as cobo', 'cobo.criterion_id', '=', 'criteria.id')
        ->join('program_criterion', 'program_criterion.criterion_id', '=', 'criteria.id')
        ->whereIn('program_id', $program_ids)
        ->where('objective_id', $objective->id)
        ->where('num_scales', $num_scales)
        ->select('criteria.*', 'cobo.criterion_id')
        ->distinct()
        ->get();

      foreach ($objective->criteria[$num_scales] as $criteria) {
        $criteria->programs = DB::table('programs')
          ->join('program_criterion', 'programs.id', '=', 'program_criterion.program_id')
          ->where('criterion_id', $criteria->criterion_id)
          ->get();

        $criteria->outcomes = DB::table('outcomes')
          ->join('criterion_objective_outcome', 'outcomes.id', '=', 'criterion_objective_outcome.outcome_id')
          ->where('objective_id', $objective->id)
          ->where('criterion_id', $criteria->criterion_id)
          ->select('outcomes.*')
          ->get();
        $criteria->scales = DB::table('criterion_scale')
          ->join('scales', 'criterion_scale.scale_id', '=', 'scales.id')
          ->where('criterion_id', $criteria->criterion_id)
          ->orderBy('position', 'asc')
          ->get();
      }
    }
    //$objective->program;
    //$objective->criteria;

    return array(
      'objective' => $objective
    );
  }
}
