<?php

class AuthController extends \BaseController
{

	/**
	 * Display a listing of the resource.
	 * GET /auth
	 *
	 * @return Response
	 */
	public function showLogin()
	{
		$title = "Online Learning Assessment System";
		return View::make('global.login', compact('title'));
	}

	public function login()
	{
		/** Validate data */
		$validator = Validator::make(
			Input::all(),
			array(
				'email' => 'required|email',
				'password' => 'required|min:4|max:16'
			)
		);

		if (!$validator->fails()) {
			//			TODO: Remove this for production environment
// 			if (App::environment('local', 'staging')) {
// 				return $this->processLogin();
// 			}
			try {
				// User input
				$username = str_replace('@upr.edu', '', Input::get('email'));
				$password = Input::get('password');

				// Radius connection info
				$radius = radius_auth_open();
				$radius_ip = '136.145.223.27';
				$radius_secret = '8reC6ujatArecHe63spech5Wa';

				radius_add_server($radius, $radius_ip, 1812, $radius_secret, 5, 3);

				// Create radius request and add params
				radius_create_request($radius, RADIUS_ACCESS_REQUEST);
				radius_put_attr($radius, RADIUS_USER_NAME, $username);
				radius_put_attr($radius, RADIUS_USER_PASSWORD, $password);

				$result = radius_send_request($radius);

				switch ($result) {
						// Credentials are correct
					case RADIUS_ACCESS_ACCEPT:

						return $this->processLogin();
						break;
					case RADIUS_ACCESS_REJECT:
						// If email is a workshop email,
						if (Input::get('email') == 'taller1@upr.edu' && Input::get('password') == 'o34eAvaluo') {
							return $this->processLogin();
						}

						// Tell user credentials are incorrect
						Session::flash('status', 'danger');
						Session::flash('message', 'Incorrect email/password combination.');
						return Redirect::action('AuthController@showLogin');
						break;
						// Throw exception in case of any other error
					default:
						throw new Exception("-", 1);
						break;
				}
			} catch (Exception $e) {
				// Tell user access is denied and return to login page.
				Session::flash('status', 'danger');
				Session::flash('message', 'An error occurred while connecting to the authentication service. Please try again later. If the problem persists, contact the help desk at x. 80400 or the administrators at oeae.uprrp.edu.');
				return Redirect::action('AuthController@showLogin');
			}
			return Redirect::route('login');
		} else {
			/** Prepare error message */
			$message = '<ul>';

			foreach ($validator->messages()->all('<li>:message</li>') as $validationError) {
				$message .= $validationError;
			}

			$message .= '</ul>';

			Session::flash('status', 'danger');
			Session::flash('message', $message);
			return Redirect::action('AuthController@showLogin');
		}
	}

	private function processLogin()
	{
		// Get user record in OLAS database, if it exists
		$user = User::where('email', Input::get('email'))->first();

		// If user exists in the database AND is authorized
		if ($user and $user->has_access) {
			// Log in user and direct to main page
			Auth::login($user);

			// Get last visible AND running term;
			$semester = Semester::where('is_visible', 1)
				->where('start', '<=', date('Y-m-d H:i:s'))
				->orderBy('start', 'DESC')
				->first();

			Session::forget('current_semester');
			Session::put('current_semester', $semester);

			// Push into semesters variable
			$semesters_id = array();
			$semesters_info = array();

			$semesters_ids[] = $semester->id;
			$semesters_info[] = $semester->name . ' (' . $semester->code . ')';

			// Put semesters information arrays into Session
			Session::forget('semesters_ids');
			Session::put('semesters_ids', $semesters_ids);

			Session::forget('semesters_info');
			Session::put('semesters_info', $semesters_info);

			// Record last login
			User::where('id', Auth::user()->id)
				->update(
					array(
						'last_login' => DB::raw('NOW()')
					)
				);

			if (!Auth::user()->office_phone) {
				return Redirect::action('UsersController@edit');
			}

			// Redirect depending on user
			return Redirect::intended('agreement');
			switch (Auth::user()->role) {
				case 1:
					return Redirect::intended('administrator');
					break;

				case 2:
					return Redirect::intended('school-coordinator');
					// 					return Redirect::intended('agreement');
					break;

				case 3:
					return Redirect::intended('program-coordinator');
					break;

				case 4:
					return Redirect::intended('professor');
					break;
			}
		} else {
			// Tell user access is denied and return to login page.
			Session::flash('status', 'danger');
			Session::flash('message', 'You are not an authorized user. You may request access by contacting oeae.uprrp.edu.');
			return Redirect::action('AuthController@showLogin');
		}
	}

	public function logout()
	{
		Auth::logout();
		Session::flush();
		return Redirect::action('AuthController@showLogin');
	}
}