<?php

class UsersController extends \BaseController
{

	/**
	 * Display a listing of the users.
	 *
	 * @return Response
	 */
	public function index()
	{
		$title = "Users";

		$users = User::with('programs', 'school')
			->orderBy('surnames')
			->orderBy('first_name')
			->get();
		Log::info('LmaOOOOO get cocked');


		$schools = School::orderBy('name', 'asc')->get();
		$access_level  = count(User::select('role')->where('has_access', 1)->groupBy('role')->get());
		try {
			Log::info("Schools");
			foreach ($schools as $school) {
				Log::info(print_r($school, true));
			}
			foreach ($users as $user) {
				Log::info("ID");
				Log::info($user->id);
				Log::info("Name");
				Log::info($user->surname . $user->first_name);
				Log::info("if funciona??");
				Log::info($user->school_id);
				Log::info("elseif??");
				Log::info(count($user->programs));
				if ($user->school_id) {
					Log::info("Schoool");
					Log::info($user->school->name);
					Log::info($user->school_id);
				} elseif (count($user->programs) > 0) {
					Log::info("Entre aqui");
					Log::info($user->programs[0]->school_id);
					Log::info($user->programs[0]->school->name);
				} else Log::info("Not so cocked");

				Log::info("bueno vamos a ver que hay???");
				Log::info(count($user->programs));
				if (count($user->programs)) {
					foreach ($user->programs as $program) {
						Log::info($program->id);
						Log::info($program->name);
					}
				} else Log::info("Tal vez cocked");
				Log::info("email");
				Log::info($user->email);
				Log::info("Role" . $user->role);
				Log::info($user->office_phone);
				Log::info($user->cell_phone);
			}
		} catch (Exception $e) {
			Log::info("get Cocked" . $e);
		}
		Log::info("el error era en la base de datos XDDDDDDD");


		return View::make('local.managers.admins.users', compact('title', 'users', 'schools', 'access_level'));
	}

