<?php
/**
 * @package     JBusinessDirectory
 * @subpackage  com_jbusinessdirectory
 *
 * @copyright   Copyright (C) 2007 - 2015 CMS Junkie. All rights reserved.
 * @license     GNU General Public License version 2 or later;
 */
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');
require_once JPATH_COMPONENT_SITE . '/classes/attributes/attributeservice.php';
/**
 * List Model.
 *
 * @package JBusinessDirectory
 * @subpackage com_jbusinessdirectory
 */
class JBusinessDirectoryModelEvents extends JModelList {
	/**
	 * Constructor.
	 *
	 * @param   array  An optional associative array of configuration settings.
	 *
	 * @see     JController
	 * @since   1.6
	 */
	public function __construct($config = array()) {
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = array(
				'id', 'co.id',
				'name', 'co.name',
				'companyName', 'bc.name',
				'price', 'co.price',
				'specialPrice', 'co.specialPrice',
				'type', 'co.type',
				'location', 'co.location',
				'start_date', 'co.start_date',
				'end_date', 'co.end_date',
				'view_count', 'co.view_count',
				'eventOfTheDay', 'co.eventOfTheDay',
				'featured', 'co.featured',
				'state', 'co.state',
				'approved', 'co.approved'
			);
		}

		parent::__construct($config);
	}

	/**
	 * Overrides the getItems method to attach additional metrics to the list.
	 *
	 * @return  mixed  An array of data items on success, false on failure.
	 *
	 * @since   1.6.1
	 */
	public function getItems() {
		$appSettings = JBusinessUtil::getApplicationSettings();
		$packagesTable = JTable::getInstance('Package', 'JTable', array());
		$eventsTable = JTable::getInstance('Event', 'JTable', array());

		// Get a storage key.
		$store = $this->getStoreId('getItems');

		// Try to load the data from internal storage.
		if (!empty($this->cache[$store])) {
			return $this->cache[$store];
		}

		// Load the list items.
		$items = parent::getItems();

		// If empty or an error, just return.
		if (empty($items)) {
			return array();
		}
		
		foreach ($items as $item) {
			$item->start_date = JBusinessUtil::convertToFormat($item->start_date);
			$item->end_date = JBusinessUtil::convertToFormat($item->end_date);

			$item->allow_events = false;
			$item->expired = false;

			if (!$appSettings->enable_packages || $appSettings->item_decouple) {
				$item->allow_events = true;
				$companyTable = JTable::getInstance('Company', 'JTable', array());
				if (!$appSettings->item_decouple) {
					$company = $companyTable->getPlainCompany($item->company_id);
					if (empty($company)) {
						$item->not_visible = false;
						$item->allow_events = false;
					}
				}
			} elseif (!empty($item->company_id)) {
				$package = $packagesTable->getCurrentActivePackage($item->company_id);

				if (!empty($package->features)) {
					$item->features = $package->features;
				} else {
					$item->features = array();
				}

				if (in_array(COMPANY_EVENTS, $item->features)) {
					$item->allow_events = true;
				}
			}

			if (!empty($item->end_date) && $item->end_date != '0000-00-00') {
				$tz = $item->time_zone;
				$dt = new DateTime("now");
				if (!empty($tz)) {
					$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
				}

				// apply time zone
				$today = $dt->format("Y-m-d H:i:s");

				// Create Y-m-d H:i:s format if start/end hour is available, if not, 00:00:00 is set as start hour and 23:59:59 as end hour
				$endDate = $item->end_date . ' 00:00:00';
				if (!empty($item->end_time)) {
					$endDate = $item->end_date . ' ' . $item->end_time;
				}

				if (strtotime($today) > strtotime($endDate)) {
					$item->expired = true;
				}
			}
		}

		// Add the items to the internal cache.
		$this->cache[$store] = $items;

		return $this->cache[$store];
	}

	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return  string  An SQL query
	 *
	 * @since   1.6
	 */
	protected function getListQuery() {
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		
		
		// Select all fields from the table.
		$query->select($this->getState('list.select', 'co.*'));
		$query->from($db->quoteName('#__jbusinessdirectory_company_events').' AS co');
		
		// Join over the company types
		$query->select('bc.name as companyName');
		$query->join('LEFT', $db->quoteName('#__jbusinessdirectory_companies').' AS bc ON bc.id=co.company_id');
		
		// Join over the company types
		$query->select('et.name as eventType');
		$query->join('LEFT', $db->quoteName('#__jbusinessdirectory_company_event_types').' AS et ON co.type=et.id');

		// Join over the event pictures
		$query->select('cep.picture_path, cep.picture_enable');
		$query->join('LEFT', $db->quoteName('#__jbusinessdirectory_company_event_pictures').' AS cep ON cep.eventId=co.id 
				and
					(cep.id in (
							select  min(op1.id) as min from #__jbusinessdirectory_company_events co1
							left join  #__jbusinessdirectory_company_event_pictures op1 on co1.id=op1.eventId
							where op1.picture_enable=1
							group by co1.id
					))
				
				');
		
		// Filter by search in title.
		$search = $this->getState('filter.search');
		$search = trim($search);
		
		$keywords = array();
		if (strpos($search, '"') === false) {
			$keyword = $db->escape($search);
			$keywords = explode(" ", $keyword);
		} else {
			$keyword = trim($search, '"');
			$keyword = $db->escape($keyword);
			$keywords = array($keyword);
		}
		
		if (!empty($search)) {
			$query->where("(co.name LIKE '%". implode("%' or co.name LIKE '%", $keywords) ."%' or 
							co.location LIKE '%". implode("%' or co.location LIKE '%", $keywords) ."%' or 
						  	bc.name LIKE '%". implode("%' or bc.name LIKE '%", $keywords) ."%' )");
		}
		
		$listingId = $this->getState('filter.listing_id');
		if (is_numeric($listingId)) {
			$query->where('co.company_id ='.(int) $listingId);
		}
		
		$statusId = $this->getState('filter.status_id');
		if (is_numeric($statusId)) {
			$query->where('co.approved ='.(int) $statusId);
		}
	
		$stateId = $this->getState('filter.state_id');
		if (is_numeric($stateId)) {
			$query->where('co.state ='.(int) $stateId);
		}
	
		$query->group('co.id');

		// Add the list ordering clause.
		$orderCol  = $this->state->get('list.ordering', 'co.id');
		$orderDirn = $this->state->get('list.direction', 'ASC');

		// Add the list ordering clause.
		$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDirn));

		return $query;
	}

	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @param   string  $ordering   An optional ordering field.
	 * @param   string  $direction  An optional direction (asc|desc).
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function populateState($ordering = 'co.id', $direction = 'desc') {
		$app = JFactory::getApplication('administrator');

		$listingId = $this->getUserStateFromRequest($this->context.'.filter.listing_id', 'listing_id');
		$this->setState('filter.listing_id', $listingId);
		
		$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);
		
		$statusId = $app->getUserStateFromRequest($this->context.'.filter.status_id', 'filter_status_id');
		$this->setState('filter.status_id', $statusId);
	
		$stateId = $app->getUserStateFromRequest($this->context.'.filter.state_id', 'filter_state_id');
		$this->setState('filter.state_id', $stateId);
	
		// Check if the ordering field is in the white list, otherwise use the incoming value.
		$value = $app->getUserStateFromRequest($this->context.'.ordercol', 'filter_order', $ordering);
		$this->setState('list.ordering', $value);
	
		// Check if the ordering direction is valid, otherwise use the incoming value.
		$value = $app->getUserStateFromRequest($this->context.'.orderdir', 'filter_order_Dir', $direction);
		$this->setState('list.direction', $value);
		
		// List state information.
		parent::populateState($ordering, $direction);
	}
	
	public function getCompanyTypes() {
		$companiesTable = $this->getTable("Company");
		return $companiesTable->getCompanyTypes();
	}
	
	public function getStates() {
		$states = array();
		$state = new stdClass();
		$state->value = 0;
		$state->text = JTEXT::_("LNG_INACTIVE");
		$states[] = $state;
		$state = new stdClass();
		$state->value = 1;
		$state->text = JTEXT::_("LNG_ACTIVE");
		$states[] = $state;
	
		return $states;
	}
	
	public function getStatuses() {
		$statuses = array();
		$status = new stdClass();
		$status->value = 0;
		$status->text = JTEXT::_("LNG_NEEDS_CREATION_APPROVAL");
		$statuses[] = $status;
		$status = new stdClass();
		$status->value = -1;
		$status->text = JTEXT::_("LNG_DISAPPROVED");
		$statuses[] = $status;
		$status = new stdClass();
		$status->value = 1;
		$status->text = JTEXT::_("LNG_APPROVED");
		$statuses[] = $status;
	
		return $statuses;
	}
	
	public function exportEventsCSVtoFile($path) {
		$csv_output = $this->getEventsCSV();
		$result =  file_put_contents($path, $csv_output);
		return $result;
	}
	
	public function getEventsCSV() {
		$languages = JBusinessUtil::getLanguages();
		$jinput    = JFactory::getApplication()->input;
		$delimiter = $jinput->getString("delimiter", ",");
		$includeId = $jinput->get("include_id");

		$eventAttributesTable = JTable::getInstance("EventAttributes", "JTable");
		$eventTable = JTable::getInstance("Event", "JTable");
		$attributesTable = JTable::getInstance("Attribute", "JTable");
		$attributes = $attributesTable->getAttributes(ATTRIBUTE_TYPE_EVENT);
		$categoryTable = JTable::getInstance("Category", "JBusinessTable");


		$csv_output = "";
		$name = "name".$delimiter;
		$shortDesc = "short_description".$delimiter;
		$desc = "description".$delimiter;
		$metaName = "meta_title".$delimiter;
		$metaDesc = "meta_description".$delimiter;
		$metaKey = "meta_keywords".$delimiter;
		foreach ($languages as $lng) {
			$name.="name_$lng".$delimiter;
			$shortDesc.="short_description_$lng".$delimiter;
			$desc.="description_$lng".$delimiter;
			$metaName.="meta_title_$lng".$delimiter;
			$metaDesc.="meta_description_$lng".$delimiter;
			$metaKey.="meta_keywords_$lng".$delimiter;
		}

		if (isset($includeId)) {
			$csv_output .= "id".$delimiter; 
		}

		$csv_output .= $name ."alias".$delimiter.$shortDesc.$desc
			."eventType".$delimiter ."type_id".$delimiter."company".$delimiter ."company_id".$delimiter."state".$delimiter
			."currency_id".$delimiter."price".$delimiter."approved".$delimiter."view_count".$delimiter."categories".$delimiter
			."main_subcategory".$delimiter."start_date".$delimiter."end_date".$delimiter."start_time".$delimiter
			."end_time".$delimiter."doors_open_time".$delimiter."booking_open_date".$delimiter ."booking_close_date".$delimiter
			."booking_open_time".$delimiter."booking_close_time".$delimiter."show_start_time".$delimiter ."show_end_time".$delimiter
			."show_end_date".$delimiter."show_doors_open_time".$delimiter."street_number".$delimiter."address".$delimiter."area".$delimiter."country".$delimiter."city".$delimiter
			."province".$delimiter."county".$delimiter."postal_code".$delimiter."latitude" .$delimiter."longitude".$delimiter."recurring_id".$delimiter
			."contact_phone".$delimiter."contact_email".$delimiter."pictures".$delimiter.$metaName
			.$metaDesc.$metaKey."expiration_email_date".$delimiter."user_id".$delimiter
			."featured".$delimiter."created".$delimiter."attendance_mode".$delimiter."attendance_url";
		
		if (!empty($attributes)) {
			foreach ($attributes as $attribute) {
				$csv_output = $csv_output.$delimiter."attribute_".$attribute->name;
			}
		}

	
		$csv_output = $csv_output."\n";
	
		$start = 0;
		$batch = ITEMS_BATCH_SIZE;
		do {
			$events = $eventTable->getEventsForExport($start, $batch);
			if (count($events)>0) {
				foreach ($events as $event) {
					$subCategory = "";
					if (!empty($event->main_subcategory)) {
						$sub = $categoryTable->getCategoryById($event->main_subcategory);
						if (isset($sub)) {
							$subCategory = $sub->name;
						}
					}

					$event->short_description = str_replace(array("\r\n", "\r", "\n"), "<br />", $event->short_description);
					$event->short_description = str_replace('"', '""', $event->short_description);
					$event->description = str_replace(array("\r\n", "\r", "\n"), "<br />", $event->description);
					$event->description = str_replace('"', '""', $event->description);
					
					$event->meta_keywords= str_replace(array("\r\n", "\r", "\n"), "<br />", $event->meta_keywords);
					$event->meta_keywords= str_replace('"', '""', $event->meta_keywords);
					
					$event->meta_description = str_replace(array("\r\n", "\r", "\n"), "<br />", $event->meta_description);
					$event->meta_description = str_replace('"', '""', $event->meta_description);


					$translations = JBusinessDirectoryTranslations::getAllTranslations(EVENT_DESCRIPTION_TRANSLATION, $event->id);
					$translationsMeta = JBusinessDirectoryTranslations::getAllTranslations(EVENT_META_TRANSLATION, $event->id);

					$name = "\"$event->name\"" . $delimiter;
					$shortDesc = "\"$event->short_description\"" . $delimiter;
					$desc = "\"$event->description\"" . $delimiter;
					$metaName = "\"$event->meta_title\"" . $delimiter;
					$metaDesc = "\"$event->meta_description\"" . $delimiter;
					$metaKey = "\"$event->meta_keywords\"" . $delimiter;
					foreach ($languages as $lng) {
						$langContentName = isset($translations[$lng . "_name"]) ? $translations[$lng . "_name"] : "";
						$langContentShort = isset($translations[$lng . "_short"]) ? $translations[$lng . "_short"] : "";
						$langContentDesc = isset($translations[$lng]) ? $translations[$lng] : "";
						$contentNameMeta = isset($translationsMeta[$lng . "_name"]) ? $translationsMeta[$lng . "_name"] : "";
						$contentDescMeta = isset($translationsMeta[$lng]) ? $translationsMeta[$lng] : "";
						$contentKeyMeta = isset($translationsMeta[$lng . "_short"]) ? $translationsMeta[$lng . "_short"] : "";

						$name .= "\"".$langContentName."\"".$delimiter;
						$shortDesc .= "\"".$langContentShort."\"".$delimiter;
						$desc .= "\"".$langContentDesc."\"".$delimiter;
						$metaName .= "\"".$contentNameMeta."\"".$delimiter;
						$metaDesc .= "\"".$contentDescMeta."\"".$delimiter;
						$metaKey .= "\"".$contentKeyMeta."\"".$delimiter;
					}

					if (isset($includeId)) {
						$csv_output .= "\"$event->id\"".$delimiter; 
					}

					$csv_output .= $name."\"$event->alias\"".$delimiter .$shortDesc.$desc."\"$event->eventType\"".$delimiter
						."\"$event->type\"".$delimiter."\"$event->company\"".$delimiter."\"$event->company_id\"".$delimiter."\"$event->state\"".$delimiter
						."\"$event->currency_id\"".$delimiter."\"$event->price\"".$delimiter."\"$event->approved\"".$delimiter."\"$event->view_count\"".$delimiter
						."\"$event->categories\"".$delimiter ."\"$subCategory\"".$delimiter."\"$event->start_date\"".$delimiter
						."\"$event->end_date\"".$delimiter."\"$event->start_time\"".$delimiter ."\"$event->end_time\"".$delimiter."\"$event->doors_open_time\"".$delimiter
						."\"$event->booking_open_date\"".$delimiter ."\"$event->booking_close_date\"".$delimiter."\"$event->booking_open_time\"".$delimiter
						."\"$event->booking_close_time\"".$delimiter ."\"$event->show_start_time\"".$delimiter."\"$event->show_end_time\"".$delimiter
						."\"$event->show_end_date\"".$delimiter ."\"$event->show_doors_open_time\"".$delimiter ."\"$event->street_number\"".$delimiter ."\"$event->address\"".$delimiter
						."\"$event->area\"". $delimiter . "\"$event->countryName\"".$delimiter."\"$event->city\"".$delimiter."\"$event->province\"".$delimiter."\"$event->county\"".$delimiter."\"$event->postalCode\"".$delimiter
						."\"$event->latitude\"".$delimiter."\"$event->longitude\"".$delimiter."\"$event->recurring_id\"".$delimiter
						."\"$event->contact_phone\"".$delimiter."\"$event->contact_email\"".$delimiter."\"$event->pictures\"".$delimiter
						.$metaName.$metaDesc.$metaKey ."\"$event->expiration_email_date\"".$delimiter."\"$event->user_id\"".$delimiter."\"$event->featured\"".$delimiter."\"$event->created\"".$delimiter;
						
						$attendanceMode = JBusinessUtil::getAttendanceModeText($event->attendance_mode);
						$csv_output .= "\"$attendanceMode\"".$delimiter."\"$event->attendance_url\"";

						$eventAttributes = $eventAttributesTable->getEventAttributes($event->id);
					foreach ($attributes as $attribute) {
						$found = false;
						foreach ($eventAttributes as $key => $companyAttribute) {
							if ($attribute->code == $companyAttribute->code) {
								$attributeValue = AttributeService::getAttributeValues($companyAttribute);
								$csv_output .= $delimiter."\"$attributeValue\"";
								$found = true;
								unset($eventAttributes[$key]);
								break;
							}
						}
						if (!$found) {
							$csv_output .= $delimiter."\"\"";
						}
					}
					$csv_output .= "\n";
				}
			}
			$start += $batch;
		} while (count($events) == $batch);
			
		return $csv_output;
	}

	public function exportEventsCSV() {
		$csv_output = $this->getEventsCSV();

		$fileName = "jbusinessdirectory_events";
		header("Content-type: application/vnd.ms-excel");
		header("Content-disposition: csv" . date("Y-m-d") . ".csv");
		header("Content-disposition: filename=".$fileName.".csv");
		print $csv_output;
	}

	
	public function getEventsWithTranslationCSV() {
		$jinput    = JFactory::getApplication()->input;
		$delimiter = $jinput->getString("delimiter", ",");
	
		$eventTable = $this->getTable("Event", 'JTable');
	
		$languages = JBusinessUtil::getLanguages();
		$start = 0;
		$batch = ITEMS_BATCH_SIZE;
		$events = $eventTable->getEventsForExport($start, $batch);
	
		$csv_output = "ID".$delimiter."Name".$delimiter."Company_id".$delimiter."Company".$delimiter."Currency_Id".$delimiter."Short_Description".$delimiter;
	
		foreach ($languages as $language) {
			$csv_output .= "Short_Description $language".$delimiter;
		}
	
		$csv_output .= "Description".$delimiter;
	
		foreach ($languages as $language) {
			$csv_output .= "Description $language".$delimiter;
		}
	
		$csv_output .= "CategoriesIds".$delimiter."Event_Type".$delimiter."Pictures".$delimiter."Price".$delimiter."Type_ID".$delimiter."Start_Date".$delimiter."End_Date".$delimiter."Start_Time".$delimiter."End_Time".$delimiter."Approved".$delimiter."Full_Address".$delimiter."City".$delimiter."Country".$delimiter."Location".$delimiter."Latitude".$delimiter."Longitude".$delimiter."Created".$delimiter."View_Count".$delimiter."State".$delimiter."Recurring_Id".$delimiter."Contact_Phone".$delimiter."Contact_Email".$delimiter."Doors_Open_Time".$delimiter."Booking_Open_Date".$delimiter."Booking_Close_Date".$delimiter."Booking_Open_Time".$delimiter."Booking_Close_Time".$delimiter."Show_Start_Time".$delimiter."Show_End_Time".$delimiter."Show_End_Date".$delimiter."Show_Doors_Open_Time".$delimiter."Total_Tickets".$delimiter."Main_Subcategory";
	
		$csv_output = $csv_output."\n";
	
		foreach ($events as $event) {
			$companyCategoryTable = $this->getTable('CompanyCategory', 'JTable');
			$event->selectedCategories = $companyCategoryTable->getSelectedEventCategories($event->id);
			//   dump($event);exit;
	
			$event->short_description = str_replace(array("\r\n", "\r", "\n"), "<br />", $event->short_description);
			$event->description = str_replace(array("\r\n", "\r", "\n"), "<br />", $event->description);
			$event->description = str_replace('"', '""', $event->description);
	
			$csv_output .= $event->id.$delimiter."\"$event->name\"".$delimiter."\"$event->company_id\"".$delimiter."\"$event->company\"".$delimiter."\"$event->currency_id\"".$delimiter."\"$event->short_description\"".$delimiter;
	
			foreach ($languages as $lng) {
				$content_short = array();
				$translation = JBusinessDirectoryTranslations::getObjectTranslation(EVENT_DESCRIPTION_TRANSLATION, $event->id, $lng);
				$content_short[] = empty($translation)?"":$translation->name;
				if (empty($content_short)) {
					$csv_output.= "".$delimiter;
				} else {
					$csv_output.= "\"".implode(",", $content_short)."\"".$delimiter;
				}
			}
	
			$csv_output .= "\"$event->description\"".$delimiter;
	
			foreach ($languages as $lng) {
				$content = array();
				$translation = JBusinessDirectoryTranslations::getObjectTranslation(EVENT_DESCRIPTION_TRANSLATION, $event->id, $lng);
				$content[] = empty($translation)?"":$translation->name;
				if (empty($content)) {
					$csv_output.= "".$delimiter;
				} else {
					$csv_output.= "\"".implode(",", $content)."\"".$delimiter;
				}
			}
	
			$csv_output .= "\"".implode(",", $event->selectedCategories)."\"".$delimiter."\"$event->eventType\"".$delimiter;
	
			$pictures = explode(",", $event->pictures);
			foreach ($pictures as &$picture) {
				$picture = BD_PICTURES_PATH.$picture;
			}
			$pictures = implode(",", $pictures);
			$csv_output .="\"".$pictures."\"";
	
	
			$csv_output .= $delimiter."\"$event->price\"".$delimiter."\"$event->type\"".$delimiter."\"$event->start_date\"".$delimiter."\"$event->end_date\"".$delimiter."\"$event->start_time\"".$delimiter."\"$event->end_time\"".$delimiter."\"$event->approved\"".$delimiter."\"$event->address\"".$delimiter."\"$event->city\"".$delimiter."\"$event->county\"".$delimiter."\"$event->location\"".$delimiter."\"$event->latitude\"".$delimiter."\"$event->longitude\"".$delimiter."\"$event->created\"".$delimiter."\"$event->view_count\"".$delimiter."\"$event->state\"".$delimiter."\"$event->recurring_id\"".$delimiter."\"$event->contact_phone\"".$delimiter."\"$event->contact_email\"".$delimiter."\"$event->doors_open_time\"".$delimiter."\"$event->booking_open_date\"".$delimiter."\"$event->booking_close_date\"".$delimiter."\"$event->booking_open_time\"".$delimiter."\"$event->booking_close_time\"".$delimiter.$event->show_start_time.$delimiter.$event->show_end_time.$delimiter.$event->show_end_date.$delimiter.$event->show_doors_open_time.$delimiter."\"$event->total_tickets\"".$delimiter."\"$event->main_subcategory\"";
	
			$csv_output .= "\n";
		}
	
		return $csv_output;
	}
}
