<?php

use Illuminate\Support\Facades\Auth;

class Objective2Controller extends \BaseController
{

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */

	public function index()
	{

		$title = "Learning Outcomes and Criteria";
		$outcomes = Outcome::orderBy('name', 'ASC')->get();
		$schools = School::orderBy('name', 'ASC')->get();
		$objectives = Objective::withTrashed()->orderBy('text', 'ASC')->get();

		return View::make('global.view-learning-outcomes-criteria', compact('title', 'outcomes', 'schools', 'objectives'));
	}



	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function isObjectiveUnique($input, $existing_Objective = NULL)
	{

		Log::info('isObjectiveUnique');

		if (Input::get('program_id') != 0)
			$program_id = $input['program_id'];
		else
			$program_id = NULL;

		$saved_Objective = Objective::withTrashed()
			->where('text', '=', $input['text'])
			->where('outcome_id', '=', $input['outcome_id'])
			->where('program_id', '=', $program_id)

			->first();



		if ($saved_Objective)
			return false;
		else
			return true;
	}


	private function makeValidator($clean_input)
	{
		/** Validation rules */
		return Validator::make(
			array(
				'text' => $clean_input['text'],

				'outcome_id' => $clean_input['outcome_id'],
				'program_id' => $clean_input['program_id']

			),
			array(
				'text' => 'required|string',

				'outcome_id' => 'required|array',
				'program_id' => 'required|array'

			)

		);
	}


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

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


		$clean_input['outcome_id'] = Input::get('outcome');
		$counter = Input::get('counter') + 0;

		for ($i = 0; $i < $counter; $i++) {
			$clean_input['outcome_id'][$i] = trim(preg_replace('/\t+/', '', $clean_input['outcome_id'][$i]));
		}

		$clean_input['program_id'] = Input::get('program_id');
		Log::info(Input::get('program_id'));

