Location: PHPKode > projects > ConCentric Event Planning Software > CC/system/application/controllers/concentric/eventrooms.php
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * MODULE NAME   : eventrooms.php
 *
 * DESCRIPTION   : eventrooms module controller
 *
 * MODIFICATION HISTORY
 *   V1.0   2008-11-13 2:00 AM   - Leane Verhulst     - Created
 *
 * @package			ConCentric
 * @subpackage		eventrooms component Class
 * @author			Leane Verhulst
 * @copyright		Copyright (c) 2008
 * @license			http://www.gnu.org/licenses/gpl.html
 */

class Eventrooms extends Concentric_Controller
{
	/**
	* Contructor function
	*
	* Load the instance of CI by invoking the parent constructor
	*
	* @access      public
	* @return      none
	*/
	function Eventrooms()
	{
		// Call parent constructor
		parent::Concentric_Controller();

		$this->form_name = "EventRooms";
		$this->load->model('eventrooms_model');    // Instantiate the model
		// load helper library
		$this->load->helper('concentric');
	}

	// -------------------------------------------------------------------------
	/**
	* "Index" Page
	*
	* Default class action
	*
	* @access      public
	* @return      none
	*/
	function index($sortby = '')
	{
		// The default action is the browse action
		$this->browse($sortby);
	}

	// -------------------------------------------------------------------------
	// Function: browse()
	// Description: Extracts a list of all data records and
	//              displays it.
	function browse($sortby = '')
	{
		// get sort from cookie / save new sort to cookie
		$array = get_eventrooms_sort($sortby);
		$sortname = $array['name'];
		$sortdirection = $array['direction'];
		$sortby = $array['sortby'];

		// fetch query object from the model
		$template['eventrooms_list'] = $this->eventrooms_model->fetchEventRooms(NULL, $sortby);

		// create urls for use in content view
		$template['base_url']   = 'concentric/eventrooms/browse/';
		$template['edit_url']   = 'concentric/eventrooms/edit/';
		$template['delete_url'] = 'concentric/eventrooms/delete/';
		$template['add_url']    = 'concentric/eventrooms/add/';
		$template['cancel_url'] = 'concentric/home';
		$template['sort_url']['EventName']  = 'concentric/eventrooms/browse/eventname';
		$template['sort_url']['RoomName']   = 'concentric/eventrooms/browse/roomname';
		$template['sort']['name']          = $sortname;
		$template['sort']['direction']     = $sortdirection;

		// Set breadcrumb
		$this->page->set_crumb('Event Rooms',$template['base_url']);

		// set values for use in content view
		$template['form_attributes'] = array('name' => $this->form_name, 'id' => $this->form_name);
		$template['header'] = $this->form_name;

		// build content html using grid view and template data
		$data['content'] = $this->load->view('/concentric/eventrooms/eventrooms_grid', $template, TRUE);

		// set values for use in header view
		$data['header']  = $this->form_name;

		// pass all data to container view and display to user
		$this->load->view($this->_container,$data);
	}

	// -------------------------------------------------------------------------
	// Function: add()
	// Description: Prompts user for input and adds a new entry
	//              in the database.
	function add()
	{
		$this->_modify('add');
	}

	// -------------------------------------------------------------------------
	// Function: edit()
	// Description: Prompts user for input and updates an entry
	//              in the database.
	function edit()
	{
		$this->_modify('edit');
	}

