<?php
/*
 * Copyright (c) 2026, Tribal Limited
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Zenario, Tribal Limited nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL TRIBAL LTD BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
if (!defined('NOT_ACCESSED_DIRECTLY')) exit('This file may not be directly accessed');




class zenario_ctype_event extends ze\moduleBaseClass {
	
	public $targetID = false;
	public $targetVersion = false;
	public $targetType = false;
	
	protected $data = [];
	
	function init() {
		$this->allowCaching(
			$atAll = true, $ifUserLoggedIn = true, $ifGetOrPostVarIsSet = false, $ifSessionVarOrCookieIsSet = true);
		$this->clearCacheBy(
			$clearByContent = true, $clearByMenu = false, $clearByFile = false, $clearByModuleData = false);
		
		return true;
	}
	
	function showSlot() {
		$this->targetID = $this->cID;
		$this->targetVersion = $this->cVersion;
		$this->targetType = $this->cType;
		
		if ($this->targetType != 'event') {
			if (ze\admin::id()) {
				echo ze\admin::phrase("This plugin must be placed on a layout used by Event content items.");
			}
			return;
		}
		
		if ($event = $this->getEventDetails($this->targetID, $this->targetVersion)) {

			if ($this->setting('show_title')) {
				$this->data['show_title'] = true;
				$this->data['title'] = htmlspecialchars(ze\content::title($this->targetID, $this->targetType, $this->targetVersion));
				$this->data['title_tags'] = $this->setting('title_tags');
			}
			

			$useTimezones = false;
			$selectedTimezone = '';
			
			if (ze::setting('zenario_ctype_event__timezone_support')) {
				if ($event['specify_time']) {
					if ($event['event_timezone'] == 'default_timezone') {
						$selectedTimezone = ze::setting('zenario_timezones__default_timezone');
					} else {
						$selectedTimezone = $event['event_other_timezone'];
					}
				}
				
				if ($selectedTimezone) {
					$useTimezones = true;
				
					$timezones = ze\dataset::getTimezonesLOV();
					$this->data['timezone_label'] = $timezones[$selectedTimezone]['label'];
				}
			}
			
			if (($event['start_date'] ?? false) == ($event['end_date'] ?? false)) {
				$this->data['dates_range'] = $this->phrase('[[date]]', ['date'=> ze\date::format($event['start_date'] ?? false, $this->setting('date_format'), false, false)]);
			} else {
				$this->data['dates_range'] = $this->phrase(
					'[[start_date]] to [[end_date]]',
					[
						'start_date'=> ze\date::format($event['start_date'] ?? false, $this->setting('date_format'), false, false),
						'end_date'=> ze\date::format($event['end_date'] ?? false, $this->setting('date_format'), false, false)
					]
				);
			}
			
			if (!empty($event['start_time']) && (($event['start_time'] ?? false) != '00:00:00')) {
				if (!empty($event['end_time']) && (($event['start_time'] ?? false) != ($event['end_time'] ?? false))) {
					$this->data['dates_range'] .= " " . $this->phrase('[[start_time]] to [[end_time]]', ['start_time' => ze\date::formatTime($event['start_time'], ze::setting('vis_time_format'),''),
																								'end_time'=> ze\date::formatTime($event['end_time'], ze::setting('vis_time_format'),'')]);
				} else {
					$this->data['dates_range'] .= " " .  $this->phrase('[[time]]', ['time'=> ze\date::formatTime($event['start_time'], ze::setting('vis_time_format'),'')]);
				}
			}
			
			if (!empty($event['stop_dates'])) {
				$stopDates = explode(',', $event['stop_dates']);
				if (count($stopDates)) {
					foreach ($stopDates as $K => $stopDate){
						$stopDates[$K] = ze\date::format($stopDate, $this->setting('date_format'), false, false);
					}
					
					$this->data['stop_dates'] = implode(', ', $stopDates);
				}
			}
			
			if ($event['url']) {
				$this->data['More_Info_Url'] = true;
				$this->data['event_url'] = htmlspecialchars($event['url']);
			}

			$locationFieldSetting = ze::setting('zenario_ctype_event__location_field');
			$locationTextSetting = ze::setting('zenario_ctype_event__location_text');
			if (
				$locationFieldSetting !== false && $locationFieldSetting != 'hidden'
				&& $this->setting('show_online_when_event_is_online')
				&& $event['online']
				&& ($onlineText = $this->setting('online_text'))
			) {
				$this->data['Online_Text'] = $onlineText;
			}

			if ($locationFieldSetting !== false && $locationFieldSetting != 'hidden' && $this->setting('show_address')) {
				//Check if this is an address of a location that exists in the DB,
				//or an address not in DB.
				if (ze\module::inc('zenario_location_manager') && $event['location_id']) {
					$locationDetails = zenario_location_manager::getLocationDetails($event['location_id']);
					if (!empty($locationDetails) && is_array($locationDetails)) {
						$locationAddressFormatted = [];

						//Loop through these fields...
						$locationAddressFields = [
							$locationDetails['address1'],
							$locationDetails['address2'],
							$locationDetails['locality'],
							$locationDetails['city'],
							$locationDetails['state'],
							$locationDetails['postcode']
						];

						//... and make sure they're not blank.
						foreach ($locationAddressFields as $locationAddressField) {
							if ($locationAddressField) {
								$locationAddressFormatted[] = $locationAddressField;
							}
						}

						//Display the country name if possible.
						if (ze\module::inc('zenario_country_manager')) {
							$countryName = zenario_country_manager::getCountryName($locationDetails['country_id']);

							if ($countryName) {
								$locationAddressFormatted[] = $countryName;
							}
						}

						if (!empty($locationDetails)) {
							$this->data['Address_Text'] = implode(', ', $locationAddressFormatted);
						}
					}
				} elseif ($locationTextSetting && $event['location']) {
					$this->data['Address_Text'] = $event['location'];
				}

				if ($this->setting('show_at_location_text')) {
					$atLocationText = $this->setting('at_location_text');

					$this->data['At_Location_Text'] = $atLocationText;
				}
			}
			
			$allowPinnedContent = ze\row::get('content_types', 'allow_pinned_content', ['content_type_id' => 'event']);
			if ($allowPinnedContent) {
				$pinned = ze\row::get('content_item_versions', 'pinned', ['id' => $this->targetID, 'type' => 'event', 'version' => $this->targetVersion]);
				
				if ($pinned) {
					$isAdmin = false;
					if (ze\admin::id()) {
						$isAdmin = true;
					}
					
					$showPinnedIcon = $this->setting('pinned_events_icon');
					if ($showPinnedIcon == 'show_to_all' || ($showPinnedIcon == 'show_to_admins_only' && $isAdmin)) {
						$this->data['Show_Pinned_Icon'] = true;
					}
					
					$showPinnedText = $this->setting('pinned_events_text');
					if ($showPinnedText == 'show_to_all' || ($showPinnedText == 'show_to_admins_only' && $isAdmin)) {
						$this->data['Show_Pinned_Text'] = true;
						$this->data['Pinned_Text'] = $this->phrase($this->setting('pinned_events_text_wording'));
						$this->data['Pinned_Text_Html_Tag'] = $this->setting('pinned_events_text_html_tag');
					}
				}
			}
			
			$this->data['Event_Details'] = true;
			$this->twigFramework($this->data);
		}
	}	

	public function fillAdminBox($path, $settingGroup, &$box, &$fields, &$values) {
		switch ($path) {
			case 'zenario_content':
				if ($box['key']['cType'] == 'event') {
					$duplicatingOrTranslating = ($box['key']['duplicate'] || $box['key']['duplicate_from_menu'] || $box['key']['translate']);
					
					$fields['zenario_ctype_event__when_and_where/start_time_hours']['values'] =
					$fields['zenario_ctype_event__when_and_where/end_time_hours']['values'] = [
						"00" => ['label' => "00", 'ord' => 1],
						"01" => ['label' => "01", 'ord' => 2],
						"02" => ['label' => "02", 'ord' => 3],
						"03" => ['label' => "03", 'ord' => 4],
						"04" => ['label' => "04", 'ord' => 5],
						"05" => ['label' => "05", 'ord' => 6],
						"06" => ['label' => "06", 'ord' => 7],
						"07" => ['label' => "07", 'ord' => 8],
						"08" => ['label' => "08", 'ord' => 9],
						"09" => ['label' => "09", 'ord' => 10],
						"10" => ['label' => "10", 'ord' => 11],
						"11" => ['label' => "11", 'ord' => 12],
						"12" => ['label' => "12", 'ord' => 13],
						"13" => ['label' => "13", 'ord' => 14],
						"14" => ['label' => "14", 'ord' => 15],
						"15" => ['label' => "15", 'ord' => 16],
						"16" => ['label' => "16", 'ord' => 17],
						"17" => ['label' => "17", 'ord' => 18],
						"18" => ['label' => "18", 'ord' => 19],
						"19" => ['label' => "19", 'ord' => 20],
						"20" => ['label' => "20", 'ord' => 21],
						"21" => ['label' => "21", 'ord' => 22],
						"22" => ['label' => "22", 'ord' => 23],
						"23" => ['label' => "23", 'ord' => 24]
					];
					
					$fields['zenario_ctype_event__when_and_where/start_time_minutes']['values'] =
					$fields['zenario_ctype_event__when_and_where/end_time_minutes']['values'] = [
						"00" => ['label' => "00", 'ord' => 1],
                        "05" => ['label' => "05", 'ord' => 2],
                        "10" => ['label' => "10", 'ord' => 3],
                        "15" => ['label' => "15", 'ord' => 4],
                        "20" => ['label' => "20", 'ord' => 5],
                        "25" => ['label' => "25", 'ord' => 6],
                        "30" => ['label' => "30", 'ord' => 7],
                        "35" => ['label' => "35", 'ord' => 8],
                        "40" => ['label' => "40", 'ord' => 9],
                        "45" => ['label' => "45", 'ord' => 10],
                        "50" => ['label' => "50", 'ord' => 11],
                        "55" => ['label' => "55", 'ord' => 12],
                        "59" => ['label' => "59", 'ord' => 13]
					];
					
					if (($box['key']['source_cID'] ?? false) && ($box['key']['source_cVersion'] ?? false)) {
						$eventDetails = $this->getEventDetails($box['key']['source_cID'], $box['key']['source_cVersion']);
	
						if (!empty($eventDetails) && is_array($eventDetails)) {
							$values['zenario_ctype_event__when_and_where/start_date'] = $eventDetails['start_date'];
							$values['zenario_ctype_event__when_and_where/end_date'] = $eventDetails['end_date'];
							$values['zenario_ctype_event__when_and_where/specify_time'] = $eventDetails['specify_time'];
							$values['zenario_ctype_event__when_and_where/late_evening_event'] = $eventDetails['next_day_finish'];
	
							if (!empty($eventDetails['start_time'])) {
								$startTime = explode(":", $eventDetails['start_time']);
							} else {
								$startTime = [];
							}
							
							if (!empty($eventDetails['end_time'])) {
								$endTime = explode(":", $eventDetails['end_time']);
							} else {
								$endTime = [];
							}
							
							$values['zenario_ctype_event__when_and_where/start_time_hours'] = $startTime[0] ?? false;
							$values['zenario_ctype_event__when_and_where/start_time_minutes'] = $startTime[1] ?? false;
		
							$values['zenario_ctype_event__when_and_where/end_time_hours'] = $endTime[0] ?? false;
							$values['zenario_ctype_event__when_and_where/end_time_minutes'] = $endTime[1] ?? false;
		
							$values['zenario_ctype_event__when_and_where/url'] =
							$values['zenario_ctype_event__when_and_where/event_url_original'] = $eventDetails['url'];
							
							$values['zenario_ctype_event__when_and_where/online'] = $eventDetails['online'];
							$values['zenario_ctype_event__when_and_where/location'] = $eventDetails['location'];
							$values['zenario_ctype_event__when_and_where/location_id'] = $eventDetails['location_id'];
							
							$values['zenario_ctype_event__when_and_where/online_original'] = $eventDetails['online'];
							$values['zenario_ctype_event__when_and_where/location_original'] = $eventDetails['location'];
							$values['zenario_ctype_event__when_and_where/location_id_original'] = $eventDetails['location_id'];
	
							if ($eventDetails['location'] || $eventDetails['location_id']) {
								$values['zenario_ctype_event__when_and_where/at_location_checkbox'] = true;
								$values['zenario_ctype_event__when_and_where/at_location_checkbox_original'] = true;
		
								if ($eventDetails['location_id']) {
									$values['zenario_ctype_event__when_and_where/at_physical_location'] = 'location_picker';
									$values['zenario_ctype_event__when_and_where/at_physical_location_original'] = 'location_picker';
								} elseif ($eventDetails['location']) {
									$values['zenario_ctype_event__when_and_where/at_physical_location_original'] = 'address_text';
								}
							}
						}
						
						if ($values['zenario_ctype_event__when_and_where/start_date']) {
							$fields['tabs']['zenario_ctype_event__when_and_where/start_date']['last_value'] = $values['zenario_ctype_event__when_and_where/start_date'];
						}
	
						if ($values['zenario_ctype_event__when_and_where/start_time_hours']) {
							$fields['tabs']['zenario_ctype_event__when_and_where/start_time_hours']['last_value'] = $values['zenario_ctype_event__when_and_where/start_time_hours'];
						}
	
						if ($values['zenario_ctype_event__when_and_where/start_time_minutes']) {
							$fields['tabs']['zenario_ctype_event__when_and_where/start_time_minutes']['last_value'] = $values['zenario_ctype_event__when_and_where/start_time_minutes'];
						}
						
						if ($duplicatingOrTranslating) {
							$values['zenario_ctype_event__when_and_where/start_date_original'] = $values['zenario_ctype_event__when_and_where/start_date'];
							$values['zenario_ctype_event__when_and_where/end_date_original'] = $values['zenario_ctype_event__when_and_where/end_date'];
							$values['zenario_ctype_event__when_and_where/specify_time_original'] = $values['zenario_ctype_event__when_and_where/specify_time'];
							
							$values['zenario_ctype_event__when_and_where/start_time_original'] =
								$values['zenario_ctype_event__when_and_where/start_time_hours'] . ':' . $values['zenario_ctype_event__when_and_where/start_time_minutes'];
							
							$values['zenario_ctype_event__when_and_where/end_time_original'] =
								$values['zenario_ctype_event__when_and_where/end_time_hours'] . ':' . $values['zenario_ctype_event__when_and_where/end_time_minutes'];
							
							$values['zenario_ctype_event__when_and_where/late_evening_event_original'] = $values['zenario_ctype_event__when_and_where/late_evening_event'];
						}
					}

					if (!ze\module::isRunning('zenario_location_manager')) {
						$fields['zenario_ctype_event__when_and_where/location_id']['disabled'] = true;
						$fields['zenario_ctype_event__when_and_where/at_physical_location']['values']['location_picker']['disabled'] = true;
					}
				
					$locationField = ze::setting('zenario_ctype_event__location_field');
					$siteSettingLinkStart = "<a href='organizer.php#zenario__content/panels/content_types//event~.zenario_content_type_details~tdetails~k{\"id\"%3A\"event\"}' target='_blank'>";
					$siteSettingLinkEnd = "</a>";
				
					if ($locationField == 'hidden' || $locationField === false) {
						$fields['zenario_ctype_event__when_and_where/location']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/location_id']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/locations_snippet']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/online']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/at_location_checkbox']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/at_physical_location']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/location_original']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/location_id_original']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/locations_snippet_original']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/online_original']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/at_location_checkbox_original']['hidden'] =
						$fields['zenario_ctype_event__when_and_where/at_physical_location_original']['hidden'] = true;
					} else {
						if (!ze::setting('zenario_ctype_event__location_text')) {
							$fields['zenario_ctype_event__when_and_where/location']['disabled'] = true;
							$fields['zenario_ctype_event__when_and_where/at_physical_location']['values']['address_text']['disabled'] = true;
							$fields['zenario_ctype_event__when_and_where/at_physical_location']['value'] = 'location_picker';
						
							$fields['zenario_ctype_event__when_and_where/at_physical_location']['notices_below']['enable_address_text']['message'] = ze\admin::phrase(
								'To use this setting, enable location support (if not enabled already) and support for addresses not in the database. See settings for the [[site_setting_link_start]]Event content type[[site_setting_link_end]].',
								['site_setting_link_start' => $siteSettingLinkStart, 'site_setting_link_end' => $siteSettingLinkEnd]
							);
							$fields['zenario_ctype_event__when_and_where/at_physical_location']['notices_below']['enable_address_text']['hidden'] = false;
						}
					}
				
					$eventTimezoneSupport = ze::setting('zenario_ctype_event__timezone_support');
					
					$defaultTimezone = ze::setting('zenario_timezones__default_timezone');
					$timezones = ze\dataset::getTimezonesLOV();
					ze\lang::applyMergeFields($fields['zenario_ctype_event__when_and_where/event_timezone']['values']['default_timezone']['label'], ['default_timezone' => $timezones[$defaultTimezone]['label']]);
					
					if (!empty($eventDetails)) {
						$values['zenario_ctype_event__when_and_where/event_timezone'] = $eventDetails['event_timezone'];
						$values['zenario_ctype_event__when_and_where/event_other_timezone'] = $eventDetails['event_other_timezone'];
						
						if ($duplicatingOrTranslating) {
							if ($values['zenario_ctype_event__when_and_where/event_timezone']) {
								if ($values['zenario_ctype_event__when_and_where/event_timezone'] == 'default_timezone') {
									$values['zenario_ctype_event__when_and_where/event_timezone_original'] ==
										$fields['zenario_ctype_event__when_and_where/event_timezone']['values']['default_timezone']['label'];
								} elseif ($values['zenario_ctype_event__when_and_where/event_timezone'] == 'other_timezone') {
									$timezone = $values['zenario_ctype_event__when_and_where/event_other_timezone'];
									$timezoneLabel = $timezones[$timezone]['label'];
									$values['zenario_ctype_event__when_and_where/event_timezone_original'] = $timezoneLabel;
								}
							}
						}
					}
					
					$fields['zenario_ctype_event__when_and_where/event_other_timezone']['values'] = $timezones;
					
					if (!$eventTimezoneSupport) {
						$fields['zenario_ctype_event__when_and_where/event_timezone']['disabled'] = $fields['zenario_ctype_event__when_and_where/event_other_timezone']['disabled'] = true;
					
						$fields['zenario_ctype_event__when_and_where/event_timezone']['notices_below']['enable_timezone_support']['message'] = ze\admin::phrase(
							'To use this setting, enable timezone support. See settings for the [[site_setting_link_start]]Event content type[[site_setting_link_end]].',
							['site_setting_link_start' => $siteSettingLinkStart, 'site_setting_link_end' => $siteSettingLinkEnd]
						);
						$fields['zenario_ctype_event__when_and_where/event_timezone']['notices_below']['enable_timezone_support']['hidden'] = false;
					
						unset($fields['zenario_ctype_event__when_and_where/event_other_timezone']['validation']);
					}
				}
				
				if ($box['key']['cType'] != 'event' || !$duplicatingOrTranslating) {
					$loopThrough = [
						'start_date_original',
						'end_date_original',
						'specify_time_original',
						'start_time_original',
						'end_time_original',
						'late_evening_event_original',
						'event_timezone_original',
						'locations_snippet_original',
						'online_original',
						'at_location_checkbox_original',
						'at_physical_location_original',
						'location_id_original',
						'location_original',
						'event_url_original',
						'zenario_conference_manager__link_to_conference_original',
						'zenario_conference_manager__conference_original',
						'zenario_conference_manager__send_email_on_event_ticket_purchase_original',
						'zenario_conference_manager__ticket_purchase_event_email_template_original',
						'zenario_conference_manager__private_event_url_original',
						
						'grouping_start_date_left',
						'grouping_end_date_left',
						'grouping_specify_time_left',
						'grouping_start_time_left',
						'grouping_end_time_left',
						'grouping_event_timezone_left',
						'grouping_event_location_left',
						'grouping_event_url_left',
						'conference_grouping_left'
					];
					
					foreach ($loopThrough as $fieldName) {
						unset($box['tabs']['zenario_ctype_event__when_and_where']['fields'][$fieldName]);
					}
				}
				
				break;
			case 'zenario_content_type_details':
				if ($box['key']['id'] == 'event') {
					
					if (ze\module::isRunning('zenario_location_manager')) {
						$runningOrNotRunning = 'running';
						$values['zenario_ctype_event__location_picker'] = true;
					} else {
						$runningOrNotRunning = 'not running';
						$values['zenario_ctype_event__location_picker'] = false;
					}

					ze\lang::applyMergeFields($fields['zenario_ctype_event__location_picker']['label'], ['running_or_not_running' => $runningOrNotRunning]);

					$moduleLink = "<a href='organizer.php#zenario__library/panels/modules_running_and_suspended/collection_buttons/view_all_modules////~-Location%20Manager' target='_blank'>Modules panel</a>";
					
					$fields['zenario_ctype_event__location_picker']['side_note'] = ze\admin::phrase(
						'You can manage the Location Manager module on the [[modules_panel_link]].',
						['modules_panel_link' => $moduleLink]
					);

					$locationField = ze::setting('zenario_ctype_event__location_field');
					$values['zenario_ctype_event__location_field'] = ($locationField !== false && $locationField != 'hidden');
					$values['zenario_ctype_event__location_text'] = ze::setting('zenario_ctype_event__location_text');
					$values['zenario_ctype_event__timezone_support'] = ze::setting('zenario_ctype_event__timezone_support');
				}
				break;
			case 'plugin_settings':
				$siteSettingLinkStart = "<a href='organizer.php#zenario__content/panels/content_types//event~.zenario_content_type_details~tdetails~k{\"id\"%3A\"event\"}' target='_blank'>";
				$siteSettingLinkEnd = "</a>";

				$locationFieldSetting = ze::setting('zenario_ctype_event__location_field');
				$locationTextSetting = ze::setting('zenario_ctype_event__location_text');
				
				$disabledPhraseOnlineOption = ze\admin::phrase(
					'To use this setting, enable location support. See settings for the [[site_setting_link_start]]Event content type[[site_setting_link_end]].',
					['site_setting_link_start' => $siteSettingLinkStart, 'site_setting_link_end' => $siteSettingLinkEnd]
				);
				
				if ($locationFieldSetting === false || $locationFieldSetting == 'hidden') {
					$disabledPhrasePhysicalLocation = ze\admin::phrase(
						'To use this setting, enable location support and choose at least one of the available address options. See settings for the [[site_setting_link_start]]Event content type[[site_setting_link_end]].',
						['site_setting_link_start' => $siteSettingLinkStart, 'site_setting_link_end' => $siteSettingLinkEnd]
					);
					
					$fields['first_tab/show_online_when_event_is_online']['disabled'] =
					$fields['first_tab/online_text']['disabled'] =
					$fields['first_tab/show_address']['disabled'] = true;
					$fields['first_tab/show_address']['note_below'] = $disabledPhrasePhysicalLocation;

					$values['first_tab/show_online_when_event_is_online'] =
					$values['first_tab/show_address'] = false;
					
					$disabledPhrase = ze\admin::phrase(
						'To use this setting, enable location support. See settings for the [[site_setting_link_start]]Event content type[[site_setting_link_end]].',
						['site_setting_link_start' => $siteSettingLinkStart, 'site_setting_link_end' => $siteSettingLinkEnd]
					);

					$fields['first_tab/show_online_when_event_is_online']['note_below'] =
					$fields['first_tab/online_text']['note_below'] = $disabledPhraseOnlineOption;					
				} else {
					if (!$locationTextSetting && !ze\module::isRunning('zenario_location_manager')) {
						$disabledPhrasePhysicalLocation = ze\admin::phrase(
							'To use this setting, choose at least one of the available address options. See settings for the [[site_setting_link_start]]Event content type[[site_setting_link_end]].',
							['site_setting_link_start' => $siteSettingLinkStart, 'site_setting_link_end' => $siteSettingLinkEnd]
						);
						
						$fields['first_tab/show_address']['disabled'] = true;
						$values['first_tab/show_address'] = false;
						$fields['first_tab/show_address']['note_below'] = $disabledPhrasePhysicalLocation;
					}
				}
				
				$allowPinnedContent = ze\row::get('content_types', 'allow_pinned_content', ['content_type_id' => 'event']);
				if (!$allowPinnedContent) {
					$fields['first_tab/pinned_events_icon']['disabled'] =
					$fields['first_tab/pinned_events_text']['disabled'] =
					$fields['first_tab/pinned_events_text_wording']['disabled'] =
					$fields['first_tab/pinned_events_text_html_tag']['disabled'] = true;
					
					$values['first_tab/pinned_events_icon'] = $values['first_tab/pinned_events_text'] = 'do_not_show';
					
					$fields['first_tab/pinned_events_icon']['note_below'] = $fields['first_tab/pinned_events_text']['note_below'] =
						ze\admin::phrase('To use this feature, allow content items to be pinned. See settings for the [[site_setting_link_start]]Event content type[[site_setting_link_end]].',
						['site_setting_link_start' => $siteSettingLinkStart, 'site_setting_link_end' => $siteSettingLinkEnd]
					);
				}
				
				break;
		}
	}
	
	public function formatAdminBox($path, $settingGroup, &$box, &$fields, &$values, $changes) {
		switch ($path) {
			case 'zenario_content':
				if ($box['key']['cType'] == 'event') {				
					$fields['meta_data/release_date']['hidden'] = true;
					
					if ($values['zenario_ctype_event__when_and_where/specify_time']) {
						$hideTimes = false;
					} else {
						$hideTimes = true;
					}

					$fields['zenario_ctype_event__when_and_where/start_time_hours']['hidden'] = $hideTimes;
					$fields['zenario_ctype_event__when_and_where/start_time_minutes']['hidden'] = $hideTimes;
					$fields['zenario_ctype_event__when_and_where/end_time_hours']['hidden'] = $hideTimes;
					$fields['zenario_ctype_event__when_and_where/end_time_minutes']['hidden'] = $hideTimes;
					$fields['zenario_ctype_event__when_and_where/late_evening_event']['hidden'] = $hideTimes;
				}

				if (!$box['key']['id'] && $values['zenario_ctype_event__when_and_where/start_date'] && ($values['zenario_ctype_event__when_and_where/start_date'] != $fields['zenario_ctype_event__when_and_where/start_date']['last_value'])) {
					$fields['zenario_ctype_event__when_and_where/end_date']['current_value'] = $values['zenario_ctype_event__when_and_where/start_date'];				
				}

				if ($values['zenario_ctype_event__when_and_where/start_date'] != $fields['zenario_ctype_event__when_and_where/start_date']['last_value']) {
					$fields['zenario_ctype_event__when_and_where/start_date']['last_value'] = $values['zenario_ctype_event__when_and_where/start_date'];
				}

				// Logic for auto-adjusting the end time to the start time:
				// 1) If the start time has been set, but the end time has not, set it to the start time.
				// 2) If the start time and end time have been set, but the start datetime is greater than end datetime,
				// and the event does not go past midnight, then change the end time to the start time.
				if ($box['key']['cType'] == 'event') {
					if (!$hideTimes && ($values['zenario_ctype_event__when_and_where/start_time_hours'] || $values['zenario_ctype_event__when_and_where/start_time_minutes'])) {
						if (
							(!(int) $values['zenario_ctype_event__when_and_where/end_time_hours'] && !(int) $values['zenario_ctype_event__when_and_where/end_time_minutes'])
							|| (
								(
									$fields['zenario_ctype_event__when_and_where/start_time_hours']['last_value'] != $values['zenario_ctype_event__when_and_where/start_time_hours']
									|| $fields['zenario_ctype_event__when_and_where/start_time_minutes']['last_value'] != $values['zenario_ctype_event__when_and_where/start_time_minutes']
								)
								&& strtotime($values['zenario_ctype_event__when_and_where/start_date'] . ' ' . $values['zenario_ctype_event__when_and_where/start_time_hours'] . ':' . $values['zenario_ctype_event__when_and_where/start_time_minutes']) >
								strtotime($values['zenario_ctype_event__when_and_where/end_date'] . ' ' . $values['zenario_ctype_event__when_and_where/end_time_hours'] . ':' . $values['zenario_ctype_event__when_and_where/end_time_minutes'])
								&& !$values['zenario_ctype_event__when_and_where/late_evening_event']
							)
						) {
							$values['zenario_ctype_event__when_and_where/end_time_hours'] = $values['zenario_ctype_event__when_and_where/start_time_hours'];
							$values['zenario_ctype_event__when_and_where/end_time_minutes'] = $values['zenario_ctype_event__when_and_where/start_time_minutes'];
						}
					}

					if ($values['zenario_ctype_event__when_and_where/start_time_hours'] != $fields['zenario_ctype_event__when_and_where/start_time_hours']['last_value']) {
						$fields['zenario_ctype_event__when_and_where/start_time_hours']['last_value'] = $values['zenario_ctype_event__when_and_where/start_time_hours'];
					}

					if ($values['zenario_ctype_event__when_and_where/start_time_minutes'] != $fields['zenario_ctype_event__when_and_where/start_time_minutes']['last_value']) {
						$fields['zenario_ctype_event__when_and_where/start_time_minutes']['last_value'] = $values['zenario_ctype_event__when_and_where/start_time_minutes'];
					}
				}
				break;
		}
	}
	
	public function validateAdminBox($path, $settingGroup, &$box, &$fields, &$values, $changes, $saving) {
		switch ($path) {
			case 'zenario_content':
				if ($box['key']['cType'] == 'event') {
					if ($saving) {
						if (!$values['zenario_ctype_event__when_and_where/start_date']) {
							$box['tabs']['zenario_ctype_event__when_and_where']['errors']['incomplete_dates'] = ze\admin::phrase("Please enter start and end dates for the event. (For a single-day event make them the same.)");
						}

						if ($values['zenario_ctype_event__when_and_where/start_date']) {
							$start_time_hours = $values['zenario_ctype_event__when_and_where/start_time_hours'] ?: '00';
							$start_time_minutes = $values['zenario_ctype_event__when_and_where/start_time_minutes'] ?: '00';
							$end_time_hours = $values['zenario_ctype_event__when_and_where/end_time_hours'] ?: '00';
							$end_time_minutes = $values['zenario_ctype_event__when_and_where/end_time_minutes'] ?: '00';

							if ($values['zenario_ctype_event__when_and_where/start_date'] && !$values['zenario_ctype_event__when_and_where/end_date']) {
								$box['tabs']['zenario_ctype_event__when_and_where']['errors']['incomplete_dates'] = ze\admin::phrase("Please enter start and end dates for the event. (For a single-day event make them the same.)");
							} elseif ($values['zenario_ctype_event__when_and_where/end_date'] && $values['zenario_ctype_event__when_and_where/end_date'] < $values['zenario_ctype_event__when_and_where/start_date']) {
								$fields['zenario_ctype_event__when_and_where/end_date']['error'] = ze\admin::phrase('The end date cannot be before the start date!');
							}
						} else {
							$start_time_hours =
							$start_time_minutes =
							$end_time_hours =
							$end_time_minutes = '00';
						}
	
						if ((($start_time_hours * 100 + $start_time_minutes) 
									> ($end_time_hours * 100 + $end_time_minutes)
							) && (!$values['zenario_ctype_event__when_and_where/late_evening_event'])) {
	
							$box['tabs']['zenario_ctype_event__when_and_where']['errors']['incorrect_time'] = ze\admin::phrase('Check the end time. It looks like the event ends before it starts! Set the "+1 day" flag if it runs past midnight.');
						}							
					}
				}
				break;
		}
	}
	
	public function saveAdminBox($path, $settingGroup, &$box, &$fields, &$values, $changes) {
		switch ($path) {
			case 'zenario_content':
				if ($box['key']['cType'] == 'event') {
					$url = $values['zenario_ctype_event__when_and_where/url'];
					if ($url == 'http://') {
						$url = null;
					}
					
					if ($values['zenario_ctype_event__when_and_where/start_date']) {
						$start_time_hours = $values['zenario_ctype_event__when_and_where/start_time_hours'] ?: '00';
						$start_time_minutes = $values['zenario_ctype_event__when_and_where/start_time_minutes'] ?: '00';
						$end_time_hours = $values['zenario_ctype_event__when_and_where/end_time_hours'] ?: '00';
						$end_time_minutes = $values['zenario_ctype_event__when_and_where/end_time_minutes'] ?: '00';
					} else {
						$start_time_hours =
						$start_time_minutes =
						$end_time_hours =
						$end_time_minutes = '00';
					}
					
					$details = [
						"id" => $box['key']['cID'],
						"version" => $box['key']['cVersion'],
						"version" => $box['key']['cVersion'],
						"start_date" => $values['zenario_ctype_event__when_and_where/start_date'],
						"start_time" => (
										(($start_time_hours ?? false) 
											&& ($start_time_minutes ?? false)
												&& ($values['zenario_ctype_event__when_and_where/specify_time'] ?? false))?
										($start_time_hours . ":" . $start_time_minutes): 
										null
										),
						"end_date" => $values['zenario_ctype_event__when_and_where/end_date'],
						"end_time" => (
										(($end_time_hours ?? false) 
											&& ($end_time_minutes ?? false) 
												&& ($values['zenario_ctype_event__when_and_where/specify_time'] ?? false))?
										($end_time_hours . ":" . $end_time_minutes): 
										null
									),
						"specify_time" => ze\ring::engToBoolean($values['zenario_ctype_event__when_and_where/specify_time']),
						"next_day_finish" => ze\ring::engToBoolean($values['zenario_ctype_event__when_and_where/late_evening_event']) && ($values['zenario_ctype_event__when_and_where/specify_time'] ?? false),
						"url" => $url
					];

					$details['location'] = $details['location_id'] = '';
					$details['event_timezone'] = 'default_timezone';
					$details['event_other_timezone'] = null;
					$details['online'] = 0;

					if (ze::setting('zenario_ctype_event__location_field') != 'hidden') {
						if ($values['zenario_ctype_event__when_and_where/at_location_checkbox']) {
							if (ze::setting('zenario_ctype_event__location_text') && $values['zenario_ctype_event__when_and_where/at_physical_location'] == 'address_text') {
								$details['location'] = $values['zenario_ctype_event__when_and_where/location'];
							} elseif ($values['zenario_ctype_event__when_and_where/at_physical_location'] == 'location_picker') {
								$details['location_id'] = $values['zenario_ctype_event__when_and_where/location_id'];
							}
						}

						$details['online'] = $values['zenario_ctype_event__when_and_where/online'];
					}
					
					$eventTimezoneSupport = ze::setting('zenario_ctype_event__timezone_support');
					if ($eventTimezoneSupport) {
						$details['event_timezone'] = $values['zenario_ctype_event__when_and_where/event_timezone'];
						
						if ($values['zenario_ctype_event__when_and_where/event_timezone'] == 'other_timezone') {
							$details['event_other_timezone'] = $values['zenario_ctype_event__when_and_where/event_other_timezone'];
						}
					}
					
					ze\row::set(ZENARIO_CTYPE_EVENT_PREFIX . "content_event", $details, ["id" => $box['key']['cID'], "version" => $box['key']['cVersion']]);
				}
				break;
			case 'zenario_content_type_details':
				if ($box['key']['id'] == 'event') {
					ze\site::setSetting('zenario_ctype_event__location_field', $values['zenario_ctype_event__location_field'] ? 'optional' : 'hidden');
					ze\site::setSetting('zenario_ctype_event__location_text', $values['zenario_ctype_event__location_text']);
					ze\site::setSetting('zenario_ctype_event__timezone_support', $values['zenario_ctype_event__timezone_support']);
				}
				break;
		}
	}
	
	public function preFillOrganizerPanel($path, &$panel, $refinerName, $refinerId, $mode) {
		switch ($path) {
			case 'zenario__content/panels/content':
			case 'zenario__content/panels/chained':
				//...
				
				break;
		}
	}

	public static function getEventDetails ($id, $version) {
		return ze\row::get(
			ZENARIO_CTYPE_EVENT_PREFIX . "content_event",
			[
				"id",
				"version",
				"start_date",
				"start_time",
				"end_date",
				"end_time",
				"specify_time",
				"next_day_finish",
				"day_sun_on",
				"day_sun_start_time",
				"day_sun_end_time",
				"day_mon_on",
				"day_mon_start_time",
				"day_mon_end_time",
				"day_tue_on",
				"day_tue_start_time",
				"day_tue_end_time",
				"day_wed_on",
				"day_wed_start_time",
				"day_wed_end_time",
				"day_thu_on",
				"day_thu_start_time",
				"day_thu_end_time",
				"day_fri_on",
				"day_fri_start_time",
				"day_fri_end_time",
				"day_sat_on",
				"day_sat_start_time",
				"day_sat_end_time",
				"location_id",
				"location",
				"url",
				"stop_dates",
				"online",
				"event_timezone",
				"event_other_timezone"
			],
			[
				"id" => $id,
				"version" => $version
			]
		);
	}	

	public static function eventDraftCreated($cIDTo, $cIDFrom, $cTypeTo, $cVersionTo, $cVersionFrom, $cTypeFrom) {
		if ($cTypeFrom == 'event' && $cTypeTo == 'event') {
			$sql = "
				INSERT INTO " . DB_PREFIX . ZENARIO_CTYPE_EVENT_PREFIX . "content_event
				SELECT " . (int) $cIDTo . " AS id,
					" . (int) $cVersionTo . " AS version,
					start_date,
					start_time,
					end_date,
					end_time,
					specify_time,
					next_day_finish,
					day_sun_on,
					day_sun_start_time,
					day_sun_end_time,
					day_mon_on,
					day_mon_start_time,
					day_mon_end_time,
					day_tue_on,
					day_tue_start_time,
					day_tue_end_time,
					day_wed_on,
					day_wed_start_time,
					day_wed_end_time,
					day_thu_on,
					day_thu_start_time,
					day_thu_end_time,
					day_fri_on,
					day_fri_start_time,
					day_fri_end_time,
					day_sat_on,
					day_sat_start_time,
					day_sat_end_time,
					location_id,
					location,
					url,
					stop_dates,
					online,
					event_timezone,
					event_other_timezone
				FROM " . DB_PREFIX . ZENARIO_CTYPE_EVENT_PREFIX . "content_event
				WHERE id = " . (int) $cIDFrom . "
					AND version = " . (int) $cVersionFrom;
			$result = ze\sql::update($sql);
		}
	}
	
	public static function eventContentDeleted($cID,$cType,$cVersion) {
		$sql = "
			DELETE FROM " . DB_PREFIX . ZENARIO_CTYPE_EVENT_PREFIX . "content_event
			WHERE id = " . (int) $cID . "
				AND version = " . (int) $cVersion;
				
		$result = ze\sql::update($sql);
	}
	
	public function fillOrganizerPanel($path, &$panel, $refinerName, $refinerId, $mode) {
		if (ze::get('refiner__content_type') != 'event') {
			if ($path == 'zenario__content/panels/trashed_content_items' || $path == 'zenario__content/panels/hidden_content_items') {
				if ($panel['columns']['zenario_ctype_event__start_date'] ?? false) {
					$panel['columns']['zenario_ctype_event__start_date']['show_by_default'] = false;
				}
	
				if ($panel['columns']['zenario_ctype_event__end_date'] ?? false) {
					$panel['columns']['zenario_ctype_event__end_date']['show_by_default'] = false;
				}
			} else {
				if ($panel['columns']['zenario_ctype_event__start_date'] ?? false) {
					unset($panel['columns']['zenario_ctype_event__start_date']);
				}
	
				if ($panel['columns']['zenario_ctype_event__start_time'] ?? false) {
					unset($panel['columns']['zenario_ctype_event__start_time']);
				}
	
				if ($panel['columns']['zenario_ctype_event__end_date'] ?? false) {
					unset($panel['columns']['zenario_ctype_event__end_date']);
				}
	
				if ($panel['columns']['zenario_ctype_event__end_time'] ?? false) {
					unset($panel['columns']['zenario_ctype_event__end_time']);
				}
			}
		}
	}
}
