<?php

class TemplatesController extends \BaseController
{

	/**
	 * List all templates, grouped by program
	 */
	public function ProfIndex()
	{
		$title = 'Rubric List';


		$role = Auth::user()->role;
		$program_id = DB::table("program_user")
			->where('user_id', Auth::user()->id)
			->lists('program_id')[0];
		$school_id = DB::table('programs')
			->where('id', $program_id)
			->lists('school_id')[0];


		$templates = Template::orderBy('name')
			->whereNull("school_id")
			->orWhere(function ($query) use (&$school_id) {
				$query->where('school_id', $school_id)
					->whereNull('program_id');
			})
			->orWhere(function ($query) use (&$program_id, &$school_id) {
				$query->where('school_id', $school_id)
					->where('program_id', $program_id);
			})


			->get();



		return View::make('local.managers.shared.rubric_list', compact('title', 'global_templates', 'schools', 'templates', 'role'));
	}
	public function index()
	{
		$title = 'Rubric List';

		$global_templates = Template::whereNull('school_id')->whereNull('program_id')->get();

		$schools = School::with('programs.templates')
			->orderBy('name')
			->get();
		$role = Auth::user()->role;

		switch ($role) {
			case 1:
				$templates = Template::orderBy('name')->get();
				break;

			case 2:

				$templates = Template::orderBy('name')
					->whereNull("school_id")
					->orWhere('school_id', Auth::user()->school_id)
					->get();
				break;
			case 3:
			case 4:
				$program_ids = DB::table("program_user")
					->where('user_id', Auth::user()->id)
					->lists('program_id');
				$school_ids = DB::table('programs')
					->whereIn('id', $program_ids)
					->lists('school_id');


				$templates = Template::orderBy('name')
					->whereNull("school_id")
					->orWhere(function ($query) use (&$school_ids) {
						$query->whereIn('school_id', $school_ids)
							->whereNull('program_id');
					})
					->orWhere(function ($query) use (&$program_ids, &$school_ids) {
						$query->where('school_id', $school_ids)
							->where('program_id', $program_ids);
					});
				Log::info($templates->toSql());

				$templates =  $templates->get();
				break;
		}
		Log::info($templates);
		//$templates = Template::orderBy('name')->get();

		return View::make('local.managers.shared.rubric_list', compact('title', 'global_templates', 'schools', 'templates', 'role'));
	}

	/*public function schoolCoordinatorIndex()
	{
		$title = 'Rubric List';

		$global_templates = Template::whereNull('school_id')->whereNull('program_id')->get();

		$schools = School::with('programs.templates')
			->orderBy('name')
			->get();

		$templates = Template::orderBy('name')->get();

		return View::make('local.managers.admins.rubric_list', compact('title', 'global_templates', 'schools', 'templates'));
	}*/

	public function show(Template $template)
	{
		$title = $template->name;

		$template->titles = DB::table('titles')
			->join('template_title', 'template_title.title_id', '=', "titles.id")
			->where('template_id', $template->id)
			->orderBy('position', 'ASC')
			->lists('text');

		$template->criteria = DB::table('criteria')
			->join('template_criterion', 'template_criterion.criterion_id', '=', 'criteria.id')
			->where('template_id', $template->id)
			->orderBy('position')
			->get();

		foreach ($template->criteria as $criterion) {
			$criterion->scales = DB::table('criterion_scale')
				->join('scales', 'scales.id', '=', 'criterion_scale.scale_id')
				->where('criterion_id', $criterion->criterion_id)
				->orderBy('position')
				->lists('description');
			$criterion->outcomes = DB::table('criterion_objective_outcome as cobo')
				->join('outcomes', 'outcomes.id', '=', 'cobo.outcome_id')
				->where('cobo.criterion_id', $criterion->criterion_id)
				->select('outcomes.*')
				->distinct()
				->get();
		}

		return View::make('local.managers.admins.view_template', compact('template', 'title'));
	}