	// -------------------------------------------------------------------------
	// Function: modify()
	// Description: Prompts user for input and adds/edits an entry
	//              in the database. Default to add mode.
	function _modify($mode = 'add')
	{
		// Initialize variable
		$other_scripts_data = '';

		// load validation library to help validate data
		$this->load->library('validation');

		// load grid helper
		$this->load->helper('grid');

		// create urls and values for use in content view
		$template['form_url'] = 'concentric/eventrooms/' . $mode . '/';
		$template['cancel_url'] = 'concentric/eventrooms/browse';
		$template['form_attributes'] = array( 'method' => 'post', 'id' => $this->form_name, 'name' => $this->form_name );
		$template['header']  = $this->form_name;

		// Set breadcrumb
		$this->page->set_crumb('Event Rooms',$template['cancel_url']);
		$this->page->set_crumb($mode,$template['form_url']);


		$this->_initialize();   // Setup the fields
		$this->_validation();   // Load the validation rules and fields


		// Need to create a list of rooms for grid
		$this->load->model('rooms_model');    // Instantiate the model
		$query = $this->rooms_model->fetch('rooms', 'id, sortOrder', '', '', 'sortOrder ASC');  //get data
		foreach ($query->result_array() as $row)
		{
			$rooms[$row['sortOrder']] = $row['id'];
		}
		$this->roomGrid = $this->events_model->build_room_grid($rooms);  // Build the room grid for conflict checking


		// if validation has not run or if it failed
		if ( $this->validation->run() == FALSE )
		{
			// Save validation errors to flashmsg
			// Will be output in content view by status->display
			$this->validation->output_errors();

			// Get values for form fields and build the form fields
			$status = $this->_get_form_values($mode);

			// If the returned values got an error
			if ($status === FALSE)
			{
				// Show error message
				flashMsg('error','There was a problem editing that record.');
				// redirect to main location
				redirect('/concentric/eventrooms/', 'location');
			}

			// Save field data to array to be passed to content view
			$template['fields'] = $this->fields;

			// build content html using details view and template data
			$data['content'] = $this->load->view('/concentric/details', $template, TRUE);
			// pass other scripts data to container
			$data['other_scripts'] = $other_scripts_data;

			// pass all data to container view and display to user
			$this->load->view($this->_container, $data);
		}
		else  // User is submitting valid data
		{
			// Store the values from the form into the db
			// XXS Filtering enforced for user input
			$data['field']['id']			= $this->input->post('id', TRUE);
			$data['field']['roomID']		= $this->input->post('roomID', TRUE);
			$data['field']['eventID']		= $this->input->post('eventID', TRUE);

			if ($mode == 'add')
			{
				// add the data to the table and return id
				$idField = $this->eventrooms_model->addRow('eventRooms',$data['field']);
				$status = ($idField) ? TRUE : FALSE;
			}
			else
			{
				$idField = $data['field']['id'];
				// update the data in the table
				$obj = $this->eventrooms_model->update('eventRooms', $data['field'], 'id = ' . $idField);
				$status = ($obj) ? TRUE : FALSE;
			}

			// if there was no error in add or edit
			if ($status)
			{
				// Show success message
				flashMsg('success','Record ' . $idField . ' has been saved.');
			}
			else  // there was an error
			{
				// Show error message
				flashMsg('error','The record has not been saved.');
			}

			// redirect to main location
			redirect('/concentric/eventrooms/', 'location');
			// ?redirect to add/edit?
			// redirect('/concentric/eventrooms/' . $mode . '/', 'location');
		}
	}

	// -------------------------------------------------------------------------
	// Function: delete()
	// Description: Controller function to process user delete requests
	function delete()
	{
		$idField = $this->uri->segment(4);

		//$confirm = $this->_delete_confirm($idField);  //add later
		$confirm = TRUE;

		if ($confirm)
		{
			if ( $this->eventrooms_model->delete('eventRooms', 'id =' . $idField) )
			{
				flashMsg('success', 'The record has been deleted.');
			}
			else
			{
				flashMsg('error', 'There was a problem deleting the record');
			}
		}

		redirect('/concentric/eventrooms/', 'location');
	}

	// -------------------------------------------------------------------------
	function _delete_confirm($id)
	{
		//add later
	}

