<?php

class TemplatesController extends \BaseController
{

	/**
	 * List all templates, grouped by program
	 */
	public function index()
	{
		$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 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;

		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'));
	}

	/**
	 * 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;

			case 3:
				$template->school_id = Auth::user()->programs[0]->school->id;
				$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();
		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'));
			$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;
		}

		$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($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;
				$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();
		}
	}
}