<?php
/**
 * @package   DPCalendar
 * @copyright Copyright (C) 2018 Digital Peak GmbH. <https://www.digital-peak.com>
 * @license   https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
 */

\defined('_JEXEC') or die();

use DigitalPeak\Component\DPCalendar\Administrator\Helper\DPCalendarHelper;
use DigitalPeak\Component\DPCalendar\Administrator\Router\Router;;
use Joomla\Utilities\ArrayHelper;

$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_ALL_DAY');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_MONTH');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_WEEK');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_DAY');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_LIST');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_UNTIL');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_PAST');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_TODAY');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_TOMORROW');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_THIS_WEEK');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_NEXT_WEEK');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_THIS_MONTH');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_NEXT_MONTH');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_FUTURE');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_WEEK');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_VIEW_TEXTS_MORE');

$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_TOOLBAR_NEXT');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_TOOLBAR_PREVIOUS');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_TOOLBAR_TODAY');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_SHOW_DATEPICKER');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_TOOLBAR_PRINT');
$translator->translateJS('COM_DPCALENDAR_VIEW_CALENDAR_TOOLBAR_ADD');

$translator->translateJS('JCANCEL');
$translator->translateJS('COM_DPCALENDAR_CLOSE');
$translator->translateJS('COM_DPCALENDAR_PREVIOUS');
$translator->translateJS('COM_DPCALENDAR_NEXT');
$translator->translateJS('COM_DPCALENDAR_FIELD_CAPACITY_UNLIMITED');

$document->addScriptOptions('calendar.names', $dateHelper->getNames());
$document->addScriptOptions('timezone', $dateHelper->getDate()->getTimezone()->getName());
$document->addScriptOptions('itemid', $app->getInput()->getInt('Itemid', 0));

// The options which will be passed to the js library
$options                   = [];
$options['requestUrlRoot'] = 'view=events&limit=0&format=raw&module_id=' . $module->id . '&Itemid=' . $app->getInput()->getInt('Itemid', 0);
$options['calendarIds']    = [implode(',', $ids)];

// Set the default view
$options['initialView'] = $params->get('default_view', 'month');

// Some general calendar options
$options['weekNumbers']    = (bool)$params->get('week_numbers');
$options['weekends']       = (bool)$params->get('weekend', 1);
$options['fixedWeekCount'] = (bool)$params->get('fixed_week_count', 1);

$bd = $params->get('business_hours_days', []);
if ($bd && !(is_countable($bd) ? count($bd) : 0 === 1 && !$bd[0])) {
	$options['businessHours'] = [
		'startTime'  => $params->get('business_hours_start', ''),
		'endTime'    => $params->get('business_hours_end', ''),
		'daysOfWeek' => $params->get('business_hours_days', [])
	];
}

$options['firstDay']              = (int)$params->get('weekstart', 1);
$options['hiddenDays']            = ArrayHelper::toInteger($params->get('hidden_days', []));
$options['scrollTime']            = $params->get('first_hour', 6) === 'now' ? 'now' : $params->get('first_hour', 6) . ':00:00';
$options['weekNumberCalculation'] = 'ISO';
$options['displayEventEnd']       = true;
$options['navLinks']              = true;

$max = $params->get('max_time', 24);
if (is_numeric($max)) {
	$max .= ':00:00';
}
$options['slotMaxTime'] = $max;

$min = $params->get('min_time', 0);
if (is_numeric($min)) {
	$min .= ':00:00';
}
$options['slotMinTime'] = $min;

$options['nowIndicator']     = (bool)$params->get('current_time_indicator', 1);
$options['displayEventTime'] = $params->get('compact_events', 2) != 2;

if ($params->get('event_limit', '') != '-1') {
	$options['dayMaxEventRows'] = $params->get('event_limit', '') == '' ? 2 : $params->get('event_limit', '') + 1;
}

// Set the height
if ($params->get('calendar_height', 0) > 0) {
	$options['contentHeight'] = (int)$params->get('calendar_height', 0);
} else {
	$options['height'] = 'auto';
}

$options['slotEventOverlap'] = (bool)$params->get('overlap_events', 1);

// Set up the header
$options['headerToolbar'] = ['left' => [], 'center' => [], 'right' => []];
if ($params->get('header_show_navigation', 1)) {
	$options['headerToolbar']['left'][] = 'prev';
	$options['headerToolbar']['left'][] = 'next';
}
if ($params->get('header_show_today', 0)) {
	$options['headerToolbar']['left'][] = 'today';
}
if ($params->get('header_show_datepicker', 0)) {
	$options['headerToolbar']['left'][] = 'datepicker';
}
if ($params->get('header_show_create', 1) && DPCalendarHelper::canCreateEvent()) {
	$options['headerToolbar']['left'][] = 'add';
}
if ($params->get('header_show_title', 1)) {
	$options['headerToolbar']['center'][] = 'title';
}
if ($params->get('header_show_month', 1)) {
	$options['headerToolbar']['right'][] = 'month';
}
if ($params->get('header_show_week', 1)) {
	$options['headerToolbar']['right'][] = 'week';
}
if ($params->get('header_show_day', 1)) {
	$options['headerToolbar']['right'][] = 'day';
} else {
	$options['navLinks'] = false;
}
if ($params->get('header_show_list', 1)) {
	$options['headerToolbar']['right'][] = 'list';
}

