<?php

namespace EFFE_Plugin;

/**
 * The admin-specific functionality of the plugin.
 *
 * @package    Event_Feed_For_Eventbrite
 * @subpackage Event_Feed_For_Eventbrite/admin
 * @author     Bohemia Plugins <https://www.bohemiaplugins.com>
 */
class Event_Feed_For_Eventbrite_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @access   public
	 * @param    string    $plugin_name     The name of this plugin.
	 * @param    string    $version    		The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->event_feed_for_eventbrite_options = get_option( $this->plugin_name );
		$this->event_feed_for_eventbrite_options_advanced = get_option( $this->plugin_name . '-advanced' );
		$this->freemius = effe_freemius();

	}

	/**
	 * Determine if the current screen is plugin related.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function is_plugin_screen() {
		$screen = get_current_screen();
		if( isset( $screen ) && isset( $screen->id ) ) {
			if( in_array( $screen->id, array( 
				'edit-event_feed', 
				'event_feed', 
				'event_feed_page_event-feed-for-eventbrite-settings',
				'event_feed_page_event-feed-for-eventbrite-getting-started'
			) ) ) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Determine if the current screen is related to event feed post type.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function is_plugin_post_type_screen() {
		$screen = get_current_screen();
		if( isset( $screen ) && isset( $screen->post_type ) ) {
			if( $screen->post_type === 'event_feed' ) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function enqueue_styles() {

		// Load these styles only on event feed post type admin pages
		if( $this->is_plugin_post_type_screen() === true ) {
			wp_enqueue_style( $this->plugin_name . '-minicolors', plugin_dir_url( __FILE__ ) . 'libs/minicolors/jquery.minicolors.css', null, '2.3.5', 'all' );
			wp_enqueue_style( $this->plugin_name . '-choices', plugin_dir_url( __FILE__ ) . 'libs/choices/choices.min.css', null, '9.0.1', 'all' );
			wp_enqueue_style( $this->plugin_name . '-tooltipster', plugin_dir_url( __FILE__ ) . 'libs/tooltipster/tooltipster.bundle.min.css', null, '4.2.8', 'all' );
			wp_enqueue_style( $this->plugin_name . '-tooltipster-theme', plugin_dir_url( __FILE__ ) . 'libs/tooltipster/tooltipster-sideTip-borderless.min.css', null, '4.2.8', 'all' );
			wp_enqueue_style( $this->plugin_name . '-jquery-confirm', plugin_dir_url( __FILE__ ) . 'libs/jquery-confirm/jquery-confirm.min.css', null, '3.3.4', 'all' );
			wp_enqueue_style( $this->plugin_name . '-font-awesome', plugin_dir_url( __FILE__ ) . 'libs/font-awesome/css/font-awesome.min.css', null, '4.7.0', 'all' );
		}

		// Load these styles on all plugin admin pages
		if( $this->is_plugin_screen() === true ) {
			wp_enqueue_style( $this->plugin_name . '-admin', plugin_dir_url( __FILE__ ) . 'assets/css/admin.css', array( 
				$this->plugin_name . '-minicolors',
				$this->plugin_name . '-choices',
				$this->plugin_name . '-jquery-confirm'
			), $this->version, 'all' );
		}
		
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function enqueue_scripts() {

		// Load these scripts only on event feed post type admin pages
		if( $this->is_plugin_post_type_screen() === true ) {
			
			wp_enqueue_script( $this->plugin_name . '-minicolors', plugin_dir_url( __FILE__ ) . 'libs/minicolors/jquery.minicolors.min.js', array( 'jquery' ), '2.3.5', false );
			wp_enqueue_script( $this->plugin_name . '-choices', plugin_dir_url( __FILE__ ) . 'libs/choices/choices.min.js', array( 'jquery' ), '9.0.1', false );
			wp_enqueue_script( $this->plugin_name . '-tooltipster', plugin_dir_url( __FILE__ ) . 'libs/tooltipster/tooltipster.bundle.min.js', array( 'jquery' ), '4.2.8', false );
			wp_enqueue_script( $this->plugin_name . '-clipboard', plugin_dir_url( __FILE__ ) . 'libs/clipboard/clipboard.min.js', array( 'jquery' ), '2.0.8', false );
			wp_enqueue_script( $this->plugin_name . '-jquery-confirm', plugin_dir_url( __FILE__ ) . 'libs/jquery-confirm/jquery-confirm.min.js', array( 'jquery' ), '3.3.4', false );
			wp_enqueue_script( $this->plugin_name . '-jquery-are-you-sure', plugin_dir_url( __FILE__ ) . 'libs/jquery-are-you-sure/jquery.are-you-sure.js', array( 'jquery' ), '1.9.0', false );

			// Main admin script
			wp_enqueue_script( $this->plugin_name . '-admin', plugin_dir_url( __FILE__ ) . 'assets/js/admin.js', array( 
				'jquery',
				$this->plugin_name . '-minicolors',
				$this->plugin_name . '-choices',
				$this->plugin_name . '-tooltipster',
				$this->plugin_name . '-clipboard',
				$this->plugin_name . '-jquery-confirm',
				$this->plugin_name . '-jquery-are-you-sure',
			), $this->version, false );

			// Send license information to admin js
			wp_localize_script( $this->plugin_name . '-admin', 'EventFeedForEventbrite', [
				'premium' => json_encode( effe_freemius()->can_use_premium_code() ),
				'free' => json_encode( effe_freemius()->is_free_plan() )
			] );

			// Send translations to js
			wp_localize_script( $this->plugin_name . '-admin', 'EventFeedForEventbriteAdminTranslations', [
				'search_font_placeholder' => esc_html__( 'Search Font Family', 'event-feed-for-eventbrite' ),
				'copied_text' => esc_html__( 'Copied', 'event-feed-for-eventbrite' ),
				'copy_text' => esc_html__( 'Copy', 'event-feed-for-eventbrite' ),
				'pro_feature' => esc_html__( 'PRO FEATURE', 'event-feed-for-eventbrite' ),
				'pro_feature_notice' => esc_html__( "We're sorry, the", 'event-feed-for-eventbrite' ),
				'pro_feature_notice_next' => esc_html__( 'is not available on the free plan. Please upgrade to the PRO plan to unlock all these awesome features.', 'event-feed-for-eventbrite' ),
				'pro_feature_notice_title' => esc_html__( 'is a PRO Feature', 'event-feed-for-eventbrite' ),
				'pro_feature_notice_btn' => esc_html__( 'Upgrade to PRO', 'event-feed-for-eventbrite' )
			] );

		}

	}

	/**
	 * Register the JavaScript for adding Media Uploader to the admin area.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function enqueue_media_uploader() {

    	wp_enqueue_media();
    	wp_register_script( 'media-uploader', plugin_dir_url( __FILE__ ) . 'assets/js/media-uploader.js', array( 'jquery' ), $this->version, false );
    	wp_enqueue_script( 'media-uploader' );

    }

	/**
	 * Register Event Feed for Eventbrite Gutenberg block.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function register_block() {
		register_block_type( $this->plugin_name . '/block', array(
			'editor_script' => $this->plugin_name . '/block-script',
			'editor_style' => $this->plugin_name . '/block-style'
		));
	}

	/**
	 * Load Event Feed for Eventbrite Gutenberg block scripts and styles.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function enqueue_block_editor_scripts() {

		// Gutenberg block styles
		wp_register_style(
			$this->plugin_name . '/block-style',
			plugin_dir_url( __FILE__ ) . 'assets/css/block.css',
			[ 'wp-edit-blocks' ],
			$this->version
		);

		// Gutenberg block script
		wp_register_script(
			$this->plugin_name . '/block-script',
			plugin_dir_url( __FILE__ ) . 'assets/js/block.js',
			[ 'wp-i18n', 'wp-blocks', 'wp-editor', 'wp-element', 'wp-components' ]
		);

		// Send event feeds + translation to Gutenberg block
		$feed_obj = new Event_Feed_For_Eventbrite_Feed();
		wp_localize_script( $this->plugin_name . '/block-script', 'EventFeedForEventbriteBlock', [ 
			'feeds' => $feed_obj->get_event_feeds(),
			'block_name' => esc_html__( 'Event Feed for Eventbrite', 'event-feed-for-eventbrite' ),
			'block_description' => esc_html__( 'Select and display one of your Eventbrite event feeds.', 'event-feed-for-eventbrite' ),
			'select_label' => esc_html__( 'Select event feed to display:', 'event-feed-for-eventbrite' ),
			'edit_link_text' => esc_html__( 'Edit this feed', 'event-feed-for-eventbrite' )
		] );

	}

	/**
	 * Add image size for Eventbrite thumbnail.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function eventbrite_image_size() {
    	add_image_size( 'event-feed-for-eventbrite-thumbnail', 800, 400, true );
    }

	/**
	 * Add plugin settings menu as submenu to custom post type.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function add_plugin_admin_menu() {

		add_submenu_page(
			'edit.php?post_type=event_feed',
			__( 'Settings', 'event-feed-for-eventbrite' ),
			__( 'Settings', 'event-feed-for-eventbrite' ),
			'manage_options',
			$this->plugin_name . '-settings',
			array( $this, 'display_plugin_setup_page' )
		);

	}

	/**
	 * Add welcome page that is shown after plugin activation
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function add_plugin_welcome_page() {

		add_submenu_page(
			'edit.php?post_type=event_feed',
			__( 'Welcome to Event Feed for Eventbrite', 'event-feed-for-eventbrite' ),
			__( 'Welcome', 'event-feed-for-eventbrite' ),
			'manage_options',
			$this->plugin_name . '-getting-started',
			array( $this, 'display_plugin_welcome_page' )
		);

	}

	/**
	 * Remove welcome page from the admin menu.
	 *
	 * @since 1.0.0
	 * @access   public
	 */
	public function hide_plugin_welcome_page() {
		remove_submenu_page( 'edit.php?post_type=event_feed', $this->plugin_name . '-getting-started' );
	}

	/**
	 * Add settings link to plugin details on plugins page.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function add_action_links( $links ) {

	  	$settings_link = array(
			'<a href="' . esc_url( admin_url( 'edit.php?post_type=event_feed&page=' . $this->plugin_name . '-settings' ) ) . '">' . esc_html__( 'Settings', 'event-feed-for-eventbrite' ) . '</a>', 
		);
	  	return array_merge(  $settings_link, $links );
	
	}
	
	/**
	 * Includes template of plugin settings.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function display_plugin_setup_page() {

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Get the active tab from the $_GET param
		$default_tab = null;
		$tab = isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : $default_tab;

		include_once( 'partials/settings/settings.php' );
	}

	/**
	 * Includes template of plugin welcome page.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function display_plugin_welcome_page() {

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Get the active step from the $_GET param
		$default_step = null;
		$step = isset( $_GET['step'] ) ? sanitize_key( $_GET['step'] ) : $default_step;

		include_once( 'partials/settings/getting-started.php' );

	}

	/**
	 * Register plugin settings using the Settings API.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function options_update() {

		register_setting(
			$this->plugin_name,
			$this->plugin_name,
			array( $this, 'validate' )
		);

		register_setting(
			$this->plugin_name . '-appearance',
			$this->plugin_name . '-appearance',
			array( $this, 'validate_appearance' )
		);

		register_setting(
			$this->plugin_name . '-formats',
			$this->plugin_name . '-formats',
			array( $this, 'validate_formats' )
		);

		register_setting(
			$this->plugin_name . '-advanced',
			$this->plugin_name . '-advanced',
			array( $this, 'validate_advanced' )
		);

	}

	/**
	 * Validate data on General Settings page.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function validate( $input ) {

		// All inputs
		$valid = array();

		$clean_api_key = sanitize_text_field( $input['api_key'] );

		// API key validation
		$response = eventbrite()->get_user_organizations( array( 'token' => $clean_api_key ) );

		// Test API key
		if( ! is_wp_error( $response ) ) {

			$valid['api_key'] = $clean_api_key;

		} else {

			// Fallback to previous API key
			$options = get_option( $this->plugin_name );
			$valid['api_key'] = isset( $options['api_key'] ) ? sanitize_text_field( $options['api_key'] ) : '';

			add_settings_error(
				$this->plugin_name,
				$this->plugin_name,
				__('Invalid API key. Please enter a valid key.', 'event-feed-for-eventbrite'),
				'error'
			);

		}

		// Cache duration in seconds
		$valid['cache_duration'] = intval( $input['cache_duration'] );
	
		return $valid;

	}

	/**
	 * Validate data on Design Settings page.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function validate_appearance( $input ) {
		
		// All inputs
		$valid = array();

		// Use Google fonts
		$valid['google_fonts'] = boolval( $input['google_fonts'] );

		// Google font family name
		$valid['google_fonts_family'] = sanitize_text_field( $input['google_fonts_family'] );

		// Placeholder image URL
		$valid['placeholder_image'] = esc_url_raw( $input['placeholder_image'] );

		// PLaceholder attachment ID
		$valid['placeholder_id'] = intval( $input['placeholder_id'] );

		return $valid;

	}

	/**
	 * Validate data on Date & Address Settings page.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function validate_formats( $input ) {
		
		// All inputs
		$valid = array();

		// Time Format
		$valid['time_format'] = boolval( $input['time_format'] );
		
		// Full Date Format
		$valid['date_format_custom'] = sanitize_text_field( $input['date_format_custom'] );

		// Address Format
		$valid['address_format'] = sanitize_text_field( $input['address_format'] );

		// Eventbrite timezone
		$valid['eventbrite_timezone'] = boolval( $input['eventbrite_timezone'] );

		return $valid;

	}

	/**
	 * Validate data on Advanced Settings page.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function validate_advanced( $input ) {
		
		// All inputs
		$valid = array();

		// Hide delete cache button in admin bar
		$valid['hide_delete_cache_admin_bar'] = boolval( $input['hide_delete_cache_admin_bar'] );

		// Delete plugins data during deactivation
		$valid['delete_data'] = boolval( $input['delete_data'] );

		// Show copyright
		$valid['show_copyright'] = boolval( $input['show_copyright'] );

		return $valid;

	}

	/**
	 * Get list of all Google fonts
	 * https://www.googleapis.com/webfonts/v1/webfonts?key=YOUR-API-KEY
	 * https://codepen.io/ecsora/pen/gMdbOm
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function get_google_fonts_list() {
		$list = ["ABeeZee","Abel","Abhaya Libre","Abril Fatface","Aclonica","Acme","Actor","Adamina","Advent Pro","Aguafina Script","Akaya Kanadaka","Akaya Telivigala","Akronim","Akshar","Aladin","Alata","Alatsi","Aldrich","Alef","Alegreya","Alegreya SC","Alegreya Sans","Alegreya Sans SC","Aleo","Alex Brush","Alfa Slab One","Alice","Alike","Alike Angular","Allan","Allerta","Allerta Stencil","Allison","Allura","Almarai","Almendra","Almendra Display","Almendra SC","Alumni Sans","Alumni Sans Inline One","Amarante","Amaranth","Amatic SC","Amethysta","Amiko","Amiri","Amita","Anaheim","Andada Pro","Andika","Andika New Basic","Anek Bangla","Anek Devanagari","Anek Gujarati","Anek Gurmukhi","Anek Kannada","Anek Latin","Anek Malayalam","Anek Odia","Anek Tamil","Anek Telugu","Angkor","Annie Use Your Telescope","Anonymous Pro","Antic","Antic Didone","Antic Slab","Anton","Antonio","Anybody","Arapey","Arbutus","Arbutus Slab","Architects Daughter","Archivo","Archivo Black","Archivo Narrow","Are You Serious","Aref Ruqaa","Arima Madurai","Arimo","Arizonia","Armata","Arsenal","Artifika","Arvo","Arya","Asap","Asap Condensed","Asar","Asset","Assistant","Astloch","Asul","Athiti","Atkinson Hyperlegible","Atma","Atomic Age","Aubrey","Audiowide","Autour One","Average","Average Sans","Averia Gruesa Libre","Averia Libre","Averia Sans Libre","Averia Serif Libre","Azeret Mono","B612","B612 Mono","BIZ UDGothic","BIZ UDMincho","BIZ UDPGothic","BIZ UDPMincho","Babylonica","Bad Script","Bahiana","Bahianita","Bai Jamjuree","Bakbak One","Ballet","Baloo 2","Baloo Bhai 2","Baloo Bhaijaan 2","Baloo Bhaina 2","Baloo Chettan 2","Baloo Da 2","Baloo Paaji 2","Baloo Tamma 2","Baloo Tammudu 2","Baloo Thambi 2","Balsamiq Sans","Balthazar","Bangers","Barlow","Barlow Condensed","Barlow Semi Condensed","Barriecito","Barrio","Basic","Baskervville","Battambang","Baumans","Bayon","Be Vietnam Pro","Beau Rivage","Bebas Neue","Belgrano","Bellefair","Belleza","Bellota","Bellota Text","BenchNine","Benne","Bentham","Berkshire Swash","Besley","Beth Ellen","Bevan","BhuTuka Expanded One","Big Shoulders Display","Big Shoulders Inline Display","Big Shoulders Inline Text","Big Shoulders Stencil Display","Big Shoulders Stencil Text","Big Shoulders Text","Bigelow Rules","Bigshot One","Bilbo","Bilbo Swash Caps","BioRhyme","BioRhyme Expanded","Birthstone","Birthstone Bounce","Biryani","Bitter","Black And White Picture","Black Han Sans","Black Ops One","Blaka","Blaka Hollow","Blinker","Bodoni Moda","Bokor","Bona Nova","Bonbon","Bonheur Royale","Boogaloo","Bowlby One","Bowlby One SC","Brawler","Bree Serif","Brygada 1918","Bubblegum Sans","Bubbler One","Buda","Buenard","Bungee","Bungee Hairline","Bungee Inline","Bungee Outline","Bungee Shade","Butcherman","Butterfly Kids","Cabin","Cabin Condensed","Cabin Sketch","Caesar Dressing","Cagliostro","Cairo","Caladea","Calistoga","Calligraffitti","Cambay","Cambo","Candal","Cantarell","Cantata One","Cantora One","Capriola","Caramel","Carattere","Cardo","Carme","Carrois Gothic","Carrois Gothic SC","Carter One","Castoro","Catamaran","Caudex","Caveat","Caveat Brush","Cedarville Cursive","Ceviche One","Chakra Petch","Changa","Changa One","Chango","Charis SIL","Charm","Charmonman","Chathura","Chau Philomene One","Chela One","Chelsea Market","Chenla","Cherish","Cherry Cream Soda","Cherry Swash","Chewy","Chicle","Chilanka","Chivo","Chonburi","Cinzel","Cinzel Decorative","Clicker Script","Coda","Coda Caption","Codystar","Coiny","Combo","Comfortaa","Comforter","Comforter Brush","Comic Neue","Coming Soon","Commissioner","Concert One","Condiment","Content","Contrail One","Convergence","Cookie","Copse","Corben","Corinthia","Cormorant","Cormorant Garamond","Cormorant Infant","Cormorant SC","Cormorant Unicase","Cormorant Upright","Courgette","Courier Prime","Cousine","Coustard","Covered By Your Grace","Crafty Girls","Creepster","Crete Round","Crimson Pro","Crimson Text","Croissant One","Crushed","Cuprum","Cute Font","Cutive","Cutive Mono","DM Mono","DM Sans","DM Serif Display","DM Serif Text","Damion","Dancing Script","Dangrek","Darker Grotesque","David Libre","Dawning of a New Day","Days One","Dekko","Dela Gothic One","Delius","Delius Swash Caps","Delius Unicase","Della Respira","Denk One","Devonshire","Dhurjati","Didact Gothic","Diplomata","Diplomata SC","Do Hyeon","Dokdo","Domine","Donegal One","Dongle","Doppio One","Dorsa","Dosis","DotGothic16","Dr Sugiyama","Duru Sans","Dynalight","EB Garamond","Eagle Lake","East Sea Dokdo","Eater","Economica","Eczar","El Messiri","Electrolize","Elsie","Elsie Swash Caps","Emblema One","Emilys Candy","Encode Sans","Encode Sans Condensed","Encode Sans Expanded","Encode Sans SC","Encode Sans Semi Condensed","Encode Sans Semi Expanded","Engagement","Englebert","Enriqueta","Ephesis","Epilogue","Erica One","Esteban","Estonia","Euphoria Script","Ewert","Exo","Exo 2","Expletus Sans","Explora","Fahkwang","Familjen Grotesk","Fanwood Text","Farro","Farsan","Fascinate","Fascinate Inline","Faster One","Fasthand","Fauna One","Faustina","Federant","Federo","Felipa","Fenix","Festive","Finger Paint","Fira Code","Fira Mono","Fira Sans","Fira Sans Condensed","Fira Sans Extra Condensed","Fjalla One","Fjord One","Flamenco","Flavors","Fleur De Leah","Flow Block","Flow Circular","Flow Rounded","Fondamento","Fontdiner Swanky","Forum","Francois One","Frank Ruhl Libre","Fraunces","Freckle Face","Fredericka the Great","Fredoka","Fredoka One","Freehand","Fresca","Frijole","Fruktur","Fugaz One","Fuggles","Fuzzy Bubbles","GFS Didot","GFS Neohellenic","Gabriela","Gaegu","Gafata","Galada","Galdeano","Galindo","Gamja Flower","Gayathri","Gelasio","Gemunu Libre","Genos","Gentium Basic","Gentium Book Basic","Gentium Plus","Geo","Georama","Geostar","Geostar Fill","Germania One","Gideon Roman","Gidugu","Gilda Display","Girassol","Give You Glory","Glass Antiqua","Glegoo","Gloria Hallelujah","Glory","Gluten","Goblin One","Gochi Hand","Goldman","Gorditas","Gothic A1","Gotu","Goudy Bookletter 1911","Gowun Batang","Gowun Dodum","Graduate","Grand Hotel","Grandstander","Grape Nuts","Gravitas One","Great Vibes","Grechen Fuemen","Grenze","Grenze Gotisch","Grey Qo","Griffy","Gruppo","Gudea","Gugi","Gupter","Gurajada","Gwendolyn","Habibi","Hachi Maru Pop","Hahmlet","Halant","Hammersmith One","Hanalei","Hanalei Fill","Handlee","Hanuman","Happy Monkey","Harmattan","Headland One","Heebo","Henny Penny","Hepta Slab","Herr Von Muellerhoff","Hi Melody","Hina Mincho","Hind","Hind Guntur","Hind Madurai","Hind Siliguri","Hind Vadodara","Holtwood One SC","Homemade Apple","Homenaje","Hubballi","Hurricane","IBM Plex Mono","IBM Plex Sans","IBM Plex Sans Arabic","IBM Plex Sans Condensed","IBM Plex Sans Devanagari","IBM Plex Sans Hebrew","IBM Plex Sans KR","IBM Plex Sans Thai","IBM Plex Sans Thai Looped","IBM Plex Serif","IM Fell DW Pica","IM Fell DW Pica SC","IM Fell Double Pica","IM Fell Double Pica SC","IM Fell English","IM Fell English SC","IM Fell French Canon","IM Fell French Canon SC","IM Fell Great Primer","IM Fell Great Primer SC","Ibarra Real Nova","Iceberg","Iceland","Imbue","Imperial Script","Imprima","Inconsolata","Inder","Indie Flower","Ingrid Darling","Inika","Inknut Antiqua","Inria Sans","Inria Serif","Inspiration","Inter","Irish Grover","Island Moments","Istok Web","Italiana","Italianno","Itim","Jacques Francois","Jacques Francois Shadow","Jaldi","JetBrains Mono","Jim Nightshade","Joan","Jockey One","Jolly Lodger","Jomhuria","Jomolhari","Josefin Sans","Josefin Slab","Jost","Joti One","Jua","Judson","Julee","Julius Sans One","Junge","Jura","Just Another Hand","Just Me Again Down Here","K2D","Kadwa","Kaisei Decol","Kaisei HarunoUmi","Kaisei Opti","Kaisei Tokumin","Kalam","Kameron","Kanit","Kantumruy","Karantina","Karla","Karma","Katibeh","Kaushan Script","Kavivanar","Kavoon","Kdam Thmor","Kdam Thmor Pro","Keania One","Kelly Slab","Kenia","Khand","Khmer","Khula","Kings","Kirang Haerang","Kite One","Kiwi Maru","Klee One","Knewave","KoHo","Kodchasan","Koh Santepheap","Kolker Brush","Kosugi","Kosugi Maru","Kotta One","Koulen","Kranky","Kreon","Kristi","Krona One","Krub","Kufam","Kulim Park","Kumar One","Kumar One Outline","Kumbh Sans","Kurale","La Belle Aurore","Lacquer","Laila","Lakki Reddy","Lalezar","Lancelot","Langar","Lateef","Lato","Lavishly Yours","League Gothic","League Script","League Spartan","Leckerli One","Ledger","Lekton","Lemon","Lemonada","Lexend","Lexend Deca","Lexend Exa","Lexend Giga","Lexend Mega","Lexend Peta","Lexend Tera","Lexend Zetta","Libre Barcode 128","Libre Barcode 128 Text","Libre Barcode 39","Libre Barcode 39 Extended","Libre Barcode 39 Extended Text","Libre Barcode 39 Text","Libre Barcode EAN13 Text","Libre Baskerville","Libre Bodoni","Libre Caslon Display","Libre Caslon Text","Libre Franklin","Licorice","Life Savers","Lilita One","Lily Script One","Limelight","Linden Hill","Literata","Liu Jian Mao Cao","Livvic","Lobster","Lobster Two","Londrina Outline","Londrina Shadow","Londrina Sketch","Londrina Solid","Long Cang","Lora","Love Light","Love Ya Like A Sister","Loved by the King","Lovers Quarrel","Luckiest Guy","Lusitana","Lustria","Luxurious Roman","Luxurious Script","M PLUS 1","M PLUS 1 Code","M PLUS 1p","M PLUS 2","M PLUS Code Latin","M PLUS Rounded 1c","Ma Shan Zheng","Macondo","Macondo Swash Caps","Mada","Magra","Maiden Orange","Maitree","Major Mono Display","Mako","Mali","Mallanna","Mandali","Manjari","Manrope","Mansalva","Manuale","Marcellus","Marcellus SC","Marck Script","Margarine","Markazi Text","Marko One","Marmelad","Martel","Martel Sans","Marvel","Mate","Mate SC","Maven Pro","McLaren","Mea Culpa","Meddon","MedievalSharp","Medula One","Meera Inimai","Megrim","Meie Script","Meow Script","Merienda","Merienda One","Merriweather","Merriweather Sans","Metal","Metal Mania","Metamorphous","Metrophobic","Michroma","Milonga","Miltonian","Miltonian Tattoo","Mina","Miniver","Miriam Libre","Mirza","Miss Fajardose","Mitr","Mochiy Pop One","Mochiy Pop P One","Modak","Modern Antiqua","Mogra","Mohave","Molengo","Molle","Monda","Monofett","Monoton","Monsieur La Doulaise","Montaga","Montagu Slab","MonteCarlo","Montez","Montserrat","Montserrat Alternates","Montserrat Subrayada","Moo Lah Lah","Moon Dance","Moul","Moulpali","Mountains of Christmas","Mouse Memoirs","Mr Bedfort","Mr Dafoe","Mr De Haviland","Mrs Saint Delafield","Mrs Sheppards","Ms Madi","Mukta","Mukta Mahee","Mukta Malar","Mukta Vaani","Mulish","Murecho","MuseoModerno","My Soul","Mystery Quest","NTR","Nanum Brush Script","Nanum Gothic","Nanum Gothic Coding","Nanum Myeongjo","Nanum Pen Script","Neonderthaw","Nerko One","Neucha","Neuton","New Rocker","New Tegomin","News Cycle","Newsreader","Niconne","Niramit","Nixie One","Nobile","Nokora","Norican","Nosifer","Notable","Nothing You Could Do","Noticia Text","Noto Emoji","Noto Kufi Arabic","Noto Music","Noto Naskh Arabic","Noto Nastaliq Urdu","Noto Rashi Hebrew","Noto Sans","Noto Sans Adlam","Noto Sans Adlam Unjoined","Noto Sans Anatolian Hieroglyphs","Noto Sans Arabic","Noto Sans Armenian","Noto Sans Avestan","Noto Sans Balinese","Noto Sans Bamum","Noto Sans Bassa Vah","Noto Sans Batak","Noto Sans Bengali","Noto Sans Bhaiksuki","Noto Sans Brahmi","Noto Sans Buginese","Noto Sans Buhid","Noto Sans Canadian Aboriginal","Noto Sans Carian","Noto Sans Caucasian Albanian","Noto Sans Chakma","Noto Sans Cham","Noto Sans Cherokee","Noto Sans Coptic","Noto Sans Cuneiform","Noto Sans Cypriot","Noto Sans Deseret","Noto Sans Devanagari","Noto Sans Display","Noto Sans Duployan","Noto Sans Egyptian Hieroglyphs","Noto Sans Elbasan","Noto Sans Elymaic","Noto Sans Georgian","Noto Sans Glagolitic","Noto Sans Gothic","Noto Sans Grantha","Noto Sans Gujarati","Noto Sans Gunjala Gondi","Noto Sans Gurmukhi","Noto Sans HK","Noto Sans Hanifi Rohingya","Noto Sans Hanunoo","Noto Sans Hatran","Noto Sans Hebrew","Noto Sans Imperial Aramaic","Noto Sans Indic Siyaq Numbers","Noto Sans Inscriptional Pahlavi","Noto Sans Inscriptional Parthian","Noto Sans JP","Noto Sans Javanese","Noto Sans KR","Noto Sans Kaithi","Noto Sans Kannada","Noto Sans Kayah Li","Noto Sans Kharoshthi","Noto Sans Khmer","Noto Sans Khojki","Noto Sans Khudawadi","Noto Sans Lao","Noto Sans Lepcha","Noto Sans Limbu","Noto Sans Linear A","Noto Sans Linear B","Noto Sans Lisu","Noto Sans Lycian","Noto Sans Lydian","Noto Sans Mahajani","Noto Sans Malayalam","Noto Sans Mandaic","Noto Sans Manichaean","Noto Sans Marchen","Noto Sans Masaram Gondi","Noto Sans Math","Noto Sans Mayan Numerals","Noto Sans Medefaidrin","Noto Sans Meetei Mayek","Noto Sans Meroitic","Noto Sans Miao","Noto Sans Modi","Noto Sans Mongolian","Noto Sans Mono","Noto Sans Mro","Noto Sans Multani","Noto Sans Myanmar","Noto Sans N Ko","Noto Sans Nabataean","Noto Sans New Tai Lue","Noto Sans Newa","Noto Sans Nushu","Noto Sans Ogham","Noto Sans Ol Chiki","Noto Sans Old Hungarian","Noto Sans Old Italic","Noto Sans Old North Arabian","Noto Sans Old Permic","Noto Sans Old Persian","Noto Sans Old Sogdian","Noto Sans Old South Arabian","Noto Sans Old Turkic","Noto Sans Oriya","Noto Sans Osage","Noto Sans Osmanya","Noto Sans Pahawh Hmong","Noto Sans Palmyrene","Noto Sans Pau Cin Hau","Noto Sans Phags Pa","Noto Sans Phoenician","Noto Sans Psalter Pahlavi","Noto Sans Rejang","Noto Sans Runic","Noto Sans SC","Noto Sans Samaritan","Noto Sans Saurashtra","Noto Sans Sharada","Noto Sans Shavian","Noto Sans Siddham","Noto Sans Sinhala","Noto Sans Sogdian","Noto Sans Sora Sompeng","Noto Sans Soyombo","Noto Sans Sundanese","Noto Sans Syloti Nagri","Noto Sans Symbols","Noto Sans Symbols 2","Noto Sans Syriac","Noto Sans TC","Noto Sans Tagalog","Noto Sans Tagbanwa","Noto Sans Tai Le","Noto Sans Tai Tham","Noto Sans Tai Viet","Noto Sans Takri","Noto Sans Tamil","Noto Sans Tamil Supplement","Noto Sans Telugu","Noto Sans Thaana","Noto Sans Thai","Noto Sans Thai Looped","Noto Sans Tifinagh","Noto Sans Tirhuta","Noto Sans Ugaritic","Noto Sans Vai","Noto Sans Wancho","Noto Sans Warang Citi","Noto Sans Yi","Noto Sans Zanabazar Square","Noto Serif","Noto Serif Ahom","Noto Serif Armenian","Noto Serif Balinese","Noto Serif Bengali","Noto Serif Devanagari","Noto Serif Display","Noto Serif Dogra","Noto Serif Ethiopic","Noto Serif Georgian","Noto Serif Grantha","Noto Serif Gujarati","Noto Serif Gurmukhi","Noto Serif Hebrew","Noto Serif JP","Noto Serif KR","Noto Serif Kannada","Noto Serif Khmer","Noto Serif Lao","Noto Serif Malayalam","Noto Serif Myanmar","Noto Serif Nyiakeng Puachue Hmong","Noto Serif SC","Noto Serif Sinhala","Noto Serif TC","Noto Serif Tamil","Noto Serif Tangut","Noto Serif Telugu","Noto Serif Thai","Noto Serif Tibetan","Noto Serif Yezidi","Noto Traditional Nushu","Nova Cut","Nova Flat","Nova Mono","Nova Oval","Nova Round","Nova Script","Nova Slim","Nova Square","Numans","Nunito","Nunito Sans","Nuosu SIL","Odibee Sans","Odor Mean Chey","Offside","Oi","Old Standard TT","Oldenburg","Ole","Oleo Script","Oleo Script Swash Caps","Oooh Baby","Open Sans","Oranienbaum","Orbitron","Oregano","Orelega One","Orienta","Original Surfer","Oswald","Otomanopee One","Outfit","Over the Rainbow","Overlock","Overlock SC","Overpass","Overpass Mono","Ovo","Oxanium","Oxygen","Oxygen Mono","PT Mono","PT Sans","PT Sans Caption","PT Sans Narrow","PT Serif","PT Serif Caption","Pacifico","Padauk","Palanquin","Palanquin Dark","Palette Mosaic","Pangolin","Paprika","Parisienne","Passero One","Passion One","Passions Conflict","Pathway Gothic One","Patrick Hand","Patrick Hand SC","Pattaya","Patua One","Pavanam","Paytone One","Peddana","Peralta","Permanent Marker","Petemoss","Petit Formal Script","Petrona","Philosopher","Piazzolla","Piedra","Pinyon Script","Pirata One","Plaster","Play","Playball","Playfair Display","Playfair Display SC","Plus Jakarta Sans","Podkova","Poiret One","Poller One","Poly","Pompiere","Pontano Sans","Poor Story","Poppins","Port Lligat Sans","Port Lligat Slab","Potta One","Pragati Narrow","Praise","Prata","Preahvihear","Press Start 2P","Pridi","Princess Sofia","Prociono","Prompt","Prosto One","Proza Libre","Public Sans","Puppies Play","Puritan","Purple Purse","Qahiri","Quando","Quantico","Quattrocento","Quattrocento Sans","Questrial","Quicksand","Quintessential","Qwigley","Qwitcher Grypen","Racing Sans One","Radio Canada","Radley","Rajdhani","Rakkas","Raleway","Raleway Dots","Ramabhadra","Ramaraja","Rambla","Rammetto One","Rampart One","Ranchers","Rancho","Ranga","Rasa","Rationale","Ravi Prakash","Readex Pro","Recursive","Red Hat Display","Red Hat Mono","Red Hat Text","Red Rose","Redacted","Redacted Script","Redressed","Reem Kufi","Reenie Beanie","Reggae One","Revalia","Rhodium Libre","Ribeye","Ribeye Marrow","Righteous","Risque","Road Rage","Roboto","Roboto Condensed","Roboto Flex","Roboto Mono","Roboto Serif","Roboto Slab","Rochester","Rock 3D","Rock Salt","RocknRoll One","Rokkitt","Romanesco","Ropa Sans","Rosario","Rosarivo","Rouge Script","Rowdies","Rozha One","Rubik","Rubik Beastly","Rubik Bubbles","Rubik Glitch","Rubik Microbe","Rubik Mono One","Rubik Moonrocks","Rubik Puddles","Rubik Wet Paint","Ruda","Rufina","Ruge Boogie","Ruluko","Rum Raisin","Ruslan Display","Russo One","Ruthie","Rye","STIX Two Text","Sacramento","Sahitya","Sail","Saira","Saira Condensed","Saira Extra Condensed","Saira Semi Condensed","Saira Stencil One","Salsa","Sanchez","Sancreek","Sansita","Sansita Swashed","Sarabun","Sarala","Sarina","Sarpanch","Sassy Frass","Satisfy","Sawarabi Gothic","Sawarabi Mincho","Scada","Scheherazade New","Schoolbell","Scope One","Seaweed Script","Secular One","Sedgwick Ave","Sedgwick Ave Display","Sen","Send Flowers","Sevillana","Seymour One","Shadows Into Light","Shadows Into Light Two","Shalimar","Shanti","Share","Share Tech","Share Tech Mono","Shippori Antique","Shippori Antique B1","Shippori Mincho","Shippori Mincho B1","Shizuru","Shojumaru","Short Stack","Shrikhand","Siemreap","Sigmar One","Signika","Signika Negative","Simonetta","Single Day","Sintony","Sirin Stencil","Six Caps","Skranji","Slabo 13px","Slabo 27px","Slackey","Smokum","Smooch","Smooch Sans","Smythe","Sniglet","Snippet","Snowburst One","Sofadi One","Sofia","Solway","Song Myung","Sonsie One","Sora","Sorts Mill Goudy","Source Code Pro","Source Sans 3","Source Sans Pro","Source Serif 4","Source Serif Pro","Space Grotesk","Space Mono","Special Elite","Spectral","Spectral SC","Spicy Rice","Spinnaker","Spirax","Spline Sans","Spline Sans Mono","Squada One","Square Peg","Sree Krushnadevaraya","Sriracha","Srisakdi","Staatliches","Stalemate","Stalinist One","Stardos Stencil","Stick","Stick No Bills","Stint Ultra Condensed","Stint Ultra Expanded","Stoke","Strait","Style Script","Stylish","Sue Ellen Francisco","Suez One","Sulphur Point","Sumana","Sunflower","Sunshiney","Supermercado One","Sura","Suranna","Suravaram","Suwannaphum","Swanky and Moo Moo","Syncopate","Syne","Syne Mono","Syne Tactile","Tai Heritage Pro","Tajawal","Tangerine","Tapestry","Taprom","Tauri","Taviraj","Teko","Telex","Tenali Ramakrishna","Tenor Sans","Text Me One","Texturina","Thasadith","The Girl Next Door","The Nautigal","Tienne","Tillana","Timmana","Tinos","Tiro Bangla","Tiro Devanagari Hindi","Tiro Devanagari Marathi","Tiro Devanagari Sanskrit","Tiro Gurmukhi","Tiro Kannada","Tiro Tamil","Tiro Telugu","Titan One","Titillium Web","Tomorrow","Tourney","Trade Winds","Train One","Trirong","Trispace","Trocchi","Trochut","Truculenta","Trykker","Tulpen One","Turret Road","Twinkle Star","Ubuntu","Ubuntu Condensed","Ubuntu Mono","Uchen","Ultra","Uncial Antiqua","Underdog","Unica One","UnifrakturCook","UnifrakturMaguntia","Unkempt","Unlock","Unna","Updock","Urbanist","VT323","Vampiro One","Varela","Varela Round","Varta","Vast Shadow","Vazirmatn","Vesper Libre","Viaoda Libre","Vibes","Vibur","Vidaloka","Viga","Voces","Volkhov","Vollkorn","Vollkorn SC","Voltaire","Vujahday Script","Waiting for the Sunrise","Wallpoet","Walter Turncoat","Warnes","Water Brush","Waterfall","Wellfleet","Wendy One","Whisper","WindSong","Wire One","Work Sans","Xanh Mono","Yaldevi","Yanone Kaffeesatz","Yantramanav","Yatra One","Yellowtail","Yeon Sung","Yeseva One","Yesteryear","Yomogi","Yrsa","Yuji Boku","Yuji Hentaigana Akari","Yuji Hentaigana Akebono","Yuji Mai","Yuji Syuku","Yusei Magic","ZCOOL KuaiLe","ZCOOL QingKe HuangYou","ZCOOL XiaoWei","Zen Antique","Zen Antique Soft","Zen Dots","Zen Kaku Gothic Antique","Zen Kaku Gothic New","Zen Kurenaido","Zen Loop","Zen Maru Gothic","Zen Old Mincho","Zen Tokyo Zoo","Zeyada","Zhi Mang Xing","Zilla Slab","Zilla Slab Highlight"];
		return $list;
	}

	/**
	 * Admin notices.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function event_feed_for_eventbrite_admin_notices() {

		// Admin notice in event feed edit screen if user haven't filled API key yet.
		if ( get_post_type() == 'event_feed' ) {
			$api_key = ( isset( $this->event_feed_for_eventbrite_options['api_key'] ) ) ? sanitize_text_field( $this->event_feed_for_eventbrite_options['api_key'] ) : '';
			if( ! $api_key ) {
			?>
				<div class="notice notice-warning is-dismissible">
					<p><?php echo esc_html__( 'To get started with Event Feed for Eventbrite, please', 'event-feed-for-eventbrite' ) . ' <a href="' . esc_url( admin_url( 'edit.php?post_type=event_feed&page=' . $this->plugin_name . '-settings' ) ) . '">' . esc_html__( ' enter your Eventbrite API key on the plugin settings page', 'event-feed-for-eventbrite' ) . '</a>.'; ?></p>
				</div>
			<?php
			}
		}

		// Confirmation of flushed cache
		if ( isset( $_GET[ 'purge_cache' ] ) && $_GET[ 'purge_cache' ] == true ) {
		?>
			<div class="notice notice-success is-dismissible">
				<p><?php esc_html_e( 'Eventbrite events were successfully updated.', 'event-feed-for-eventbrite' ); ?></p>
			</div>
		<?php
		}

		// Confirmation of duplicated event_feed
		if ( isset( $_GET[ 'duplicated' ] ) && $_GET[ 'duplicated' ] == true ) {
		?>
			<div class="notice notice-success is-dismissible">
				<p><?php esc_html_e( 'Event feed successfully duplicated.', 'event-feed-for-eventbrite' ); ?></p>
			</div>
		<?php
		}

	}

	/**
	 * Change left side of footer text on plugin admin pages.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function change_left_admin_footer_text( $text ) {
		if( get_post_type() == 'event_feed' 
			|| ( isset( $_GET[ 'page' ] ) && $_GET[ 'page' ] == $this->plugin_name . '-settings' )
		) {
			$footer_text = sprintf(
				'%s <strong>%s</strong> <a href="https://wordpress.org/support/plugin/event-feed-for-eventbrite/reviews/?filter=5#new-post" target="_blank">★★★★★</a> %s <a href="https://wordpress.org/support/plugin/event-feed-for-eventbrite/reviews/?filter=5#new-post" target="_blank">%s</a> %s',
				esc_html__( 'Please rate', 'event-feed-for-eventbrite' ),
				esc_html__( 'Event Feed for Eventbrite', 'event-feed-for-eventbrite' ),
				esc_html__( 'on', 'event-feed-for-eventbrite' ),
				esc_html__( 'WordPress.org', 'event-feed-for-eventbrite' ),
				esc_html__( 'to help us spread the word. Thank you very much!', 'event-feed-for-eventbrite' )
			);
			return $footer_text;
		} elseif( ( isset( $_GET[ 'page' ] ) && $_GET[ 'page' ] == $this->plugin_name . '-getting-started' ) ) {
			return '';
		} else {
			return $text;
		}
	}

	/**
	 * Remove right side of footer text on plugin admin pages.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function change_right_admin_footer_text( $text ) {
		if( get_post_type() == 'event_feed'
			|| ( isset( $_GET[ 'page' ] ) && $_GET[ 'page' ] == $this->plugin_name . '-settings' )
			|| ( isset( $_GET[ 'page' ] ) && $_GET[ 'page' ] == $this->plugin_name . '-getting-started' )
		) {
			return '';
		} else {
			return $text;
		}
	}

	/**
	 * Add admin bar button to purge the cache.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function purge_cache_admin_bar_button( $admin_bar ) {

		if ( ! current_user_can( 'manage_options' ) ) {
		    return;
		}

		if( ! $this->event_feed_for_eventbrite_options_advanced || $this->event_feed_for_eventbrite_options_advanced['hide_delete_cache_admin_bar'] !== true ) {

			$args = array(
				'id' => 'event-feed-for-eventbrite-purge-cache-btn',
				'title' => '<span class="ab-icon"></span><span class="ab-label">' . esc_html__( 'Delete Eventbrite Cache', 'event-feed-for-eventbrite' ) . '</span>',
				'parent' => 'top-secondary',
				'href' => wp_nonce_url( add_query_arg( array( 'action' => 'flush_transients' ), wp_get_referer() ), $this->plugin_name )
			);
			$admin_bar->add_node( $args );
			
		}
		
	}

	/**
	 * Process purge cache admin action.
	 *
	 * @since    1.0.0
	 * @access   public
	*/
	public function process_admin_actions() {

		if( empty( $_REQUEST['action'] ) ) {
			return;
		}

		if( $_REQUEST['action'] !== 'flush_transients' ) {
			return;
		}

		if( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if( ! wp_verify_nonce( $_REQUEST['_wpnonce'], $this->plugin_name ) ) {
			return;
		}

		switch( $_REQUEST['action'] ) {

			case 'flush_transients' :
			eventbrite()->flush_transients();
			if( is_admin() ) {
				wp_safe_redirect( add_query_arg( array( 'purge_cache' => 'true' ), wp_get_referer() ) ); exit;
			} else {
				wp_safe_redirect( wp_get_referer() ); exit;
			}
			break;

		}

	}

	/**
	 * Add metaboxes to custom post type admin screen.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function setup_custom_post_type_metaboxes() {
		add_meta_box( 'event_feed_design', esc_html__( 'Feed Design', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_design' ), 'event_feed', 'normal', 'high' );
		add_meta_box( 'event_feed_card', esc_html__( 'Event Card Settings', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_card' ), 'event_feed', 'normal', 'high' );
		add_meta_box( 'event_feed_popup', esc_html__( 'Popup Settings', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_popup' ), 'event_feed', 'normal', 'high' );
		add_meta_box( 'event_feed_checkout', esc_html__( 'Checkout Settings', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_checkout' ), 'event_feed', 'normal', 'high' );
		add_meta_box( 'event_feed_eventbrite', esc_html__( 'Eventbrite Settings', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_eventbrite' ), 'event_feed', 'normal', 'high' );
		add_meta_box( 'event_feed_filters', esc_html__( 'Event Filters', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_filters' ), 'event_feed', 'normal', 'high' );
		add_meta_box( 'event_feed_advanced', esc_html__( 'Advanced Settings', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_advanced' ), 'event_feed', 'normal', 'high' );
		add_meta_box( 'event_feed_shortcode', esc_html__( 'Shortcode', 'event-feed-for-eventbrite' ), array( $this, 'event_feed_shortcode' ), 'event_feed', 'side', 'default' );
	}

	/**
	 * Custom post type metaboxes.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function event_feed_design( $post ) {
		include_once( 'partials/event-feed/metabox-design.php' );
	}
	public function event_feed_eventbrite( $post ) {
		include_once( 'partials/event-feed/metabox-eventbrite.php' );
	}
	public function event_feed_card( $post ) {
		include_once( 'partials/event-feed/metabox-card.php' );
	}
	public function event_feed_popup( $post ) {
		include_once( 'partials/event-feed/metabox-popup.php' );
	}
	public function event_feed_checkout( $post ) {
		include_once( 'partials/event-feed/metabox-checkout.php' );
	}
	public function event_feed_advanced( $post ) {
		include_once( 'partials/event-feed/metabox-advanced.php' );
	}
	public function event_feed_filters( $post ) {
		include_once( 'partials/event-feed/metabox-filters.php' );
	}
	public function event_feed_shortcode( $post ) {
		include_once( 'partials/event-feed/metabox-shortcode.php' );
	}

	/**
	 * Add nonce to default post publish metabox.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function event_feed_add_nonce_to_default_publish_metabox() {
		if( get_post_type() == 'event_feed' ) {
			wp_nonce_field( basename( __FILE__ ), 'event-feed-nonce' );
		}
	}

	/**
	 * Redirect from Getting Started page to next screen (after entering API key in the wizard).
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function getting_started_save_api_key() {
		
		if( isset( $_POST['effe_getting_started_nonce'] ) && wp_verify_nonce( $_POST['effe_getting_started_nonce'], 'effe_getting_started_nonce') ) {

			// Sanitize the input
			$valid_api_key = sanitize_text_field( $_POST['api_key'] );

			// Test API key
			$response = eventbrite()->get_user_organizations( array( 'token' => $valid_api_key ) );

			if( ! is_wp_error( $response ) ) {

				// Get options
				$options_default = 'a:2:{s:7:"api_key";s:20:"";s:14:"cache_duration";i:86400;}';
				$options = get_option( $this->plugin_name, $options_default );

				// Set values
				$options_new['api_key'] = $valid_api_key;
				$options_new['cache_duration'] = isset( $options['cache_duration'] ) ? intval( $options['cache_duration'] ) : 86400;

				// Update API key in plugin options
				update_option( $this->plugin_name, $options_new, true );

				// Redirect to next step in wizard
				wp_redirect( admin_url( '/edit.php?post_type=event_feed&page=' . $this->plugin_name . '-getting-started&step=start-creating' ) );
				exit;

			} else {
				
				// Redirect back with error message
				wp_redirect( admin_url( '/edit.php?post_type=event_feed&page=' . $this->plugin_name . '-getting-started&notice=error' ) );
				exit;

			}
			
		} else {

			wp_die( esc_html__( 'Invalid nonce specified', 'event-feed-for-eventbrite' ), esc_html__( 'Error', 'event-feed-for-eventbrite' ), array(
				'response' 	=> 403,
				'back_link' => 'admin.php?page=' . $this->plugin_name,
			) );

		}

	}

	/**
	 * Add user's organizations to options table.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function event_feed_update_user_organizations() {
		
		if ( is_admin() ) {

			$current_screen = get_current_screen();

			// Only make API request on 'Add new event feed' and 'Edit event feed' page
			if( ( $current_screen->post_type == 'event_feed' ) && ( $current_screen->base == 'post' || $current_screen->base == 'post-new' || $current_screen->base == 'edit' ) ) {

				$api_key = isset( $this->event_feed_for_eventbrite_options[ 'api_key' ] ) ? $this->event_feed_for_eventbrite_options[ 'api_key' ] : '';
				
				if( $api_key !== '') {
					
					// Make API request and save the transient to database
					$response = eventbrite()->get_user_organizations( array( 'token' => $api_key ) );

					// If response is valid, save response to GET variable
					if ( ! is_wp_error( $response ) ) {

						$safe_user_organizations = [];
						if( $response ) {
							foreach ( $response as $user_organization ) {
								$safe_user_organization_id = intval( $user_organization->id );
								$safe_user_organization_name = sanitize_text_field( $user_organization->name );
								$safe_object = (object) [ 'id' => $safe_user_organization_id, 'name' => $safe_user_organization_name ];
								array_push( $safe_user_organizations, $safe_object );
							}
						}
						$_GET['organizations'] = $safe_user_organizations;

					} else {
						$_GET['organizations'] = false;
					}

				}

			}
		
		}

	}

	/**
	 * Add admin column showing feed's shortcode to posts table and reorder columns.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
    public function shortcode_event_feed_column( $columns ) {
        $columns = array(
            'cb' => $columns['cb'],
            'title' => esc_html__( 'Title' ),
            'layout' => esc_html__( 'Layout', 'event-feed-for-eventbrite' ),
            'organization' => esc_html__( 'Organization', 'event-feed-for-eventbrite' ),
            'shortcode' => esc_html__( 'Shortcode', 'event-feed-for-eventbrite' ),
            'date' => esc_html__( 'Date' ),
        );
        return $columns;
    }

    /**
	 * Add data to admin columns.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
    public function shortcode_event_feed_column_content( $column, $post_id ) {
        
        // Layout
        if( $column == 'layout' ) {
			$layout_type = get_post_meta( $post_id, 'layout_type', true );
			$layout_type_translation = __( 'List', 'event-feed-for-eventbrite' );
			switch ( $layout_type ) {
				case 'list':
					$layout_type_translation = __( 'List', 'event-feed-for-eventbrite' );
					break;
				case 'widget':
					$layout_type_translation = __( 'Widget', 'event-feed-for-eventbrite' );
					break;
				case 'grid':
					$layout_type_translation = __( 'Grid', 'event-feed-for-eventbrite' );
					break;
				case 'cards':
					$layout_type_translation = __( 'Cards', 'event-feed-for-eventbrite' );
					break;
			}
            echo '<span style="text-transform: capitalize">' . esc_html( $layout_type_translation ) . '</span>';
        }
		
		// Organization
        if( $column == 'organization' ) {
			$feed_organization_id = get_post_meta( $post_id, 'organization', true );

			$safe_user_organizations = [];
			if( isset( $_GET['organizations'] ) ) {
				foreach ( $_GET['organizations'] as $user_organization ) {
					$safe_user_organization_id = intval( $user_organization->id );
					$safe_user_organization_name = sanitize_text_field( $user_organization->name );
					$safe_object = (object) [ 'id' => $safe_user_organization_id, 'name' => $safe_user_organization_name ];
					array_push( $safe_user_organizations, $safe_object );
				}
			}
			$user_organizations = $safe_user_organizations;
			
            if( $feed_organization_id && ( '' !== $user_organizations  ) ) {
				$valid_organization_id = false;
				$valid_organization_name = '';
                foreach( $user_organizations as $user_organization ) {
					if( $user_organization->id == $feed_organization_id ) {
						$valid_organization_id = true;
						$valid_organization_name = $user_organization->name;
					}
				}
				if( $valid_organization_id == false ) {
					echo '<span style="color: #DC3232; font-weight: 600">' . esc_html__( 'Need review', 'event-feed-for-eventbrite' ) . '</span>';
				} else {
					echo esc_html( $valid_organization_name );
				}
            } else {
                echo '-';
            }
        }

        // Shortcode
        if( $column == 'shortcode' ) {
            echo '<span class="event-feed-for-eventbrite-shortcode-field event-feed-for-eventbrite-shortcode-field-inline">
				<input id="' . esc_attr( 'event-feed-for-eventbrite-shortcode-' . $post_id ) . '" type="text" value="' . esc_attr( '[event-feed id=' . $post_id . ']' ) . '" readonly></input>
				<span class="event-feed-for-eventbrite-tooltip" data-clipboard-target="' . esc_attr( '#event-feed-for-eventbrite-shortcode-' . $post_id ) . '">
					<svg aria-hidden="true" role="img" class="StyledOcticon-sc-7ly0uy-0 hOvdVr" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" style="display: inline-block; user-select: none; vertical-align: text-bottom;">
						<path fill-rule="evenodd" d="M5.75 1a.75.75 0 00-.75.75v3c0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75v-3a.75.75 0 00-.75-.75h-4.5zm.75 3V2.5h3V4h-3zm-2.874-.467a.75.75 0 00-.752-1.298A1.75 1.75 0 002 3.75v9.5c0 .966.784 1.75 1.75 1.75h8.5A1.75 1.75 0 0014 13.25v-9.5a1.75 1.75 0 00-.874-1.515.75.75 0 10-.752 1.298.25.25 0 01.126.217v9.5a.25.25 0 01-.25.25h-8.5a.25.25 0 01-.25-.25v-9.5a.25.25 0 01.126-.217z"></path>
					</svg>
				</span>
			</span>';
        }
    }

 	/**
	 * Make organization admin column sortable.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function organization_event_feed_column_sortable( $columns ) {
		$columns['organization'] = 'event_organization';
		return $columns;
	}
	public function organization_event_feed_column_orderby( $query ) {
		if( ! is_admin() || ! $query->is_main_query() ) {
			return;
		}
		if ( 'event_organization' === $query->get( 'orderby') ) {
			$query->set( 'orderby', 'meta_value' );
			$query->set( 'meta_key', 'organization' );
			$query->set( 'meta_type', 'char' );
		}
	}

	/**
	 * Make layout admin column sortable.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function layout_event_feed_column_sortable( $columns ) {
		$columns['layout'] = 'event_layout';
		return $columns;
	}
	public function layout_event_feed_column_orderby( $query ) {
		if( ! is_admin() || ! $query->is_main_query() ) {
			return;
		}
		if ( 'event_layout' === $query->get( 'orderby') ) {
			$query->set( 'orderby', 'meta_value' );
			$query->set( 'meta_key', 'layout_type' );
			$query->set( 'meta_type', 'char' );
		}
	}
	
	/**
	 * Admin global css.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function event_feed_admin_css() {
		if( $this->is_plugin_screen() === true ) {
		echo '<style type="text/css">';
			echo '.column-shortcode { max-width: 15%; width: 280px; }';
			echo '.column-layout { width: 12%; }';
			echo '.column-organization { width: 15%; }';
			echo '.preview { float: none; }';
			echo '.post-type-event_feed .status-trash .row-actions .preview { display: none; }';
			echo '#wpadminbar #wp-admin-bar-event-feed-for-eventbrite-purge-cache-btn .ab-icon:before { content: "\f463"; top: 2px; }';
		echo '</style>';
		}
	}

	/**
	 * Save metabox data to custom post type.
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function event_feed_save_post( $post_id, $post ) {

		// Verify the nonce before proceeding.
		if ( 
			! isset( $_POST[ 'event-feed-nonce' ] ) ||
			! wp_verify_nonce( $_POST[ 'event-feed-nonce' ], basename( __FILE__ ) )
		) {
			return;
		}

		// Bail if user doesn't have permission to edit the post.
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Bail if this is an Ajax request, autosave, or revision.
		if (
			wp_doing_ajax() ||
			wp_is_post_autosave( $post_id ) ||
			wp_is_post_revision( $post_id )
		) {
			return;
		}

		// Layout type
		$layout_type = get_post_meta( $post_id, 'layout_type', true );
		$valid_layout_type = [
			'list',
			'widget',
			'grid',
			'cards'
		];
		if ( in_array( sanitize_text_field( $_POST[ $this->plugin_name ][ 'layout_type' ] ), $valid_layout_type, true ) ) {
			$safe_layout_type = sanitize_text_field( $_POST[ $this->plugin_name ][ 'layout_type' ] );
		} else {
			$safe_layout_type = 'list';
		}
		if( $safe_layout_type !== $layout_type ) {
			update_post_meta( $post_id, 'layout_type', $safe_layout_type );
		}

		// Rows number - desktop
		$safe_rows = isset( $_POST[ $this->plugin_name ][ 'rows' ] ) ? intval( $_POST[ $this->plugin_name ][ 'rows' ] ) : 3;
		update_post_meta( $post_id, 'rows', $safe_rows );

		// Rows number - large tablet
		$safe_rows_large_tablet = isset( $_POST[ $this->plugin_name ][ 'rows_large_tablet' ] ) ? intval( $_POST[ $this->plugin_name ][ 'rows_large_tablet' ] ) : 3;
		update_post_meta( $post_id, 'rows_large_tablet', $safe_rows_large_tablet );

		// Rows number - small tablet
		$safe_rows_small_tablet = isset( $_POST[ $this->plugin_name ][ 'rows_small_tablet' ] ) ? intval( $_POST[ $this->plugin_name ][ 'rows_small_tablet' ] ) : 2;
		update_post_meta( $post_id, 'rows_small_tablet', $safe_rows_small_tablet );

		// Rows number - mobile
		$safe_rows_mobile = isset( $_POST[ $this->plugin_name ][ 'rows_mobile' ] ) ? intval( $_POST[ $this->plugin_name ][ 'rows_mobile' ] ) : 1;
		update_post_meta( $post_id, 'rows_mobile', $safe_rows_mobile );

		// Events limit - desktop
		$safe_events_limit = isset( $_POST[ $this->plugin_name ][ 'events_limit' ] ) ? intval( $_POST[ $this->plugin_name ][ 'events_limit' ] ) : 6;
		if( $safe_events_limit === 0 ) { $safe_events_limit = 6; }
		update_post_meta( $post_id, 'events_limit', $safe_events_limit );

		// No events limit - desktop
		$events_limit_no = get_post_meta( $post_id, 'events_limit_no', true );
		$safe_events_limit_no = boolval( $_POST[ $this->plugin_name ][ 'events_limit_no' ] );
		if( $safe_events_limit_no !== $events_limit_no ) {
			if( $safe_events_limit_no === true ) {
				update_post_meta( $post_id, 'events_limit_no', true );
			} else {
				delete_post_meta( $post_id, 'events_limit_no' );
			}
		}

		// Events limit - large tablet
		$safe_events_limit_large_tablet = isset( $_POST[ $this->plugin_name ][ 'events_limit_large_tablet' ] ) ? intval( $_POST[ $this->plugin_name ][ 'events_limit_large_tablet' ] ) : 6;
		if( $safe_events_limit_large_tablet === 0 ) { $safe_events_limit_large_tablet = 6; }
		update_post_meta( $post_id, 'events_limit_large_tablet', $safe_events_limit_large_tablet );

		// No events limit - large tablet
		$events_limit_no_large_tablet = get_post_meta( $post_id, 'events_limit_no_large_tablet', true );
		$safe_events_limit_no_large_tablet = boolval( $_POST[ $this->plugin_name ][ 'events_limit_no_large_tablet' ] );
		if( $safe_events_limit_no_large_tablet !== $events_limit_no_large_tablet ) {
			if( $safe_events_limit_no_large_tablet === true ) {
				update_post_meta( $post_id, 'events_limit_no_large_tablet', true );
			} else {
				delete_post_meta( $post_id, 'events_limit_no_large_tablet' );
			}
		}

		// Events limit - small tablet
		$safe_events_limit_small_tablet = isset( $_POST[ $this->plugin_name ][ 'events_limit_small_tablet' ] ) ? intval( $_POST[ $this->plugin_name ][ 'events_limit_small_tablet' ] ) : 6;
		if( $safe_events_limit_small_tablet === 0 ) { $safe_events_limit_small_tablet = 6; }
		update_post_meta( $post_id, 'events_limit_small_tablet', $safe_events_limit_small_tablet );

		// No events limit - small tablet
		$events_limit_no_small_tablet = get_post_meta( $post_id, 'events_limit_no_small_tablet', true );
		$safe_events_limit_no_small_tablet = boolval( $_POST[ $this->plugin_name ][ 'events_limit_no_small_tablet' ] );
		if( $safe_events_limit_no_small_tablet !== $events_limit_no_small_tablet ) {
			if( $safe_events_limit_no_small_tablet === true ) {
				update_post_meta( $post_id, 'events_limit_no_small_tablet', true );
			} else {
				delete_post_meta( $post_id, 'events_limit_no_small_tablet' );
			}
		}

		// Events limit - mobile
		$safe_events_limit_mobile = isset( $_POST[ $this->plugin_name ][ 'events_limit_mobile' ] ) ? intval( $_POST[ $this->plugin_name ][ 'events_limit_mobile' ] ) : 6;
		if( $safe_events_limit_mobile === 0 ) { $safe_events_limit_mobile = 6; }
		update_post_meta( $post_id, 'events_limit_mobile', $safe_events_limit_mobile );

		// No events limit - mobile
		$events_limit_no_mobile = get_post_meta( $post_id, 'events_limit_no_mobile', true );
		$safe_events_limit_no_mobile = boolval( $_POST[ $this->plugin_name ][ 'events_limit_no_mobile' ] );
		if( $safe_events_limit_no_mobile !== $events_limit_no_mobile ) {
			if( $safe_events_limit_no_mobile === true ) {
				update_post_meta( $post_id, 'events_limit_no_mobile', true );
			} else {
				delete_post_meta( $post_id, 'events_limit_no_mobile' );
			}
		}

		// Display image
		$display_image = get_post_meta( $post_id, 'display_image', true );
		$safe_display_image = boolval( $_POST[ $this->plugin_name ][ 'display_image' ] );
		if( $safe_display_image !== $display_image ) {
			if( $safe_display_image === true ) {
				update_post_meta( $post_id, 'display_image', true );
			} else {
				delete_post_meta( $post_id, 'display_image' );
			}
		}

		// Display price
		$display_price = get_post_meta( $post_id, 'display_price', true );
		$safe_display_price = boolval( $_POST[ $this->plugin_name ][ 'display_price' ] );
		if( $safe_display_price !== $display_price ) {
			if( $safe_display_price === true ) {
				update_post_meta( $post_id, 'display_price', true );
			} else {
				delete_post_meta( $post_id, 'display_price' );
			}
		}

		// Display remaining tickets
		$display_tickets = get_post_meta( $post_id, 'display_tickets', true );
		$safe_display_tickets = boolval( $_POST[ $this->plugin_name ][ 'display_tickets' ] );
		if( $safe_display_tickets !== $display_tickets ) {
			if( $safe_display_tickets === true ) {
				update_post_meta( $post_id, 'display_tickets', true );
			} else {
				delete_post_meta( $post_id, 'display_tickets' );
			}
		}

		// Display title
		$display_title = get_post_meta( $post_id, 'display_title', true );
		$safe_display_title = boolval( $_POST[ $this->plugin_name ][ 'display_title' ] );
		if( $safe_display_title !== $display_title ) {
			if( $safe_display_title === true ) {
				update_post_meta( $post_id, 'display_title', true );
			} else {
				delete_post_meta( $post_id, 'display_title' );
			}
		}

		// Display short date and time
		$display_short_datetime = get_post_meta( $post_id, 'display_short_datetime', true );
		$safe_display_short_datetime = boolval( $_POST[ $this->plugin_name ][ 'display_short_datetime' ] );
		if( $safe_display_short_datetime !== $display_short_datetime ) {
			if( $safe_display_short_datetime === true ) {
				update_post_meta( $post_id, 'display_short_datetime', true );
			} else {
				delete_post_meta( $post_id, 'display_short_datetime' );
			}
		}
		
		// Display full date and time
		$display_datetime = get_post_meta( $post_id, 'display_datetime', true );
		$safe_display_datetime = boolval( $_POST[ $this->plugin_name ][ 'display_datetime' ] );
		if( $safe_display_datetime !== $display_datetime ) {
			if( $safe_display_datetime === true ) {
				update_post_meta( $post_id, 'display_datetime', true );
			} else {
				delete_post_meta( $post_id, 'display_datetime' );
			}
		}

		// Display location
		$display_location = get_post_meta( $post_id, 'display_location', true );
		$safe_display_location = boolval( $_POST[ $this->plugin_name ][ 'display_location' ] );
		if( $safe_display_location !== $display_location ) {
			if( $safe_display_location === true ) {
				update_post_meta( $post_id, 'display_location', true );
			} else {
				delete_post_meta( $post_id, 'display_location' );
			}
		}

		// Display description
		$display_description = get_post_meta( $post_id, 'display_description', true );
		$safe_display_description = boolval( $_POST[ $this->plugin_name ][ 'display_description' ] );
		if( $safe_display_description !== $display_description ) {
			if( $safe_display_description === true ) {
				update_post_meta( $post_id, 'display_description', true );
			} else {
				delete_post_meta( $post_id, 'display_description' );
			}
		}

		// Display Sign up button
		$display_signup_button = get_post_meta( $post_id, 'display_signup_button', true );
		$safe_display_signup_button = boolval( $_POST[ $this->plugin_name ][ 'display_signup_button' ] );
		if( $safe_display_signup_button !== $display_signup_button ) {
			if( $safe_display_signup_button === true ) {
				update_post_meta( $post_id, 'display_signup_button', true );
			} else {
				delete_post_meta( $post_id, 'display_signup_button' );
			}
		}

		// Display Read more button
		$display_more_button = get_post_meta( $post_id, 'display_more_button', true );
		$safe_display_more_button = boolval( $_POST[ $this->plugin_name ][ 'display_more_button' ] );
		if( $safe_display_more_button !== $display_more_button ) {
			if( $safe_display_more_button === true ) {
				update_post_meta( $post_id, 'display_more_button', true );
			} else {
				delete_post_meta( $post_id, 'display_more_button' );
			}
		}

		// Theme color
		$safe_theme_color = isset( $_POST[ $this->plugin_name ][ 'theme_color' ] ) ? sanitize_hex_color( $_POST[ $this->plugin_name ][ 'theme_color' ] ) : '#007cba';
		update_post_meta( $post_id, 'theme_color', $safe_theme_color );

		// Title length
		$safe_title_length = isset( $_POST[ $this->plugin_name ][ 'title_length' ] ) ? intval( $_POST[ $this->plugin_name ][ 'title_length' ] ) : 55;
		if( $safe_title_length === 0 ) { $safe_title_length = 55; }
		update_post_meta( $post_id, 'title_length', $safe_title_length );

		// Title length full
		$title_length_full = get_post_meta( $post_id, 'title_length_full', true );
		$safe_title_length_full = boolval( $_POST[ $this->plugin_name ][ 'title_length_full' ] );
		if( $safe_title_length_full !== $title_length_full ) {
			if( $safe_title_length_full === true ) {
				update_post_meta( $post_id, 'title_length_full', true );
			} else {
				delete_post_meta( $post_id, 'title_length_full' );
			}
		}

		// Excerpt length
		$safe_excerpt_length = isset( $_POST[ $this->plugin_name ][ 'excerpt_length' ] ) ? intval( $_POST[ $this->plugin_name ][ 'excerpt_length' ] ) : 120;
		if( $safe_excerpt_length === 0 ) { $safe_excerpt_length = 120; }
		update_post_meta( $post_id, 'excerpt_length', $safe_excerpt_length );

		// Excerpt length full
		$excerpt_length_full = get_post_meta( $post_id, 'excerpt_length_full', true );
		$safe_excerpt_length_full = boolval( $_POST[ $this->plugin_name ][ 'excerpt_length_full' ] );
		if( $safe_excerpt_length_full !== $excerpt_length_full ) {
			if( $safe_excerpt_length_full === true ) {
				update_post_meta( $post_id, 'excerpt_length_full', true );
			} else {
				delete_post_meta( $post_id, 'excerpt_length_full' );
			}
		}

		// Display price as image overlay
		$price_overlay = get_post_meta( $post_id, 'price_overlay', true );
		$safe_price_overlay = boolval( $_POST[ $this->plugin_name ][ 'price_overlay' ] );
		if( $safe_price_overlay !== $price_overlay ) {
			if( $safe_price_overlay === true ) {
				update_post_meta( $post_id, 'price_overlay', true );
			} else {
				delete_post_meta( $post_id, 'price_overlay' );
			}
		}
		
		// Remaining tickets text
		$safe_tickets_text = isset( $_POST[ $this->plugin_name ][ 'tickets_text' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'tickets_text' ] ) : esc_html__( 'Tickets left', 'event-feed-for-eventbrite' );
		if( $safe_tickets_text === '' ) { $safe_tickets_text = 'Tickets left'; }
		update_post_meta( $post_id, 'tickets_text', $safe_tickets_text );
		
		// Buy tickets button text
		$safe_tickets_button_text = isset( $_POST[ $this->plugin_name ][ 'tickets_button_text' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'tickets_button_text' ] ) : esc_html__( 'Buy tickets', 'event-feed-for-eventbrite' );
		if( $safe_tickets_button_text === '' ) { $safe_tickets_button_text = 'Buy tickets'; }
		update_post_meta( $post_id, 'tickets_button_text', $safe_tickets_button_text );
		
		// Sign up button text
		$safe_signup_button_text = isset( $_POST[ $this->plugin_name ][ 'signup_button_text' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'signup_button_text' ] ) : esc_html__( 'Register', 'event-feed-for-eventbrite' );
		if( $safe_signup_button_text === '' ) { $safe_signup_button_text = 'Register'; }
		update_post_meta( $post_id, 'signup_button_text', $safe_signup_button_text );

		// Read more button text
		$safe_more_button_text = isset( $_POST[ $this->plugin_name ][ 'more_button_text' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'more_button_text' ] ) : esc_html__( 'View details', 'event-feed-for-eventbrite' );
		if( $safe_more_button_text === '' ) { $safe_more_button_text = 'View details'; }
		update_post_meta( $post_id, 'more_button_text', $safe_more_button_text );

		// Organization
		$safe_organization = isset( $_POST[ $this->plugin_name ][ 'organization' ] ) ? intval( $_POST[ $this->plugin_name ][ 'organization' ] ) : '';
		update_post_meta( $post_id, 'organization', $safe_organization );

		// Time filter
		$time_filter = get_post_meta( $post_id, 'time_filter', true );
		$valid_time_filter = [
			'current_future',
			'past'
		];
		if ( in_array( sanitize_text_field( $_POST[ $this->plugin_name ][ 'time_filter' ] ), $valid_time_filter, true ) ) {
			$safe_time_filter = sanitize_text_field( $_POST[ $this->plugin_name ][ 'time_filter' ] );
		} else {
			$safe_time_filter = 'current_future';
		}
		if( $safe_time_filter !== $time_filter ) {
			update_post_meta( $post_id, 'time_filter', $safe_time_filter );
		}

		// Display public events
		$display_public = get_post_meta( $post_id, 'display_public', true );
		$safe_display_public = boolval( $_POST[ $this->plugin_name ][ 'display_public' ] );
		if( $safe_display_public !== $display_public ) {
			if( $safe_display_public === true ) {
				update_post_meta( $post_id, 'display_public', true );
			} else {
				delete_post_meta( $post_id, 'display_public' );
			}
		}

		// Display private events
		$display_private = get_post_meta( $post_id, 'display_private', true );
		$safe_display_private = boolval( $_POST[ $this->plugin_name ][ 'display_private' ] );
		if( $safe_display_private !== $display_private ) {
			if( $safe_display_private === true ) {
				update_post_meta( $post_id, 'display_private', true );
			} else {
				delete_post_meta( $post_id, 'display_private' );
			}
		}

		// Display events with venue
		$display_venue = get_post_meta( $post_id, 'display_venue', true );
		$safe_display_venue = boolval( $_POST[ $this->plugin_name ][ 'display_venue' ] );
		if( $safe_display_venue !== $display_venue ) {
			if( $safe_display_venue === true ) {
				update_post_meta( $post_id, 'display_venue', true );
			} else {
				delete_post_meta( $post_id, 'display_venue' );
			}
		}

		// Display online events
		$display_online = get_post_meta( $post_id, 'display_online', true );
		$safe_display_online = boolval( $_POST[ $this->plugin_name ][ 'display_online' ] );
		if( $safe_display_online !== $display_online ) {
			if( $safe_display_online === true ) {
				update_post_meta( $post_id, 'display_online', true );
			} else {
				delete_post_meta( $post_id, 'display_online' );
			}
		}

		// Name filter
		$name_filter = get_post_meta( $post_id, 'name_filter', true );
		$safe_name_filter = isset( $_POST[ $this->plugin_name ][ 'name_filter' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'name_filter' ] ) : '';
		if ( ! $safe_name_filter && $name_filter ) {
			delete_post_meta( $post_id, 'name_filter' );
		} elseif ( $safe_name_filter !== $name_filter ) {
			update_post_meta( $post_id, 'name_filter', $safe_name_filter );
		}

		// Location filter
		$location_filter = get_post_meta( $post_id, 'location_filter', true );
		$safe_location_filter = isset( $_POST[ $this->plugin_name ][ 'location_filter' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'location_filter' ] ) : '';
		if ( ! $safe_location_filter && $location_filter ) {
			delete_post_meta( $post_id, 'location_filter' );
		} elseif ( $safe_location_filter !== $location_filter ) {
			update_post_meta( $post_id, 'location_filter', $safe_location_filter );
		}

		// Sign up behaviour
		$link_to = get_post_meta( $post_id, 'link_to', true );
		$valid_link_to = [
			'popup',
			'popup_eventbrite'
		];
		if ( in_array( sanitize_text_field( $_POST[ $this->plugin_name ][ 'link_to' ] ), $valid_link_to, true ) ) {
			$safe_link_to = sanitize_text_field( $_POST[ $this->plugin_name ][ 'link_to' ] );
		} else {
			$safe_link_to = 'popup';
		}
		if( $safe_link_to !== $link_to ) {
			update_post_meta( $post_id, 'link_to', $safe_link_to );
		}

		// Open links in
		$link_target_blank = get_post_meta( $post_id, 'link_target_blank', true );
		$safe_link_target_blank = boolval( $_POST[ $this->plugin_name ][ 'link_target_blank' ] );
		if( $safe_link_target_blank !== $link_target_blank ) {
			if( $safe_link_target_blank == true ) {
				update_post_meta( $post_id, 'link_target_blank', true );
			} else {
				delete_post_meta( $post_id, 'link_target_blank' );
			}
		}

		// Show popup
		$popup = get_post_meta( $post_id, 'popup', true );
		$safe_popup = boolval( $_POST[ $this->plugin_name ][ 'popup' ] );
		if( $safe_popup !== $popup ) {
			if( $safe_popup == true ) {
				update_post_meta( $post_id, 'popup', true );
			} else {
				delete_post_meta( $post_id, 'popup' );
			}
		}

		// Show add to calendar button
		$calendar_button = get_post_meta( $post_id, 'calendar_button', true );
		$safe_calendar_button = boolval( $_POST[ $this->plugin_name ][ 'calendar_button' ] );
		if( $safe_calendar_button !== $calendar_button ) {
			if( $safe_calendar_button == true ) {
				update_post_meta( $post_id, 'calendar_button', true );
			} else {
				delete_post_meta( $post_id, 'calendar_button' );
			}
		}

		// Show map
		$google_map = get_post_meta( $post_id, 'google_map', true );
		$safe_google_map = boolval( $_POST[ $this->plugin_name ][ 'google_map' ] );
		if( $safe_google_map !== $google_map ) {
			if( $safe_google_map == true ) {
				update_post_meta( $post_id, 'google_map', true );
			} else {
				delete_post_meta( $post_id, 'google_map' );
			}
		}

		// Show organizer
		$organizer_info = get_post_meta( $post_id, 'organizer_info', true );
		$safe_organizer_info = boolval( $_POST[ $this->plugin_name ][ 'organizer_info' ] );
		if( $safe_organizer_info !== $organizer_info ) {
			if( $safe_organizer_info == true ) {
				update_post_meta( $post_id, 'organizer_info', true );
			} else {
				delete_post_meta( $post_id, 'organizer_info' );
			}
		}

		// Show link to Eventbrite
		$eventbrite_link = get_post_meta( $post_id, 'eventbrite_link', true );
		$safe_eventbrite_link = boolval( $_POST[ $this->plugin_name ][ 'eventbrite_link' ] );
		if( $safe_eventbrite_link !== $eventbrite_link ) {
			if( $safe_eventbrite_link == true ) {
				update_post_meta( $post_id, 'eventbrite_link', true );
			} else {
				delete_post_meta( $post_id, 'eventbrite_link' );
			}
		}

		// CSS ID
		$css_id = get_post_meta( $post_id, 'css_id', true );
		$safe_css_id = isset( $_POST[ $this->plugin_name ][ 'css_id' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'css_id' ] ) : '';
		if ( ! $safe_css_id && $css_id ) {
			delete_post_meta( $post_id, 'css_id' );
		} elseif ( $safe_css_id !== $css_id ) {
			update_post_meta( $post_id, 'css_id', $safe_css_id );
		}

		// CSS classes
		$css_classes = get_post_meta( $post_id, 'css_classes', true );
		$safe_css_classes = isset( $_POST[ $this->plugin_name ][ 'css_classes' ] ) ? sanitize_text_field( $_POST[ $this->plugin_name ][ 'css_classes' ] ) : '';
		if ( ! $safe_css_classes && $css_classes ) {
			delete_post_meta( $post_id, 'css_classes' );
		} elseif ( $safe_css_classes !== $css_classes ) {
			update_post_meta( $post_id, 'css_classes', $safe_css_classes );
		}

	}

	/**
	 * Add the ability to duplicate event feed and redirects back to the edit post screen
	 *
	 * @since    1.0.0
	 * @author   Misha Rudrastyh
	 * @access   public
	 * @link     https://rudrastyh.com/wordpress/duplicate-post.html
	 */
	public function duplicate_event_feed_as_draft() {

		global $wpdb;
		if (! ( isset( $_GET[ 'post' ]) || isset( $_POST[ 'post' ] )  || ( isset( $_REQUEST[ 'action' ] ) && 'duplicate_event_feed_as_draft' == $_REQUEST[ 'action' ] ) ) ) {
			wp_die( esc_html__( 'No post to duplicate has been supplied!', 'event-feed-for-eventbrite' ) );
		}
	
		/*
		* Nonce verification
		*/
		if ( ! isset( $_GET[ 'duplicate_nonce' ] ) || ! wp_verify_nonce( $_GET[ 'duplicate_nonce' ], basename( __FILE__ ) ) )
			return;
	
		/*
		* Get the original post id
		*/
		$post_id = ( isset( $_GET[ 'post' ] ) ? absint( $_GET[ 'post' ] ) : absint( $_POST[ 'post' ] ) );

		/*
		* And all the original post data then
		*/
		$post = get_post( $post_id );
	
		/*
		* If you don't want current user to be the new post author,
		* then change next couple of lines to this: $new_post_author = $post->post_author;
		*/
		$current_user = wp_get_current_user();
		$new_post_author = $current_user->ID;
	
		/*
		* If post data exists, create the post duplicate
		*/
		if ( isset( $post ) && $post != null ) {
	
			/*
			* new post data array
			*/
			$args = array(
				'comment_status' => $post->comment_status,
				'ping_status'    => $post->ping_status,
				'post_author'    => $new_post_author,
				'post_content'   => $post->post_content,
				'post_excerpt'   => $post->post_excerpt,
				'post_name'      => $post->post_name,
				'post_parent'    => $post->post_parent,
				'post_password'  => $post->post_password,
				'post_status'    => 'publish',
				'post_title'     => $post->post_title . ' ' . esc_html__( 'Copy', 'event-feed-for-eventbrite' ),
				'post_type'      => $post->post_type,
				'to_ping'        => $post->to_ping,
				'menu_order'     => $post->menu_order
			);
	
			/*
			* Insert the post by wp_insert_post() function
			*/
			$new_post_id = wp_insert_post( $args );
	
			/*
			* Get all current post terms ad set them to the new post draft
			*/
			$taxonomies = get_object_taxonomies( $post->post_type ); // returns array of taxonomy names for post type, ex array( "category", "post_tag" );
			foreach ( $taxonomies as $taxonomy ) {
				$post_terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'slugs' ) );
				wp_set_object_terms( $new_post_id, $post_terms, $taxonomy, false );
			}
	
			/*
			* Duplicate all post meta just in two SQL queries
			*/
			$post_meta_infos = $wpdb->get_results( "SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id" );
			if ( count( $post_meta_infos ) != 0 ) {
				$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
				foreach ($post_meta_infos as $meta_info) {
					$meta_key = $meta_info->meta_key;
					if( $meta_key == '_wp_old_slug' ) continue;
					$meta_value = addslashes( $meta_info->meta_value );
					$sql_query_sel[] = "SELECT $new_post_id, '$meta_key', '$meta_value'";
				}
				$sql_query.= implode(" UNION ALL ", $sql_query_sel);
				$wpdb->query( $sql_query );
			}
	
			/*
			* Finally, redirect to the edit post screen for the new draft
			*/
			wp_redirect( admin_url( 'edit.php?post_type=' . $post->post_type . '&duplicated=true' ) );
			exit;

		} else {
			wp_die( esc_html__( 'Event feed creation failed, could not find original post:', 'event-feed-for-eventbrite' ) . ' ' . $post_id );
		}

	}

	/**
	 * Modify event feed's post row actions
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function modify_event_feed_row_actions( $actions, $post ) {
		
        if ( current_user_can( 'edit_posts' ) && $post->post_type == 'event_feed' ) {

			// Save trash temporarily
			if( isset( $actions['trash'] ) ) {
				$trash = $actions['trash'];
			}

			// Remove items from post row actions
			unset( $actions['inline hide-if-no-js'] );
            unset( $actions['view'] );
            unset( $actions['trash'] );

			$actions['preview'] = '<a href="' . esc_url( get_site_url() . '?event_feed=' . $post->post_name ) . '" rel="bookmark" aria-label="' . esc_html__( 'Preview “Event Feed”', 'event-feed-for-eventbrite' ) . '">' . esc_html__( 'Preview', 'event-feed-for-eventbrite' ) . '</a>';
			
			$actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=duplicate_event_feed_as_draft&post=' . $post->ID, basename( __FILE__ ), 'duplicate_nonce' ) . '" aria-label="' . esc_html__( 'Duplicate “Event Feed”', 'event-feed-for-eventbrite' ) . '">' . esc_html__( 'Duplicate', 'event-feed-for-eventbrite' ) . '</a>';

			// Re-add trash to the end of array
			if( isset( $trash ) ) {
				$actions['trash'] = $trash;
			}
            
        }

		return $actions;
    }

	public function prevent_draft_post_change( $data, $postarr ) {
		if ( ! isset( $postarr['ID'] ) || ! $postarr['ID'] ) return $data;
		if ( $postarr['post_type'] !== 'event_feed' ) return $data; // only for event feed
		$old = get_post( $postarr['ID'] ); // the post before update
		if (
			$old->post_status == 'trash' &&
			$data['post_status'] === 'draft'
		) {
			$data['post_status'] = 'publish';
		}
		return $data;
	}


	/**
	 * Ajax function to get date in specified format
	 *
	 * @since    1.0.0
	 * @access   public
	 */
	public function get_dateformat() {
		$date = wp_date( $_POST['format'] );
		echo esc_html( $date );
		die(1);
	}

}