<?php
/**
 * Configuration management class.
 *
 * @package EventimUSEventListings
 */

defined( 'ABSPATH' ) || exit;

/**
 * Main configuration class for plugin settings.
 */
class EvuselConfig {

	/**
	 * Option name for storing settings.
	 *
	 * @var string
	 */
	private $optionName = 'evusel-options';

	/** Calendar view shortcode name. */
	const SHORTCODE_CALENDAR_VIEW = 'seecalendarview';

	/** List view shortcode name. */
	const SHORTCODE_LIST_VIEW = 'seelistview';

	/** Category filter shortcode name. */
	const SHORTCODE_CATEGORY_FILTER = 'seecategoryfilter';

	/** Tag filter shortcode name. */
	const SHORTCODE_TAG_FILTER = 'seetagfilter';

	/** Slider shortcode name. */
	const SHORTCODE_SLIDER = 'seeslider';

	/** Event search shortcode name. */
	const SHORTCODE_EVENT_SEARCH = 'eventsearch';

	/** Event search results shortcode name. */
	const SHORTCODE_EVENT_SEARCH_RESULTS = 'eventsearch-results';

	/** Just announced events shortcode name. */
	const SHORTCODE_JUST_ANNOUNCED_EVENTS = 'justannouncedevents';

	/** Past events shortcode name. */
	const SHORTCODE_PAST_EVENTS = 'pastevents';

	/** Nonce code for security. */
	const NONCE_CODE = 'eventim-us-settings';

	/** Cron interval options. */
	const CRON_INTERVALS = array(
		'1'  => 'every_minute',
		'15' => 'every_fifteen_minutes',
	);

	/** Cron interval seconds. */
	const CRON_INTERVAL_SECS = array(
		'1'  => '60',
		'15' => '60',
	);

	/** Cron trigger endpoint. */
	const CRON_TRIGGER_ENDPOINT = 'run-cron';

	/** API endpoint namespace. */
	const API_ENDPOINT_NAMESPACE = 'evusel';



	/**
	 * ACF JSON path.
	 *
	 * @var string
	 */
	public static $ACFJsonPath = EVUSEL_PLUGIN_DIR . 'acf-fields';

	/**
	 * Options array.
	 *
	 * @var array
	 */
	private $options;

	/**
	 * Constructor.
	 *
	 * @return void
	 */
	public function __construct() {
		$this->options = get_option( $this->optionName, array() );

		if ( empty( $this->options ) ) {
			$oldOptions = get_option( 'seetickets-options', array() );
			if ( ! empty( $oldOptions ) ) {
				$this->options = $oldOptions;
				update_option( $this->optionName, $this->options );
				delete_option( 'seetickets-options' );
			}
		}
	}