$options['headerToolbar']['left']   = implode(',', $options['headerToolbar']['left']);
$options['headerToolbar']['center'] = implode(',', $options['headerToolbar']['center']);
$options['headerToolbar']['right']  = implode(',', $options['headerToolbar']['right']);

$resourceViews = $params->get('calendar_resource_views');
if (!DPCalendarHelper::isFree() && $resourceViews && $resources) {
	$options['resources']           = $resources;
	$options['resourceViews']       = $resourceViews;
	$options['datesAboveResources'] = true;
}

// Set up the views
$options['views']          = [];
$options['views']['month'] = [
	'titleFormat'            => $dateHelper->convertPHPDateToJS($params->get('titleformat_month', 'F Y')),
	'eventTimeFormat'        => $dateHelper->convertPHPDateToJS($params->get('timeformat_month', 'H:i')),
	'dayHeaderFormat'        => $dateHelper->convertPHPDateToJS($params->get('columnformat_month', 'D'))
];
$options['views']['week']  = [
	'titleFormat'            => $dateHelper->convertPHPDateToJS($params->get('titleformat_week', 'M j Y')),
	'eventTimeFormat'        => $dateHelper->convertPHPDateToJS($params->get('timeformat_week', 'H:i')),
	'dayHeaderFormat'        => $dateHelper->convertPHPDateToJS($params->get('columnformat_week', 'D n/j')),
	'slotDuration'           => $dateHelper->minutesToDuration((int)$params->get('agenda_slot_minutes', 30)),
	'slotLabelInterval'      => $dateHelper->minutesToDuration((int)$params->get('agenda_slot_minutes', 30)),
	'slotLabelFormat'        => $dateHelper->convertPHPDateToJS($params->get('axisformat_week', 'H:i'))
];
$options['views']['day']   = [
	'titleFormat'            => $dateHelper->convertPHPDateToJS($params->get('titleformat_day', 'F j Y')),
	'eventTimeFormat'        => $dateHelper->convertPHPDateToJS($params->get('timeformat_day', 'H:i')),
	'dayHeaderFormat'        => $dateHelper->convertPHPDateToJS($params->get('columnformat_day', 'l')),
	'slotDuration'           => $dateHelper->minutesToDuration((int)$params->get('agenda_slot_minutes', 30)),
	'slotLabelInterval'      => $dateHelper->minutesToDuration((int)$params->get('agenda_slot_minutes', 30)),
	'slotLabelFormat'        => $dateHelper->convertPHPDateToJS($params->get('axisformat_day', 'H:i'))
];
$options['views']['list']  = [
	'titleFormat'       => $dateHelper->convertPHPDateToJS($params->get('titleformat_list', 'M j Y')),
	'eventTimeFormat'   => $dateHelper->convertPHPDateToJS($params->get('timeformat_list', 'H:i')),
	'dayHeaderFormat'   => $dateHelper->convertPHPDateToJS($params->get('columnformat_list', 'D')),
	'listDayFormat'     => $dateHelper->convertPHPDateToJS($params->get('dayformat_list', 'l')),
	'listDaySideFormat' => $dateHelper->convertPHPDateToJS($params->get('dateformat_list', 'F j, Y')),
	'duration'          => ['days' => (int)$params->get('list_range', 30)],
	'noEventsContent'   => $translator->translate('COM_DPCALENDAR_ERROR_EVENT_NOT_FOUND', true)
];

// Some DPCalendar specific options
$options['show_event_as_popup']   = $params->get('show_event_as_popup');
$options['popupWidth']            = $params->get('popup_width');
$options['popupHeight']           = $params->get('popup_height');
$options['show_event_tooltip']    = $params->get('show_event_tooltip', 1);
$options['show_map']              = $params->get('show_map', 1);
$options['event_create_form']     = (int)$params->get('event_create_form', 1);
$options['screen_size_list_view'] = $params->get('screen_size_list_view', 500);
$options['use_hash']              = false;
if (DPCalendarHelper::canCreateEvent()) {
	$router                      = new Router();
	$input                       = $app->getInput();
	$returnPage                  = $input->getInt('Itemid', 0) ? 'index.php?Itemid=' . $input->getInt('Itemid', 0) : null;
	$options['event_create_url'] = $router->getEventFormRoute('0', $returnPage, null, false);
}

// Set the actual date
$now              = DPCalendarHelper::getDate($params->get('start_date'));
$options['year']  = $now->format('Y', true);
$options['month'] = $now->format('m', true);
$options['date']  = $now->format('d', true);

$document->addScriptOptions('module.mini.' . $module->id . '.options', $options);
