<?php 

class SemestersController extends \BaseController {

	public function filterSemesters()
	{
		$semesters_ids = array();
		$semesters_info = array();

		if(count(Input::get('semesters_ids')))
		{
			// For each selected semester, fetch its info to add to the Session arrays
			foreach (Input::get('semesters_ids') as $semester_id) {
				$semesters_ids[] = $semester_id;
				$semester = Semester::find($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);
		}

		return Redirect::back();
	}

	public function edit()
	{
		$title = "Semester Management";
		$semesters = Semester::all();

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

	public function update()
	{
		/** Validate data */
		$validator = Validator::make(
			Input::all(),
			array(
				'id'=>'required|integer',
    			'start'=>'required|date_format:m/d/y H:i:s',
    			'end'=>'required|date_format:m/d/y H:i:s',
    			'visible'=>'required|integer',
			),
			array(
				'start.date_format' => 'The start date must be in this format: mm/dd/yyyy hh:mm:ss',
				'end.date_format' => 'The end date must be in this format: mm/dd/yyyy hh:mm:ss',
			)
		);

		if(!$validator->fails())
		{

			$semester = Semester::find(Input::get('id'));
			$semester->start = date('Y-m-d H:i:s', strtotime(Input::get('start')));
			$semester->end = date('Y-m-d H:i:s', strtotime(Input::get('end')));
			// $semester->start = strtotime(Input::get('start'));
			// $semester->end = strtotime(Input::get('end'));
			$semester->is_visible = Input::get('visible');

			try 
			{
				if($semester->save())
				{
					Session::flash('status', 'success');
				 	Session::flash('message', $semester->name.' updated ('.date('m/d/y h:i:s a').').');
				}
				else
				{
					Session::flash('status', 'danger');
					Session::flash('message', 'Error updating '.$semester->name.'. Try again later. If the problem persists, contact a super-administrator ('.date('m/d/y h:i:s a').').');	
				}
			} catch (Exception $e) {
					Session::flash('status', 'danger');
					Session::flash('message', 'Error updating '.$semester->name.'. Contact a super-administrator ('.date('m/d/y h:i:s a').').');	
						
			}
		}
		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);
		}
	}


}