		return $clean_input;
	}

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

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


		$clean_input['outcome_id'] = Input::get('assoc_outcome');
		Log::info(Input::all());


		$clean_input['program_id'] = Input::get('program_id');


		return $clean_input;
	}
	public function fetchObjective()
	{
		return Objective::find(Input::get('id'));
	}

	public function fetchObjectiveWithTrashed()
	{
		$json = array();

		$json['program'] = DB::select("select program_id from objective_program where objective_id = ?", array(Input::get('id')));
		$json['outcome'] = DB::select("select outcome_id from objective_outcome outc where outc.objective_id = ?", array(Input::get('id')));
		$json['objective'] = DB::select("select text, id from objectives where id =?", array(Input::get('id')));
		$json['assessment'] = DB::select("select * from assessments where activity_id  in (select activity_id from activity_criterion where criterion_id in (select criterion_id from criterion_objective_outcome where objective_id = ?))", array(Input::get('id')));
		$json['assoc_criteria'] = DB::select("select name from criteria where id in(select criterion_id from criterion_objective_outcome where objective_id =?)", array(Input::get('id')));
		return json_encode($json);
	}
	public function fetchAllobjectives()
	{
		$program_id = Input::get('program_fetch');
		$outcome_id = Input::get('outcome_fetch');
		$json = array();
		$json['objective'] = DB::select("SELECT * FROM `objectives` where id in (select objective_id from objective_outcome where outcome_id ={$outcome_id}) and id in (select objective_id from objective_program where program_id = {$program_id})");
		return json_encode($json);
	}
	public function delete()
	{
		DB::delete("delete from objectives where id = ?", array(Input::get('deleteObj')));
		$role = Auth::user()['role'];
		switch ($role) {
			case 1:
				return Redirect::to('objectives')->withInput();

			case 2:
				return Redirect::to('school-objectives')->withInput();

			case 3:
				return Redirect::to('program-objectives')->withInput();
		}
	}
	/**
	 * Create a new Objective.
	 *
	 * @return Redirect Redirect back to form page
	 */
	public function create()
	{

		$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 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);
			$role = Auth::user()['role'];
			switch ($role) {
				case 1:
					return Redirect::to('objective')->withInput();

				case 2:
					return Redirect::to('school-objective')->withInput();

				case 3:
					return Redirect::to('program-objective')->withInput();
			}
		} else {
			// Check Objective uniqueness
			if (!$this->isObjectiveUnique($clean_input)) {
				/** Send error message and old data */
				Session::flash('status', 'danger');
				Session::flash('message', "This objective is a duplicate of an already saved Objective because it's and associated program are the same.");
				$role = Auth::user()['role'];
				switch ($role) {
					case 1:
						return Redirect::to('objective')->withInput();

					case 2:
						return Redirect::to('school-objective')->withInput();

					case 3:
						return Redirect::to('program-objective')->withInput();
				}
			}

			/** Instantiate new Objective */
			$objective = new Objective;
			$objective->text = $clean_input['text'];







			/** If Objective is saved, send success message */
			if ($objective->save()) {
				$objectiveId = $objective->id;
				foreach ($clean_input['program_id'] as $program_id) {
					DB::insert("insert into objective_program (objective_id, program_id) values({$objectiveId},{$program_id})");
				}
				foreach ($clean_input['outcome_id'] as $outcome_id) {
					DB::insert("insert into `objective_outcome` (objective_id, outcome_id) values ({$objectiveId}, {$outcome_id})");

					/*if (!($objectiveOutcome->save())) {
						Session::flash('status', 'danger');
						Session::flash('message', '<p>Error creating objective. Please try again later.</p>');
						return Redirect::to('objective')->withInput();
					}*/
				}

				Session::flash('status', 'success');
				Session::flash('message', 'Objective created: "' . $objective->text . '".');
				$role = Auth::user()['role'];
				switch ($role) {
					case 1:
						return Redirect::to('objective')->withInput(Input::only('outcome_id'));

					case 2:
						return Redirect::to('school-objective')->withInput(Input::only('outcome_id'));

					case 3:
						return Redirect::to('program-objective')->withInput(Input::only('outcome_id'));
				}
			}

			/** If saving fails, send error message and old data */
			else {
				Session::flash('status', 'danger');
				Session::flash('message', '<p>Error creating objective. Please try again later.</p>');
				$role = Auth::user()['role'];
				switch ($role) {
					case 1:
						return Redirect::to('objective')->withInput();

					case 2:
						return Redirect::to('school-objective')->withInput();

					case 3:
						return Redirect::to('program-objective')->withInput();
				}
			}
		}
	}
	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit()
	{
		$title = "Objective";
		$outcomes = Outcome::orderBy('name', 'ASC')->lists('name', 'id');

		$objectives = Objective::withTrashed()->orderBy('text', 'ASC')->get();
		$programs = Program::orderBy('name', 'ASC')->get();

		return View::make('local.managers.admins.objectives', compact('title', 'outcomes', 'objectives', 'programs'));
	}

	public function editProgram()
	{
		$userProgram = Auth::user()['id'];
		Log::info(Auth::user());

		$userProgram = DB::select("select program_user.program_id from program_user where user_id = {$userProgram}");

		$title = "Objective";
		$outcomes = Outcome::orderBy('name', 'ASC')->lists('name', 'id');

		$objectives = Objective::withTrashed()->orderBy('text', 'ASC')->get();

		$programs = Program::where("id", '=', $userProgram[0]->program_id)->get();




		return View::make('local.managers.pCoords.objectives', compact('title', 'outcomes', 'objectives', 'programs'));
	}

	public function editSchool()
	{
		$userSchool = Auth::user()['school_id'];
		Log::info($userSchool);
		$title = "Objective";
		$outcomes = Outcome::orderBy('name', 'ASC')->lists('name', 'id');

		$objectives = Objective::withTrashed()->orderBy('text', 'ASC')->get();
		$programs = Program::where("school_id", "=", $userSchool)->orderBy('name', 'ASC')->get();



		return View::make('local.managers.sCoords.objectives', compact('title', 'outcomes', 'objectives', 'programs'));
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */

	public function update()

	{

		$Objective = Objective::withTrashed()->find(Input::get('id'));

		$clean_input = $this->cleanAssocInput();

		Log::info(print_r($clean_input, true));

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

		/** If validation fails */
		if ($validator->fails()) {
			/** Prepare error message */
			$message = 'Error(s) updating the Objective: <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'];
			switch ($role) {
				case 1:
					return Redirect::to('objective')->withInput();

				case 2:
					return Redirect::to('school-objective')->withInput();

				case 3:
					return Redirect::to('program-objective')->withInput();
			}
		} else {



			/** Set info */
			$Objective->text = $clean_input['text'];




			// Set status


			/** If Objective is updated, send success message */
			if ($Objective->save()) {

				$objectiveId = $Objective->id;
				DB::delete("delete from `objective_outcome` where objective_id ={$objectiveId}");
				DB::delete("delete from objective_program where objective_id = {$objectiveId}");

				foreach ($clean_input['program_id'] as $program_id) {
					DB::insert("insert into `objective_program`(objective_id, program_id) values ({$objectiveId},{$program_id})");
				}
				foreach ($clean_input['outcome_id'] as $outcome_id) {
					DB::insert("insert into `objective_outcome` (objective_id, outcome_id) values ({$objectiveId}, {$outcome_id})");
				}

				Session::flash('status', 'success');
				Session::flash('message', 'Updated Objective: "' . $Objective->text . '"');
				$role = Auth::user()['role'];
				switch ($role) {
					case 1:
						return Redirect::to('objective')->withInput();

					case 2:
						return Redirect::to('school-objective')->withInput();

					case 3:
						return Redirect::to('program-objective')->withInput();
				}
			}

			/** If saving fails, send error message and old data */
			else {
				Session::flash('status', 'danger');
				Session::flash('message', 'Error updating the Objective. Please try again later.');
				$role = Auth::user()['role'];
				switch ($role) {
					case 1:
						return Redirect::to('objective')->withInput();

					case 2:
						return Redirect::to('school-objective')->withInput();

					case 3:
						return Redirect::to('program-objective')->withInput();
				}
			}
		}
	}



	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}
}