	// -------------------------------------------------------------------------
	// @access private
	function _get_form_values($mode = 'add')
	{
		if ($mode == 'add')
		{
			// Set empty values / default values
			$this->fields['id']['value'] = '';
			$this->fields['eventID']['value'] = '';
			$this->fields['eventID']['selected'] = 0;
			$this->fields['roomID']['value'] = '';
			$this->fields['roomID']['selected'] = '';
		}
		else
		{
			//get the id from either the hidden field or the url
			$idField = ($this->input->post('id', TRUE) != '') ? $this->input->post('id', TRUE) : $this->uri->segment(4);

			// fetch query object from the model with all fields
			$qry = $this->eventrooms_model->fetch('eventRooms','id, eventID, roomID','','id = ' . $idField);

			// There should only be 1 row. If not, return FALSE
			if ($qry->num_rows() != 1)
			{
				return FALSE;
			}

			// Get the single result as an array and save values
			$row = $qry->row_array();
			$this->fields['id']['value'] = $row['id'];
			$this->fields['eventID']['value'] = $row['eventID'];
			$this->fields['eventID']['selected'] = $row['eventID'];
			$this->fields['roomID']['value'] = $row['roomID'];
			$this->fields['roomID']['selected'] = $row['roomID'];
		}

		// Now build the form fields
		foreach ($this->fields as $field)
		{
			$this->fields[$field['name']]['form'] = build_form_field($field);
		}

		return TRUE;
	}


	// -------------------------------------------------------------------------
	function _validation()
	{
		// load the rules
		$form_rules['eventID']  = $this->fields['eventID']['rules'];
		$form_rules['roomID']  = $this->fields['roomID']['rules'];
		$this->validation->set_rules($form_rules);

		// load the field labels
		$form_fields['id']   = $this->fields['id']['label'];
		$form_fields['eventID']   = $this->fields['eventID']['label'];
		$form_fields['roomID']   = $this->fields['roomID']['label'];
		$this->validation->set_fields($form_fields);

		// set error delimiters
		$this->validation->set_error_delimiters('<span class="error">', '</span>');

	}


	// -------------------------------------------------------------------------
	/**
	 * Initalize Values
	 * 
	 * @access private
	 * @return void;
	 */
	function _initialize()
	{
		// Setup custom field options - list fields in the order they should
		// appear in the details view
		//   rules - validation rules (optional)
		//   label - descriptive name of the field (optional)
		//   name - database field name ** MUST BE SAME AS KEY ** (required)
		//   desc - long description to show to user on form (optional)
		//   type - set of values (required)
		//            text - basic input box
		//            hidden - keep this field hidden
		//            textarea
		//            checkbox
		//            dropdown
		//            password
		//   class - class name (optional)
		//   script - html script code to insert on the field
		//   after_form_script - html script code to insert after the form has been displayed

		$this->fields['id'] = array('label' => 'Event ID',
							'name' => 'id',
							'type' => 'hidden');
		$this->fields['eventID'] = array('rules' => 'trim|required|callback__not_zero|callback__duplicate|xss_clean',
							'label' => 'Event Name',
							'name' => 'eventID',
							'desc' => 'Enter the event name.',
							'type' => 'dropdown',
							'options' => $this->_get_event_array(),
							'selected' => '');
		$this->fields['roomID'] = array('rules' => 'trim|required|callback__not_zero|callback__check_room_conflict|xss_clean',
							'label' => 'Room Name',
							'name' => 'roomID',
							'desc' => 'Enter the room use for this event.',
							'type' => 'dropdown',
							'options' => $this->_get_room_array(),
							'selected' => '');

		return;
	}

	/**
	 * Unique_field
	 * ** Assumes that the db model has already been loaded. **
	 *
	 * @access    private
	 * @param     string  The string to check for in the db.
	 * @param     field   The table and column of the field to check in table.column format
	 * @return    bool
	 */
	function _unique_field($str, $field)
	{
		list($table, $column) = split("\.", $field, 2);

		// Set the error message to use
		$this->validation->set_message('_unique_field','The %s field must have a unique value in the database.');

		$where= isset($_POST['id']) ? array('id !='=> $_POST['id'], $column=>$str) : array($column=>$str);
		$count = $this->eventrooms_model->count_condition($table, $where);
		return ($count > 0) ? FALSE : TRUE;
	}

	/**
	 * Get room array
	 *
	 * @access    private
	 * @return    array
	 */
	 function _get_room_array()
	{
		// Load the model
		$this->load->model('rooms_model');

		// fetch query object from the model with fields id, name
		$query = $this->rooms_model->fetch('rooms','id, name','','','name ASC');

		// Loop through to build array
		$data = array();
		$data[0] = '';
		foreach ($query->result_array() as $row)
		{
			$data[$row['id']] = $row['name'];
		}

		return $data;
	}