	/**
	 * Show the form for editing the user.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit()
	{
		$user = Auth::user();
		Log::info($user);
		$title = "Profile";
		$schools = School::orderBy('name', 'asc')->get();
		$programs = $user->programs;
		return View::make('global.profile', compact('user', 'title', 'schools', 'programs'));
	}

	/**
	 * Create the user in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function store()
	{
		$user = Auth::user();
		if (Input::get('submit_new_user') && Auth::user()->role == 1) {

			$first_name = strtoupper(Input::get('new_first_name'));
			$surnames = strtoupper(Input::get('new_surnames'));
			$email = strtolower(Input::get('new_email'));
			$school_id = Input::get('new_school');

			// Validation rules
			$validator = Validator::make(
				array(
					'first_name' => $first_name,
					'surnames' => $surnames,
					'email' => $email,
					'school_id' => $school_id,
				),
				array(
					'first_name' => 'required',
					'surnames' => 'required',
					'email' => 'required|email',
					'school_id' => 'integer',
				)
			);

			/** If validation fails */
			if ($validator->fails()) {
				/** Prepare error message */
				$message = 'Error(s) creating a user:<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::beginTransaction();
			try {
				switch (Input::get('new_role')) {
					case '1':

						User::create(array(
							'first_name' => $first_name,
							'surnames' => $surnames,
							'email' => $email,
							'role' => 1,
							'school_id' => NULL,
							'has_access' => 1
						));
						break;

					case '2':
						User::create(array(
							'first_name' => $first_name,
							'surnames' => $surnames,
							'email' => $email,
							'role' => 2,
							'school_id' => (int)Input::get('new_school'), // como que aqui
							'has_access' => 1
						));

						break;

					case '3':
						$user = User::create(array(
							'first_name' => $first_name,
							'surnames' => $surnames,
							'email' => $email,
							'role' => 3,
							'school_id' => NULL,
							'has_access' => 1
						));

						// Attach new programs
						foreach (Input::get('programs') as $key => $program_id) {
							$user->programs()->attach($program_id);
						}

						$user->save();
						break;

					case '4':

						$user = User::create(array(
							'first_name' => $first_name,
							'surnames' => $surnames,
							'email' => $email,
							'role' => 4,
							'school_id' => NULL,
							'has_access' => 1
						));

						// Attach new programs
						foreach (Input::get('new_programs') as $key => $program_id) {
							$user->programs()->attach($program_id);
						}
						$user->save();
						break;
				}

				DB::commit();

				Session::flash('status', 'success');
				Session::flash('message', 'User created (' . date('m/d/y h:i:s A') . ')');
				return Redirect::back();
			} catch (Exception $e) {
				DB::rollBack();

				Session::flash('status', 'danger');
				Session::flash('message', 'Error creating. Try again later or contact the system administrator.');

				return Redirect::back();
			}
		} else
			App::abort('404');
	}

	/**
	 * Update the user in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update()
	{
		$user = Auth::user();
		if (Input::get('submit_contact_info')) {
			// Validation rules
			$validator = Validator::make(
				array(
					'office_phone' => Input::get('office_phone'),
					'office_extension' => Input::get('office_extension'),
					'cell_phone' => Input::get('cell_phone'),
				),
				array(
					'office_phone' => 'string|max:20|required_with:office_extension',
					'office_extension' => 'digits_between:1,5|required_with:office_phone|unique:users,office_extension,' . $user->id,
					'cell_phone' => 'string|max:20'
				)
			);

			/** If validation fails */
			if ($validator->fails()) {
				/** Prepare error message */
				$message = 'Error(s) updating your Contact nformation<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();
			} else {
				/** Set new contact info */
				if (Input::get('office_phone')) {
					$user->office_phone = Input::get('office_phone');
					$user->office_extension = Input::get('office_extension');
				} else {
					$user->office_phone = NULL;
					$user->office_extension = NULL;
				}

				if (Input::get('cell_phone')) {
					$user->cell_phone = Input::get('cell_phone');
				} else {
					$user->cell_phone = NULL;
				}

				/** If alt email is updated, send success message */
				if ($user->save()) {
					Session::flash('status', 'success');
					Session::flash('message', 'Contact Information updated.');
					return Redirect::back();
				}

				/** If saving fails, send error message and old data */
				else {
					Session::flash('status', 'warning');
					Session::flash('message', 'Error updating your Contact Information. Please try again later.');
					return Redirect::back()->withInput();
				}
			}
		} else if (Input::get('submit_roles') && Auth::user()->role == 1) {
			try {
				$exception = DB::transaction(function () {
					$user = User::find(Input::get('id'));

					switch (Input::get('role')) {
						case '1':
							$user->role = 1;
							$user->school_id = NULL;

							// Delete all programs associated to the user
							$user->programs()->detach();

							$user->has_access = 1;

							break;

						case '2':
							$user->role = 2;
							$user->school_id = Input::get('school');

							// Delete all programs associated to the user
							$user->programs()->detach();


							break;

						case '3':
							$user->role = 3;
							$user->school_id = NULL;

							// Delete all programs associated to the user
							$user->programs()->detach();

							// Attach new programs
							foreach (Input::get('programs') as $key => $program_id) {
								$user->programs()->attach($program_id);
							}
							// $user->program_id = Input::get('program');

							break;

						case '4':
							$user->role = 4;
							$user->school_id = NULL;

							// Delete all programs associated to the user
							$user->programs()->detach();

							// Attach new programs
							foreach (Input::get('programs') as $key => $program_id) {
								$user->programs()->attach($program_id);
							}
							// $user->program_id = Input::get('program');

							break;
					}

					$user->has_access = Input::get('has_access');
					$user->save();
				});

				if (is_null($exception)) {
					Session::flash('status', 'success');
					Session::flash('message', 'User <b>' . User::find(Input::get('id'))->email . '</b> updated (' . date('m/d/y h:i:s A') . '). To ensure proper access, click \'Update\' in the \'Access Level\' section at the bottom of the page.');
					return Redirect::back();
				}
			} catch (Exception $e) {
				Session::flash('status', 'danger');
				Session::flash('message', 'Error updating users. Try again later.');

				return Redirect::back();
			}
		} else
			App::abort('403');
	}

	public function updateAccess()
	{
		try {
			$exception = DB::transaction(function () {
				switch (Input::get('access_level')) {
					case '1':
						DB::table('users')
							->whereIn('role', array(1))
							->update(array('has_access' => 1));

						DB::table('users')
							->whereIn('role', array(2, 3, 4))
							->update(array('has_access' => 0));
						break;

					case '2':
						DB::table('users')
							->whereIn('role', array(1, 2))
							->update(array('has_access' => 1));

						DB::table('users')
							->whereIn('role', array(3, 4))
							->update(array('has_access' => 0));
						break;

					case '3':
						DB::table('users')
							->whereIn('role', array(1, 2, 3))
							->update(array('has_access' => 1));

						DB::table('users')
							->whereIn('role', array(4))
							->update(array('has_access' => 0));
						break;

					case '4':
						DB::table('users')
							->whereIn('role', array(1, 2, 3, 4))
							->update(array('has_access' => 1));
						break;
				}
			});

			if (is_null($exception)) {
				Session::flash('status', 'success');
				Session::flash('message', 'Access level updated (' . date('m/d/y, h:i:s a') . ').');
			}
		} catch (Exception $e) {
			Session::flash('status', 'danger');
			Session::flash('message', 'Error updating access level. Try again later (' . date('m/d/y, h:i:s a') . ').');
		}

		return Redirect::back();
	}
}