	/**
	 * Returns default settings
	 *
	 * @since 0.4.0
	 * @return array
	 */
	private function getDefaultOptions() {
		$restEndpointPrefix = get_option( 'permalink_structure' ) ? '/wp-json/' : '?rest_route=/';

		return array(
			'api'                            => array(
				'url'                => 'https://prod-seetickets-core.seeticketsusa.us/api/v2/client/{clientId}/event?pastHours=2160',
				'api_exclude_list'   => array(),
				'client_credentials' => array(),
				'cron_endpoint'      => get_site_url() . $restEndpointPrefix . self::API_ENDPOINT_NAMESPACE . '/' . self::CRON_TRIGGER_ENDPOINT,
			),
			'shortcodes'                     => array(
				'calendar_view'   => array(
					'first_day_of_week'   => 's',
					'number_of_months'    => 12,
					'show_empty_months'   => 'on',
					'material_list_style' => 'outlined',
					'show_venue_name'     => 'off',
				),
				'list_view'       => array(
					'view_type'           => 'l',
					'per_page'            => 3,
					'column_amount'       => 2,
					'max_columns'         => 4,
					'material_list_style' => 'outlined',
					'navigation_for_grid' => 'pagination',
					'navigation_for_list' => 'loadmore',
				),
				'event_search'    => array(
					'search_parameters'   => array(),
					'material_list_style' => 'outlined',
				),
				'past_events'     => array(
					'per_page'            => 5,
					'max_events'          => 20,
					'material_list_style' => 'outlined',
					'past_event_if'       => 'eventdatepassed',
				),
				'slider'          => array(
					'layout'       => 'full_width',
					'navigation'   => 'circles',
					'no_of_slides' => '5',
				),
				'category_filter' => array(
					'view_type'           => 'l',
					'selected_categories' => array(),
					'material_list_style' => 'outlined',
				),
				'tag_filter'      => array(
					'view_type'           => 'l',
					'selected_tags'       => array(),
					'material_list_style' => 'outlined',
				),
				'just_announced'  => array(
					'no_to_display'       => 5,
					'material_list_style' => 'outlined',
					'selected_tags'       => array(),
				),
			),
			'color_theme'                    => array(
				'button_background_color' => '#212429',
				'background_color'        => '#F8F9FA',
				'text_color'              => '#212429',
				'button_text_color'       => '#FFFFFF',
				'button_text_hover_color' => '#A2B1BF',
			),
			'import'                         => array(
				'scheduled_import_interval' => '15',
			),
			'default_event_status'           => 'publish',
			'default_event_image'            => plugins_url( '../images/placeholder.jpg', __FILE__ ),
			'event_image_style'              => 'square',
			'social_icon_circles'            => 'off',
			'social_icon_background_color'   => '#ffffff',
			'social_icon_color'              => '#000000',
			'custom_labels'                  => array(
				'supporting_talent' => array(
					'label' => 'Supporting Talent:',
				),
				'door_time'         => array(
					'label' => 'Doors at',
				),
				'event_time'        => array(
					'label' => 'Event at',
				),
				'show_time'         => array(
					'label' => 'Show at',
				),
			),
			'button_status_classes'          => array(
				'gettickets'       => 'button-gettickets',
				'soldout'          => 'button-soldout',
				'notavailable'     => 'button-notavailable',
				'buytickets'       => 'button-buytickets',
				'ticketsathtedoor' => 'button-ticketsathtedoor',
				'cancelled'        => 'button-cancelled',
				'presale'          => 'button-presale',
				'free'             => 'button-free',
				'postponed'        => 'button-postponed',
				'moreinfo'         => 'button-moreinfo',
				'onsale'           => 'button-onsale',
				'hiddenOnly'       => 'button-hiddenonly',
				'comingsoon'       => 'button-comingsoon',
				'boxofficeonly'    => 'button-boxofficeonly',
			),
			'event_data_classes'             => array(
				'header'            => 'header',
				'title'             => 'title',
				'date'              => 'date',
				'headliners'        => 'headliners',
				'supporting_talent' => 'supporting-talent',
				'subtitle'          => 'subtitle',
				'doortime_showtime' => 'doortime-showtime',
				'event_time'        => 'event_time',
				'venue'             => 'venue',
				'ages'              => 'ages',
				'price'             => 'price',
				'genre'             => 'genre',
				'custom_field_1'    => 'custom-field-1',
				'custom_field_2'    => 'custom-field-2',
				'custom_field_3'    => 'custom-field-3',
			),
			'load_material_design_resources' => 'on',
			'show_repeating_events'          => false,
			'link_title_and_image_to'        => 'seepage',
			'event_card_elements_order'      => array(
				'header',
				'title',
				'event_date',
				'headliners',
				'supporting_talent',
				'subtitle',
				'doortime_showtime',
				'event_time',
				'venue',
				'ages_price',
				'genre',
				'custom_field_1',
				'custom_field_2',
				'custom_field_3',
			),
			'event_card_element_labels'      => array(
				'header'            => 'Header',
				'title'             => 'Title',
				'event_date'        => 'Event Date',
				'headliners'        => 'Headliners',
				'supporting_talent' => 'Supporting Talent',
				'subtitle'          => 'Subtitle',
				'doortime_showtime' => 'Doortime / Showtime',
				'event_time'        => 'Event Time',
				'venue'             => 'Venue',
				'ages_price'        => 'Ages / Price',
				'genre'             => 'Genre',
				'custom_field_1'    => 'Custom Field 1 (if present)',
				'custom_field_2'    => 'Custom Field 2 (if present)',
				'custom_field_3'    => 'Custom Field 3 (if present)',
			),
			'imageDimensionsPerColumn'       => array(
				2 => array(
					'gridWidth'  => 504,
					'imageWidth' => 460,
				),
				3 => array(
					'gridWidth'  => 330,
					'imageWidth' => 290,
				),
				4 => array(
					'gridWidth'  => 247,
					'imageWidth' => 220,
				),
			),
			'webp_compression_quality'       => 90,
			'debug'                          => array(
				'force_script_load' => false,
			),
		);
	}

	/**
	 * Get a specified option.
	 *
	 * @param string $key Option key.
	 * @return mixed Option value.
	 */
	public function get( $key, $getDefault = false ) {
		$keyArray = explode( '.', $key );

		if ( ! $getDefault ) {
			$option = $this->getOption( $keyArray, $this->options );
		}

		// Look for default value if not found in options
		if ( empty( $option ) ) {
			$option = $this->getOption( $keyArray, $this->getDefaultOptions() );
		}

		return $option;
	}

	/**
	 * Get a specified option key from an array.
	 *
	 * @param array $keyArray Key array.
	 * @param array $option   Option array.
	 * @return null|string Option value or null.
	 */
	private function getOption( $keyArray, $option ) {
		foreach ( $keyArray as $key ) {
			$option = isset( $option[ $key ] ) ? $option[ $key ] : null;
			if ( empty( $option ) ) {
				break;
			}
		}

		return $option;
	}

	/**
	 * Sets the options values.
	 *
	 * @param array $options Options array.
	 * @return void
	 */
	public function setOptions( $options ) {
		$this->options = $options;
	}

	/**
	 * Persist options to the DB
	 *
	 * @return void
	 */
	public function save() {
		update_option( $this->optionName, $this->options, true );
	}

	/**
	 * Return the default event image id
	 *
	 * @since 0.9.1
	 * @return void
	 */
	public function get_default_event_image_url( $size = 'large' ) {
		$defaultImageId = $this->get( 'default_event_image_id' );
		if ( ! empty( $defaultImageId ) ) {
			$defaultImageUrl = wp_get_attachment_image_url( $defaultImageId, $size, false );
			if ( ! empty( $defaultImageUrl ) ) {
				return $defaultImageUrl;
			}
		}
		return $this->get( 'default_event_image' );
	}
}

return new EvuselConfig();