	public function onLoadFetch()
	{
		$json_to_send = [];
		$template_id = Input::get('id');
		$json_to_send["criteria"] = DB::table("criteria")->join('template_criterion', 'template_criterion.criterion_id', '=', 'criteria.id')
			->where("template_criterion.template_id", '=', $template_id)
			->get();
		Log::info($json_to_send["criteria"]);
		foreach ($json_to_send['criteria'] as $criteria) {
			$json_to_send['scales'][$criteria->criterion_id] = DB::table("scales")
				->join('criterion_scale', 'criterion_scale.scale_id', '=', 'scales.id')
				->where("criterion_scale.criterion_id", '=', $criteria->criterion_id)->orderBy('position', 'ASC')->get();
		}
		return json_encode($json_to_send);
	}
	/**
	 * Show the form for creating a new rubric
	 *
	 * @return Response
	 */
	public function newTemplate()
	{
		$title = "Rubric Builder";

		$templates = Template::orderBy('name', 'ASC')->get();
		$outcomes = Outcome::where("deactivation_date", '=', null)->orderBy('name', 'ASC')->get();
		$criteria = Criterion::orderBy('name', 'ASC')->get();
		$schools = School::orderBy('name', 'ASC')->get();
		$role = Auth::user()->role;

		$templates = NULL;
		$programs = NULL;
		// Returns templates depending on the type of user
		if ($role == 1) {
			$templates = Template::orderBy('name', 'ASC')->get();
			$programs = Program::orderBy('name', 'ASC')->get();
		} elseif ($role == 2) {
			$templates = Template::where('school_id', '=', Auth::user()->school->id)->orWhere('school_id', '=', NULL)->orderBy('name', 'ASC')->get();
			$programs = Auth::user()->school->programs;
		} elseif ($role == 3) {
			$templates = Template::where('school_id', '=', Auth::user()->programs[0]->school->id)->orWhere('school_id', '=', NULL)->orderBy('name', 'ASC')->get();
			$programs = Auth::user()->programs()->get();
		}

		return View::make('local.managers.shared.rubrics', compact('title', 'templates', 'outcomes', 'criteria', 'schools', 'programs'));
	}

	public function newTemplate_new()
	{
		$title = "Rubric Builder";

		$templates = Template::orderBy('name', 'ASC')->get();
		$outcomes = Outcome::where("deactivation_date", '=', null)->orderBy('name', 'ASC')->get();
		$schools = School::orderBy('name', 'ASC')->get();
		$role = Auth::user()->role;

		$templates = NULL;
		$programs = NULL;
		// Returns templates depending on the type of user
		if ($role == 1) {
			$templates = Template::orderBy('name', 'ASC')->get();
			$programs = Program::orderBy('name', 'ASC')->get();
			$criteria = Criterion::orderBy('name', 'ASC')->get();
			$school_id_user=NULL;
		} else {
			if ($role == 2) {
				$programs = Auth::user()->school->programs;
				$school_id_user=Auth::user()->school_id;
			}
			if ($role == 3) {
				$programs = Auth::user()->programs()->get();
				$school_id_user=Auth::user()->programs[0]->school->id;
			}
			$program_ids = array();
			foreach ($programs as $program) {
				$program_ids[] = $program->id;
			}
			$criteria = Criterion::whereHas(
				'programs',
				function ($q) use ($program_ids) {
					$q->whereIn('program_id', $program_ids);
				}
			)->orderBy('name', 'ASC')->get();
			}
			$templates = Template::where('school_id', '=', $school_id_user)->orWhere('school_id', '=', NULL)
				->orderBy('name', 'ASC')->get();
			$criteria_ids = array();
			foreach ($criteria as $criterion) {
				$criteria_ids[] = $criterion->id;
			}
			$templates_fuera = Template::whereHas('criteria', function ($q) use ($criteria_ids) {
				$q->whereNotIn('criterion_id', $criteria_ids);
			})
				->orderBy('name', 'ASC')->get();
			$templates_fuera_ids = array();
			foreach ($templates_fuera as $tf) {
				$templates_fuera_ids[] = $tf->id;
			}
// 			Log::info(json_encode($templates_fuera_ids));
// exit();
			$templates_dentro = Template::whereNotIn('id', $templates_fuera_ids)
				->orderBy('name', 'ASC')->get();

// 			if(!isset($templates_dentro))$templates_dentro=

			// 			var_dump(json_encode($templates_dentro));
// 		}


		return View::make('local.managers.shared.rubrics_new', compact('title', 'templates_dentro', 'templates_fuera', 'outcomes', 'criteria', 'schools', 'programs', 'criteria_ids'));
	}

