<?php

/**
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2021 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace NRFramework\Widgets;

use \NRFramework\Widgets\Helper\Countdown as CountdownHelper;

defined('_JEXEC') or die;

/**
 * Countdown
 */
class Countdown extends Widget
{
	/**
	 * Widget default options
	 *
	 * @var array
	 */
	protected $widget_options = [
		// The countdown text
		'text' => '{time}',

		/**
		 * This text appears when the countdown finishes
		 * the countdown process.
		 */
		'finish_text' => 'Countdown finished.',

		/**
		 * The countdown format.
		 * 
		 * Available tags:
		 * {years}
		 * {months}
		 * {days}
		 * {hours}
		 * {minutes}
		 * {seconds}
		 */
		'format' => '{days} days, {hours} hours, {minutes} minutes and {seconds} seconds',

		// Whether to make the countdown timer update in real-time.
		'live' => false,

		// The actual countdown timer.
		'countdown' => false
	];

	/**
	 * Class constructor
	 *
	 * @param array $options
	 */
	public function __construct($options = [])
	{
		parent::__construct($options);

		$this->prepare();
	}

	/**
	 * Prepares the countdown.
	 * 
	 * @return  void
	 */
	private function prepare()
	{
		$this->prepareStatic();
		$this->prepareLive();
	}

	/**
	 * Prepares the static countdown.
	 * 
	 * @return  void
	 */
	private function prepareStatic()
	{
		// If we are not using live countdown
		if ($this->options['live'] == false)
		{
			// Get the countdown
			$this->options['countdown'] = CountdownHelper::getCountdown($this->options['value'], $this->options['format']);

			// Replace {time} with the actual countdown.
			$this->options['text'] = str_replace('{time}', $this->options['countdown'], $this->options['text']);
		}
	}

	/**
	 * Prepares the live countdown.
	 * 
	 * @return  void
	 */
	private function prepareLive()
	{
		$datetime = $this->options['value'];
		$format = $this->options['format'];
		
		// get timezone
		$tz = new \DateTimeZone(\JFactory::getApplication()->getCfg('offset', 'UTC'));

		// get finish time
		$then = new \DateTime($datetime, $tz);
		$then = $then->format('r');

		// get current time
		$now = new \DateTime('now', $tz);
		$now = $now->format('r');

		// check if the countdown has ended
		if (strtotime($now) > strtotime($then))
		{
			// Dont use live countdown
			$this->options['live'] = false;

			// Display finish text, countdown is over
			$this->options['countdown'] = false;

			// Set text to be the finish text
			$this->options['text'] = $this->options['finish_text'];

			// Ensure the JS library does not pick this up if there are other live countdowns.
			$this->options['css_class'] .= ' done';
		}

		if (!$this->options['live'])
		{
			return;
		}
	
		// live countdown is enabled
		$this->options['countdown'] = true;
		
		// Find which tags we have in our format
		$tags = CountdownHelper::findTagsInFormat($format);
		
		// Set timezone of site to date
		$countdown_atts = [
			'data-now="' . $now . '"',
			'data-date="' . $datetime . '"',
			'data-finish-text="' . htmlspecialchars($this->options['finish_text']) . '"',
			'data-tags="' . htmlspecialchars(json_encode($tags)) . '"'
		];
		$this->options['atts'] = implode(' ', $countdown_atts);

		// prepare live format
		$this->options['format'] = CountdownHelper::livePrepareFormat($format);

		// replace the live format with {time}
		$text = str_replace("{time}", $this->options['format'], $this->options['text']);

		// replace all {tags} added with countdown numbers to prefill the countdown before starting the javascript countdown
		$this->options['text'] = CountdownHelper::getCountdown($datetime, $text);

		$this->options['css_class'] .= ' live';
	}
}