<?php 

/**
 * Time Functions
 */

if( ! defined( 'ABSPATH' ) ) {
	return;
}

/**
 * Returns the ABBR for a given timezone.
 * If the timezone is an offset (exp. -1.5, 2.4 ) we are getting the Name of that timezone exp. (America/Los Angeles, Europe/Zagreb)
 * @param  string $offset
 * @return string           Abbreviation of the given timezone
 */
function giveasap_get_timezone_short( $offset = null ) {

	$timezone = false;

	if( null === $offset ) {
		$offset = get_option( 'gmt_offset' );
	}

	if ( 0 == $offset ) {
		return 'UTC';
	}

	$city = get_option( 'timezone_string' );

	if ( $city ) {
		return $city;
	}

	$seconds = $offset * 60 * 60;

	$abb_array = timezone_abbreviations_list();
 
	foreach ( $abb_array as $abbr ) {
		foreach ( $abbr as $city ) {
			if ( $city['offset'] == $seconds ) {
				$timezone = $city['timezone_id'];
			}
		}
	}


	if( ! $timezone ) {
		return false;
	}

	$dateTime = new DateTime();

	$dateTime->setTimeZone( new DateTimeZone( $timezone ) );

	return $dateTime->format('T'); 
}

/**
 * Get the calculated End Time for the Giveaway
 * @param  integer $post_id 
 * @return mixed           
 */
function giveasap_get_end_time( $post_id = 0 ) {
	if( ! $post_id ) {
		global $post;
		$post_id = $post->ID;
	}

	$end_time = get_post_meta( $post_id, 'end_time', true );

	// Backward compatible where giveasap meta was used instead of post meta
	if( ! $end_time ) {
		$end_time = giveasap_get_meta( $post_id, 'end_time', true );
	}
	 
	return $end_time;
}

/**
 * Echo the Formatted Datetime
 * @param  integer  $timestamp Timestamp of the date & time
 * @param  boolean $timezone  Timezone. If true, show it next to the date
 * @return string             
 */
function giveasap_the_formatted_datetime( $timestamp, $timezone = true ) {
	echo giveasap_get_formatted_datetime( $timestamp, $timezone );
}

/**
 * Get the Formatted Datetime
 * @param  integer $timestamp Timestamp of the date & time
 * @param  boolean $timezone  Timezone. If true, show it next to the date
 * @return string             
 */
function giveasap_get_formatted_datetime( $timestamp, $timezone = true ) {
	$format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' );

	if( $timezone ) {
		$format .= ' T';
	}

	$string = date_i18n( $format, $timestamp );

	if ( false !== strpos( $string, 'UTC' ) ) {
		$offset = get_option('gmt_offset');

		if ( $offset ) {
			$minutes = floatval( $offset ) * 60;
			if ( $minutes < 0 ) {
				$minutes = $minutes * (-1);
				$string .= '-';
			} else {
				$string .= '+';
			}
			$string .= date_i18n('H:i', mktime(0, $minutes ) );
		}
	}

	return $string;
}