	/**
	 * Get event array
	 *
	 * @access    private
	 * @return    array
	 */
	 function _get_event_array()
	{
		// Load the model
		$this->load->model('events_model');

		// fetch query object from the model with fields id, name
		$query = $this->events_model->fetch('events','id, name','','activeQ = 1','name ASC');

		// Loop through to build array
		$data = array();
		$data[0] = '';
		foreach ($query->result_array() as $row)
		{
			$data[$row['id']] = $row['name'];
		}

		return $data;
	}

	// -------------------------------------------------------------------------
	/**
	 * Check that item selected is not the zero (empty) choice
	 *
	 * @access    private
	 * @param     string  The string to check.
	 * @return    bool
	 */
	function _not_zero($str)
	{
		// Set the error message to use
		$this->validation->set_message('_not_zero','The %s field is required.');

		if ($str == 0)
			return FALSE;

		return TRUE;
	}

	// -------------------------------------------------------------------------
	/**
	 * Check whether event is already in room
	 *
	 * @access    private
	 * @param     string  The string to check.
	 * @return    bool
	 */
	function _duplicate($str)
	{
		// Set the error message to use
		$this->validation->set_message('_duplicate','This event has already been added to the room.');

		// if no room id, quit
		$roomid = $this->input->post('roomID', TRUE);
		if ($roomid == '')
			return TRUE;

		// if no event id, quit
		$eventid = $this->input->post('eventID', TRUE);
		if ($eventid == '')
			return TRUE;

		// get info
		$query = $this->eventrooms_model->fetch('eventRooms','id','','roomID = '.$roomid.' && eventID = '.$eventid);
		if ($query->num_rows() == 0)
		{
			return TRUE;  //good, no entries
		}

		return FALSE;  //bad
	}

	// -------------------------------------------------------------------------
	/**
	 * Check that event does not have a conflict before scheduling
	 *
	 * @access    private
	 * @param     string  The string to check.
	 * @return    bool
	 */
	function _check_room_conflict($str)
	{
		// Set the error message to use
		$this->validation->set_message('_check_room_conflict','The %s field cannot be scheduled due to a conflict.');

		// if no event id, there can be no conflicts
		$eventid = $this->input->post('eventID', TRUE);
		if ($eventid == '')
			return TRUE;  //good, no conflicts

		// get event info
		$this->load->model('events_model');
		$query = $this->events_model->fetch('events','startDateTime,eventLength,setupTime,teardownTime','','id = '.$eventid);
		if ($query->num_rows() == 0)
			return TRUE;  //good, no conflicts
		$eventrow = $query->row_array();
		$str = $eventrow['startDateTime'];  //get date string

		// if date is blank, there can be no conflicts
		if ($str == '0000-00-00 00:00:00' OR $str == '')
			return TRUE;  //good, no conflicts

		// get rooms used by this event
		//$this->load->model('eventrooms_model');
		//$query = $this->eventrooms_model->fetchEventRooms('event.id = '.$id);
		//if ($query->num_rows() == 0)
		//	return TRUE;  //good, no conflicts

		// convert rooms query to array
		//foreach ($query->result_array() as $row)
		//{
		//	$roomsort[$row['room_sortorder']] = $row['room_id'];  //room sortOrder
		//}

		// if no room id, there can be no conflicts
		$roomid = $this->input->post('roomID', TRUE);
		if ($roomid == '')
			return TRUE;  //good, no conflicts

		// get room info
		$this->load->model('rooms_model');
		$query = $this->rooms_model->fetch('rooms','sortOrder','','id = '.$roomid);
		if ($query->num_rows() == 0)
			return TRUE;  //good, no conflicts
		$roomrow = $query->row_array();
		$roomsort[$roomrow['sortOrder']] = $roomid;

		// get event data
		$sdttm = strtotime($str);
		$edttm = strtotime("+".($eventrow['eventLength']*3600).' seconds', $sdttm);
		$setup = strtotime("-".($eventrow['setupTime']*3600).' seconds', $sdttm);
		$teardown = strtotime("+".($eventrow['teardownTime']*3600).' seconds', $sdttm);
		$eventInfo = array('id' => $eventid,
							'sdttm' => date('Y-m-d H:i:s',$sdttm),
							'edttm' => date('Y-m-d H:i:s',$edttm),
							'setupdttm' => date('Y-m-d H:i:s',$setup),
							'teardowndttm' => date('Y-m-d H:i:s',$teardown),
							'setup' => $eventrow['setupTime'],
							'teardown' => $eventrow['teardownTime'],
							'eventlength' => $eventrow['eventLength']
							);

		// check that an event can fit on grid and return status
		$status = check_event_on_roomgrid($this->roomGrid, $roomsort, $eventInfo, $this->ccsettings->item('interval_length'));

		// if status is not blank, there was a problem
		if ($status != '')
		{
			flashMsg('warning',$status);
			return FALSE;  //bad, conflicts
		}

		return TRUE;  //good, no conflicts
	}