	/**
	 * Save a new rubric
	 *
	 * @return Response
	 */
	public function create()
	{
		DB::beginTransaction();
		$template = new Template;

		$template->name = Input::get('name');

		$template->is_visible = Input::get('is_visible');
		$template->expected_percentage = Input::get('expected_percentage');
		$template->expected_points = Input::get('expected_points');

		// If user can set the school (that is, if school_id is not undefined)
		// set the school id or set to null
		if (is_numeric(Input::get('school_id'))) {
			if (Input::get('school_id') != 0)
				$template->school_id = Input::get('school_id');
			elseif (Input::get('school_id') == 0)
				$template->school_id = NULL;
		}

		// If user can set the program (that is, if program_id is not undefined)
		// set the program id or set to null
		if (is_numeric(Input::get('program_id'))) {
			if (Input::get('program_id') != 0)
				$template->program_id = Input::get('program_id');
			elseif (Input::get('program_id') == 0)
				$template->program_id = NULL;
		}

		// If the user is any coordinator, set the school id
		// If the user is a program coordinator, also set program id
		switch (Auth::user()->role) {
			case 2:
				$template->school_id = Auth::user()->school->id;
				break;
				//TODO esto yo no lo hice
			case 3:
				$template->school_id = Auth::user()->programs[0]->school->id;
				//Comenté esto porque siempre va a estar el program_id 
				//TODO
				if ($template->program_id == NULL)
					$template->program_id = Auth::user()->programs[0]->id;
				break;
		}

		$criteria = Input::get('criteria');

		$max_score = Input::get('max_score');
		$titles = Input::get('titles');



		$template->num_scales = count($titles);
		$template->max_score = $max_score;

		if ($template->save()) {

			$templateId = $template->id;
			foreach ($criteria as $index => $criterion_id) {


				if (!(DB::insert("insert into template_criterion (`template_id`,`criterion_id`, `position`) values ({$templateId},{$criterion_id}, '{$index}')"))) {
					Session::flash('status', 'danger');
					Session::flash('message', 'Rubric could not be created.');
					DB::rollback();
					return;
				}
			}

			foreach ($titles as $index => $text) {
				$query = DB::table('titles')
					->where('text', $text)->first();
				if ($query) {
					$result = DB::insert("insert into `template_title` (`template_id`, `title_id`, `position`) values ({$templateId}, {$query->id}, {$index})");
					if (!$result) {
						Session::flash('status', 'danger');
						Session::flash('message', 'Rubric could not be created.');
						DB::rollback();
						return;
					}
				} else {
					$result1 = DB::insert("insert into `titles` (`text`) values ('{$text}')");
					if (!$result1) {
						Session::flash('status', 'danger');
						Session::flash('message', 'Rubric could not be created.');
						DB::rollback();
						return;
					}
					$query = DB::table('titles')
						->where('text', $text)->first();
					$result = DB::insert("insert into `template_title` (`template_id`, `title_id`, `position`) values ({$templateId}, {$query->id}, {$index})");
					if (!$result) {
						Session::flash('status', 'danger');
						Session::flash('message', 'Rubric could not be created.');
						DB::rollback();
						return;
					}
				}
			}


			Session::flash('status', 'success');
			Session::flash('message', 'Rubric created. You can now select it from the list.');

			DB::commit();


			return;
		} else {
			Session::flash('status', 'danger');
			Session::flash('message', 'Rubric could not be created.');
			DB::rollback();
			return;
		}
	}

