<?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->program;
      $objective->criteria;

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