	// --------------------------------------------------------------------------------------------
	// Reports
	// --------------------------------------------------------------------------------------------

	// -------------------------------------------------------------------------
	/**
	* Reports Page
	*
	* @access      public
	* @return      none
	*/
	function reports()
	{
		// create urls for use in content view
		$template['base_url']   = 'concentric/eventrooms/reports/';
		$template['cancel_url'] = 'concentric/home';

		// Set breadcrumb
		$this->page->set_crumb('Event Rooms Reports','concentric/eventrooms/reports/');

		// set values for use in content view
		$template['form_attributes'] = array('name' => $this->form_name, 'id' => $this->form_name);
		$template['header'] = $this->form_name;

		// build content html
		$data['content'] = $this->load->view('/concentric/eventrooms/eventrooms_reports_menu', $template, TRUE);

		// set values for use in header view
		$data['header']  = $this->form_name;

		// pass all data to container view and display to user
		$this->load->view($this->_container,$data);
	}

	// -------------------------------------------------------------------------
	/**
	* Report all data
	*
	* @access      public
	* @return      none
	*/
	function rep_all()
	{
		// fetch query object from the model
		$template['eventrooms_list'] = $this->eventrooms_model->fetchEventRooms();

		// create urls for use in content view
		$template['base_url']   = 'concentric/eventrooms/reports/';
		$template['cancel_url'] = 'concentric/home';

		// Set breadcrumbs
		$this->page->set_crumb('Event Rooms Reports','concentric/eventrooms/reports/');
		$this->page->set_crumb('List All','concentric/eventrooms/rep_all/');

		// set values for use in content view
		$template['form_attributes'] = array('name' => $this->form_name, 'id' => $this->form_name);
		$template['header'] = $this->form_name;
		$template['mode'] = 'internal';

		// build content html using grid view and template data
		$data['content'] = $this->load->view('/concentric/eventrooms/eventrooms_list', $template, TRUE);

		// set values for use in header view
		$data['header']  = $this->form_name;

		// pass all data to container view and display to user
		$this->load->view($this->_container,$data);
	}

	// -------------------------------------------------------------------------
	/**
	* Download all data
	*
	* @access      public
	* @return      none
	*/
	function rep_download_all($eor = '')
	{
		// Load the helper
		$this->load->helper('download');

		// fetch query object from the model
		$query = $this->eventrooms_model->fetchEventRooms();

		// Initialize values
		$data = '';
		$eor = ($eor == '') ? '' : (',' . $eor);
		// Loop through the data and build the data
		foreach ($query->result_array() as $row)
		{
			$data .= '"' . $row['id'] . '","' . $row['event_name'] . '","' . $row['room_name'] . '"' . $eor . "\n";
		}

		// Download the file
		force_download('eventrooms.csv', $data);

		redirect('/concentric/eventrooms/reports', 'location');
	}


}


/* End of file eventrooms.php */
/* Location: ./system/application/controllers/concentric/eventrooms.php */
Return current item: ConCentric Event Planning Software