	/**
	 * Return a specific template
	 *
	 * @return Template
	 */
	public function fetch()
	{
		$template_info = [];
		$template_info['template'] = Template::find(Input::get('id'));
		$template_info['criterion'] = DB::table('criteria')
			->join('template_criterion', 'template_criterion.criterion_id', '=', 'criteria.id')
			->where("template_criterion.template_id", '=', Input::get('id'))
			->get();
		Log::info(json_encode($template_info['criterion']));
		// 				Log::info(($temp_crit->program_ids));
		foreach ($template_info['criterion'] as $temp_crit) {
			$temp_crit->scales = DB::table('scales')
				->join('criterion_scale', 'criterion_scale.scale_id', '=', 'scales.id')
				->where('criterion_scale.criterion_id', '=', $temp_crit->criterion_id)
				->orderBy('position', 'ASC')
				->get();

			$temp_crit->program_ids = json_encode(DB::table('program_criterion')
				->where('criterion_id', $temp_crit->id)
				->lists('program_id'));

			Log::info("ee" . json_encode($temp_crit->program_ids));

			$temp_crit->objectives = DB::table('criterion_objective_outcome')
				->join('objectives', 'objectives.id', '=', 'criterion_objective_outcome.objective_id')
				->where('criterion_id', $temp_crit->id)
				->select('objectives.*')
				->distinct()
				->lists('text');
			$outcomeID = DB::table('criterion_objective_outcome')->where('criterion_id', '=', $temp_crit->criterion_id)
				->lists('outcome_id');
			$outcomes = DB::table('outcomes')->whereIn('id', $outcomeID)->get();
			$outcomeStr = '';
			foreach ($outcomes as $key => $outcome) {
				$outcomeStr .= $outcome->name . ', ';
			}
			$outcomeStr = rtrim($outcomeStr, ',');
			$temp_crit->outcomes = $outcomeStr;
		}
		Log::info("ee2" . json_encode($template_info));

		$template_info['titles'] = DB::table('titles')
			->join('template_title', 'template_title.title_id', '=', 'titles.id')
			->where('template_id', Input::get('id'))
			->orderBy('position')
			->get();

		// 		Log::info(json_encode($template_info));

		return json_encode($template_info);
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @return Response
	 */
	public function update()
	{
		DB::beginTransaction();
		$template = Template::find(Input::get('id'));
		Log::info(Input::all());
		$template->name = Input::get('name');

		$template->is_visible = Input::get('is_visible');
		$template->expected_percentage = Input::get('expected_percentage');
		$template->expected_points = Input::get('expected_points');


		// If user can set the school (that is, if school_id is not undefined)
		// set the school id or set to null
		if (is_numeric(Input::get('school_id'))) {
			if (Input::get('school_id') != 0)
				$template->school_id = Input::get('school_id');
			elseif (Input::get('school_id') == 0)
				$template->school_id = NULL;
		}

		// If user can set the program (that is, if program_id is not undefined)
		// set the program id or set to null
		if (is_numeric(Input::get('program_id'))) {
			if (Input::get('program_id') != 0)
				$template->program_id = Input::get('program_id');
			elseif (Input::get('program_id') == 0)
				$template->program_id = NULL;
		}

		switch (Auth::user()->role) {
			case 2:
				$template->school_id = Auth::user()->school->id;
				break;

			case 3:
				$template->school_id = Auth::user()->programs[0]->school->id;
				if ($template->program_id == NULL)
					$template->program_id = Auth::user()->programs[0]->id;
				break;
		}


		$criteria = Input::get('criteria');

		$max_score = Input::get('max_score');
		$titles = Input::get('titles');



		$template->num_scales = count($titles);
		$template->max_score = $max_score;
		//$division = $max_score / count($scales[0]);

		if ($template->save()) {
			$templateId = $template->id;
			DB::delete("delete from template_criterion where template_id ={$template->id}");
			foreach ($criteria as $index => $criterion_id) {

				if (!DB::insert("insert into template_criterion (`template_id`,`criterion_id`, `position`) values ({$templateId},{$criterion_id}, {$index})")) {

					Session::flash('status', 'danger');
					Session::flash('message', 'Rubric could not be created.');
					DB::rollback();
					return;
				}
			}
			DB::delete("delete from template_title where template_id = {$template->id}");
			foreach ($titles as $index => $text) {
				$query = DB::table('titles')
					->where('text', $text)->first();
				if ($query) {
					$result = DB::insert("insert into `template_title` (`template_id`, `title_id`, `position`) values ({$templateId}, {$query->id}, {$index})");
					if (!$result) {
						Session::flash('status', 'danger');
						Session::flash('message', 'Rubric could not be created.');
						DB::rollback();
						return;
					}
				} else {
					$result1 = DB::insert("insert into `titles` (`text`) values ('{$text}')");
					if (!$result1) {
						Session::flash('status', 'danger');
						Session::flash('message', 'Rubric could not be created.');
						DB::rollback();
						return;
					}
					$query = DB::table('titles')
						->where('text', $text)->first();
					$result = DB::insert("insert into `template_title` (`template_id`, `title_id`, `position`) values ({$templateId}, {$query->id}, {$index})");
					if (!$result) {
						Session::flash('status', 'danger');
						Session::flash('message', 'Rubric could not be created.');
						DB::rollback();
						return;
					}
				}
			}



			Session::flash('status', 'success');

			Session::flash('message', 'Rubric updated (' . date('m/d/y, h:i:s a') . ').');
			DB::commit();
		} else {
			Session::flash('status', 'danger');
			Session::flash('message', 'Rubric could not be updated (' . date('m/d/y, h:i:s a') . ').');
			DB::commit();
		}
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @return Response
	 */
	public function destroy()
	{
		$template = Template::find(Input::get('id'));

		if ($template->delete()) {
			Session::flash('status', 'success');
			Session::flash('message', 'Rubric deleted.');
		} else {
			Session::flash('status', 'danger');
			Session::flash('message', 'Rubric could not be deleted.');
		}

		return;
	}

	public function printview($id)
	{
		try {
			$template = Template::find($id);
			$template->titles = DB::table('titles')
				->join('template_title', 'template_title.title_id', '=', 'titles.id')
				->where("template_id", $template->id)
				->orderBy('position', 'ASC')
				->lists('text');
			$template_criterion = DB::table('template_criterion')
				->join('criteria', 'criteria.id', '=', 'template_criterion.criterion_id')
				->where('template_id', $template->id)
				->orderBy('position', 'ASC')
				->get();

			foreach ($template_criterion as $single_crit) {
				$single_crit->scales = DB::table('criterion_scale')
					->join('scales', 'criterion_scale.scale_id', '=', 'scales.id')
					->where('criterion_id', $single_crit->id)
					->orderBy('position')
					->lists('description');
				$single_crit->outcomes = DB::table('outcomes')
					->join('criterion_objective_outcome', 'criterion_objective_outcome.outcome_id', '=', 'outcomes.id')
					->where('criterion_id', $single_crit->id)
					->select('name')
					->distinct()
					->lists('name');
			}

			$title = $template->name;

			if ($template->school_id != NULL)
				$school = $template->school->name;
			else
				$school = 'All Schools';

			if ($template->program_id != NULL)
				$program = $template->program->name;
			else
				$program = 'All Programs';

			return View::make('local.managers.shared.print_rubric', compact('title', 'template_criterion', 'template', 'school', 'program'));
		} catch (Exception $e) {
			Session::flash('status', 'danger');
			Session::flash('message', $e->getMessage());
			return Redirect::back();
		}
	}
}