<?php
/**
 * @author QuanticaLabs - http://codecanyon.net/user/QuanticaLabs/portfolio?ref=QuanticaLabs
 *
 * @link			http://codecanyon.net/item/timetable-responsive-schedule-for-joomla/9749539?ref=QuanticaLabs
 * @copyright		Copyright (C) 2008 - 2014 quanticalabs.com . All rights reserved.
 * @license			GNU General Public License version 2 or later; see LICENSE under Licensing/ directory
 */
 
defined('_JEXEC') or die('Restricted access');

JLoader::register('TimetableHelper', JPATH_ADMINISTRATOR . '/components/com_timetable/helpers/timetable.php');

/**
 * Event Model
 */
class TimetableModelEvent extends JModelAdmin
{
	
	public $typeAlias = 'com_timetable.event';
	protected $text_prefix = 'COM_TIMETABLE';
	
	public function load_event_hour($event_hour_id) {
		$db = JFactory::getDbo();
		
		$query = "SELECT * 
			FROM 
				#__timetable_event_hours
			WHERE
				id = '" . $event_hour_id . "'
			LIMIT 1";
		$db->setQuery($query);
		$event_hour = $db->loadObject();
		$event_hour->start = date("H:i", strtotime($event_hour->start));
		$event_hour->end = date("H:i", strtotime($event_hour->end));
		return $event_hour;

	}
	
	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param       type    The table type to instantiate
	 * @param       string  A prefix for the table class name. Optional.
	 * @param       array   Configuration array for model. Optional.
	 *
	 * @return      JTable  A database object
	 * @since       2.5
	 */
	public function getTable($type = 'Events', $prefix = 'TimetableTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param       array   $data     Data for the form.
	 * @param       boolean $loadData True if the form is to load its own data (default case), false if not.
	 *
	 * @return      mixed   A JForm object on success, false on failure
	 * @since       2.5
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_timetable.event', 'event',
			array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form))
		{
			return false;
		}

		return $form;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return      mixed   The data for the form.
	 * @since       2.5
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_timetable.edit.event.data', array());
		if (empty($data))
		{
			$data = $this->getItem();
		}
		
		return $data;
	}
	
	protected function prepareTable($table)
	{
		$table->title = htmlspecialchars_decode($table->title, ENT_QUOTES);
		$table->alias = JApplication::stringURLSafe($table->alias);

		if(empty($table->alias))
		{
			$table->alias = JApplication::stringURLSafe($table->title);
		}
	}
	
	public function delete(&$pks) {
		$db = JFactory::getDbo();
		foreach($pks as $pk) {
			// clear event options
			$query = "DELETE FROM 
					#__timetable_event_options
				WHERE 
					event_id = " . $pk;
			$db->setQuery($query);
			$db->execute();
			
			// clear event hours
			$query = "DELETE FROM 
					#__timetable_event_hours
				WHERE 
					event_id = " . $pk;
			$db->setQuery($query);
			$db->execute();
		}
		parent::delete($pks);
	}
	public function save($data)	{
		if(parent::save($data)) {
			$db = JFactory::getDbo();
			$event_id = $this->state->{'event.id'};
			// save event options data
			$options = array();
			foreach($data as $key=>$val) {
				if(strpos($key, "option_") !== FALSE) {
					$options[str_replace("option_", "", $key)] = $val;
				}
			}
			
			foreach($options as $key=>$val) {
				$key = addslashes($key);
				$val = addslashes($val);
				$query = "SELECT option_id 
					FROM
						#__timetable_event_options
					WHERE
						event_id = '{$event_id}' AND
						option_key = '{$key}'";
				$db->setQuery($query);
				$result = $db->loadResult();
				
				if(empty($result)) {
					//insert
					$query = "INSERT INTO 
						#__timetable_event_options(
							event_id,
							option_key,
							option_value
						)
						VALUES(
							'{$event_id}',
							'{$key}',
							'{$val}'
						)";
				} else {
					//update
					$query = "UPDATE #__timetable_event_options
						SET
							option_value ='{$val}'
						WHERE
							event_id = '{$event_id}' AND
							option_key = '{$key}'";
				}
				$db->setQuery($query);
				$db->execute();
			}
		}
		return true;
	}
	
	public function getItem($pk = null)
	{
		if($item = parent::getItem($pk))
		{
			$db = JFactory::getDbo();
			
			// load event options
			$query = $db->getQuery(true);
			$query->select($db->quoteName(array('option_key', 'option_value')));
			$query->from($db->quoteName('#__timetable_event_options'));
			$query->where(array($db->quoteName('event_id') . ' =' . $db->quote($item->id)));
			$db->setQuery($query);
			$event_options = $db->loadAssocList();
			foreach($event_options as $event_options) {
				$key = "option_" . $event_options["option_key"];
				$item->$key = $event_options["option_value"];
			}
			
			// load categories
			$query = "SELECT id, title, alias 
				FROM 
					#__timetable_categories";
			$db->setQuery($query);
			$results = $db->loadObjectList();
			$categories = array();
			foreach($results as $result) {
				$categories[$result->id] = $result;
			}
			$item->categories = $categories;

			// load event categories
			$query = "SELECT category_id
				FROM 
					#__timetable_event_categories
				WHERE
					event_id='{$item->id}'";
			$db->setQuery($query);
			$results = $db->loadObjectList();
			$event_categories = array();
			foreach($results as $result) {
				$event_categories[] = $result->category_id;
			}
			$item->event_categories = $event_categories;
			
			// load columns
			$query = "SELECT id, title, alias 
				FROM 
					#__timetable_columns";
			$db->setQuery($query);
			$results = $db->loadObjectList();
			$columns = array();
			foreach($results as $result) {
				$columns[$result->id] = $result;
			}
			$item->columns = $columns;
			
			// load event hours
			if(!empty($item->id)) {
				$query = "SELECT `id`, `event_id`, `weekday_id`, TIME_FORMAT(`start`, '%H:%i') start, TIME_FORMAT(`end`, '%H:%i') end, `tooltip`, `before_hour_text`, `after_hour_text`, `category`
					FROM 
						#__timetable_event_hours 
					WHERE
						event_id = " . $item->id;
				$db->setQuery($query);
				$item->event_hours = $db->loadObjectList();
			}

			
		}
		return $item;
	}
}