<?php
/**
 * Plugin Name: Eventim US Event Listings
 * Description: This plugin is provided by Eventim US to enable event synchronization and integrate a modern and highly customizable event representation system in WordPress.
 * Version: 0.36.2
 * Author: Eventim US
 * Author URI: https://eventim.us/
 * Text Domain: eventim-us-event-listings
 * Domain Path: /languages
 * Requires at least: 5.7
 * Requires PHP: 8.1
 * License: GPL-2.0+
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

defined( 'ABSPATH' ) || exit;

if ( ! function_exists( 'plugin_dir_path' ) || ! function_exists( 'plugin_dir_url' ) ) {
	wp_die( 'WordPress functions not available. Please ensure WordPress is properly loaded.' );
}

define( 'EVUSEL_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'EVUSEL_PLUGIN_DIR_URL', plugin_dir_url( __FILE__ ) );
define( 'EVUSEL_TIMEZONE_IDENTIFIERS_LIST', timezone_identifiers_list( DateTimeZone::ALL_WITH_BC ) );

if ( evusel_required_plugins_active() ) {

	// Init custom JS and CSS
	add_action( 'wp_enqueue_scripts', 'evusel_enqueue_frontend_scripts', 110 );
	add_action( 'admin_enqueue_scripts', 'evusel_enqueue_admin_scripts' );

	require EVUSEL_PLUGIN_DIR . 'includes/evusel-event-post-type.php';

	require EVUSEL_PLUGIN_DIR . 'includes/helpers.php';

	// First include the activation file before registering the hook
	require EVUSEL_PLUGIN_DIR . 'includes/activate-plugin.php';

	// Then register the activation hook
	register_activation_hook( __FILE__, 'evusel_activate_plugin' );

	// Init configuration
	$GLOBALS['evuselConfig'] = require_once EVUSEL_PLUGIN_DIR . 'includes/EvuselConfig.php';
	$evuselConfig            = &$GLOBALS['evuselConfig'];

	// Add code to frontend header (priority 120 to run after evusel_enqueue_frontend_scripts at 110)
	add_action( 'wp_enqueue_scripts', 'evusel_custom_header_code', 120 );

	// Init ACF fields
	require EVUSEL_PLUGIN_DIR . 'includes/acf-fields.php';

	// Init shortcodes
	require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/calendar-view.php';
	require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/list-view.php';
	require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/category-filter.php';
	require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/tag-filter.php';
	require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/slider.php';
	require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/event-search.php';
	require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/just-announced-events.php';
	// require EVUSEL_PLUGIN_DIR . 'includes/shortcodes/past-events.php';

	// Register cron actions
	require_once EVUSEL_PLUGIN_DIR . 'includes/cron.php';

	require EVUSEL_PLUGIN_DIR . 'includes/evusel-dashboard.php';

	add_action( 'admin_post_save_see_settings', 'evusel_save_settings' );

} else {

	add_action( 'admin_notices', 'evusel_required_plugins_warning' );
}

add_action( 'admin_enqueue_scripts', 'evusel_enqueue_admin_scripts' );
/**
 * Enqueue admin scripts and styles.
 *
 * @param string $hook Current admin page hook.
 * @return void
 */
function evusel_enqueue_admin_scripts( $hook ) {
	if ( $hook === 'toplevel_page_eventim-us-settings' ) {
		$script_path = EVUSEL_PLUGIN_DIR . 'js/evusel-menu.js';
		if ( file_exists( $script_path ) ) {
			wp_enqueue_script(
				'evusel-menu-script',
				EVUSEL_PLUGIN_DIR_URL . 'js/evusel-menu.js',
				array(),
				filemtime( $script_path ),
				true
			);
		}
	}

	wp_register_style( 'spectrum', plugins_url( 'css/vendor/spectrum.css', __FILE__ ) );
	wp_enqueue_style( 'spectrum' );
	wp_enqueue_script( 'jquery' );
	wp_register_style(
		'evusel-admin-custom-styles',
		plugins_url( 'css/seetickets-admin-custom-styles.css', __FILE__ ),
		array(),
		time()
	);
	wp_enqueue_style( 'evusel-admin-custom-styles' );

	wp_register_script( 'spectrum', plugins_url( 'js/vendor/spectrum.js', __FILE__ ), array( 'jquery' ), null, true );
	wp_enqueue_script( 'spectrum' );
	wp_register_script( 'evusel-jquery-sortable', plugins_url( 'js/vendor/jquery-sortable.min.js', __FILE__ ), array( 'jquery' ), null, true );
	wp_enqueue_script( 'evusel-jquery-sortable' );
	wp_enqueue_script( 'jquery-ui-autocomplete' );
	wp_register_script( 'evusel-admin-custom-scripts', plugins_url( 'js/evusel-admin-custom-scripts.js', __FILE__ ), array( 'jquery', 'jquery-ui-autocomplete' ), null, true );
	wp_enqueue_script( 'evusel-admin-custom-scripts' );

	global $evuselConfig;
	if ( ! empty( $evuselConfig ) ) {
		$defaultColors = $evuselConfig->get( 'color_theme', true );

		$statusOverrideSuggestions = array_values( get_field_object( 'field_604944373ed26' )['choices'] );

		wp_localize_script(
			'evusel-admin-custom-scripts',
			'evusel_ajax_obj',
			array(
				'ajax_url'                     => admin_url( 'admin-ajax.php' ),
				'nonce'                        => wp_create_nonce( 'evusel-admin-nonce' ),
				'rest_nonce'                   => wp_create_nonce( 'wp_rest' ),
				'defaultEvuselEventImage'      => $evuselConfig->get( 'default_event_image' ),
				'defaultButtonBackgroundColor' => $defaultColors['button_background_color'],
				'defaultButtonTextColor'       => $defaultColors['button_text_color'],
				'defaultButtonTextHoverColor'  => $defaultColors['button_text_hover_color'],
				'defaultBackgroundColor'       => $defaultColors['background_color'],
				'defaultTextColor'             => $defaultColors['text_color'],
				'eventSearchShortcode'         => $evuselConfig::SHORTCODE_EVENT_SEARCH,
				'listViewShortcode'            => $evuselConfig::SHORTCODE_LIST_VIEW,
				'categoryFilterShortcode'      => $evuselConfig::SHORTCODE_CATEGORY_FILTER,
				'tagFilterShortcode'           => $evuselConfig::SHORTCODE_TAG_FILTER,
				'statusOverrideSuggestions'    => $statusOverrideSuggestions,
				'cronEndpoint'                 => $evuselConfig->get( 'api.cron_endpoint' ),
				'evuselPluginDirUrl'           => EVUSEL_PLUGIN_DIR_URL,
			)
		);
	}

	wp_enqueue_media();
}

// Init custom scripts
/**
 * Enqueue frontend scripts and styles.
 *
 * @return void
 */
function evusel_enqueue_frontend_scripts() {

	global $evuselConfig, $post;
	$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';

	if ( $evuselConfig->get( 'load_material_design_resources' ) === 'on' ) {
		wp_register_style( 'material-components-web-css', plugins_url( 'css/vendor/material-components-web.min.css', __FILE__ ), array() );
		// Enqueue the MDC JS for Material Design Components
		wp_register_script( 'material-components-web-js', plugins_url( 'js/vendor/material-components-web.min.js', __FILE__ ), array(), null, true );
		wp_enqueue_script( 'material-components-web-js' );
		// wp_register_script( 'material-components-web-js', plugins_url('js/vendor/material-components-web.min.js', __FILE__), [], null, true );
	}

	wp_register_style( 'evusel-custom-styles', plugins_url( "css/seetickets-custom-styles$min.css", __FILE__ ) );
	wp_enqueue_style( 'evusel-custom-styles' );
	wp_register_script( 'evusel-custom-scripts', plugins_url( 'js/seetickets-custom-scripts.js', __FILE__ ), array( 'jquery' ), null, true );
	wp_enqueue_script( 'evusel-custom-scripts' );
	wp_localize_script(
		'evusel-custom-scripts',
		'evusel_ajax_obj',
		array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'evusel-nonce' ),
		)
	);

	wp_register_script( 'swiper-bundle-js', plugins_url( 'js/vendor/swiper-bundle.min.js', __FILE__ ), array(), null, true );
	wp_register_script( 'evusel-swiper-init', plugins_url( "js/seetickets-swiper-init$min.js", __FILE__ ), array( 'swiper-bundle-js' ), null, true );
	wp_localize_script(
		'evusel-swiper-init',
		'evuselSliderSettings',
		array(
			'autoplaySlider' => $evuselConfig->get( 'shortcodes.slider.autoplay' ) === 'on' ? 'yes' : 'no',
		)
	);

	wp_register_style( 'swiper-bundle-css', plugins_url( 'css/vendor/swiper-bundle.min.css', __FILE__ ), array() );

	$columnAmount        = $evuselConfig->get( 'shortcodes.list_view.column_amount' );
	$dimensionsPerColumn = $evuselConfig->get( 'imageDimensionsPerColumn' );

	wp_register_script( 'see-calendar-js', plugins_url( "js/see-calendar$min.js", __FILE__ ), array( 'jquery' ), null, true );
	wp_register_script( 'see-list-js', plugins_url( "js/see-list$min.js", __FILE__ ), array( 'jquery' ), null, true );
	wp_register_script( 'pagination-js', plugins_url( "js/vendor/pagination$min.js", __FILE__ ), array( 'jquery' ), null, true );
	wp_localize_script(
		'evusel-custom-scripts',
		'evuselListSettings',
		array(
			'imageWidth'              => $dimensionsPerColumn[ $columnAmount ]['imageWidth'],
			'gridWidth'               => $dimensionsPerColumn[ $columnAmount ]['gridWidth'],
			'gridImageContainerStyle' => $evuselConfig->get( 'event_image_style' ),
		)
	);
}

// Check if required plugins are active
/**
 * Check if required plugins are active.
 *
 * @return bool True if required plugins are active, false otherwise.
 */
function evusel_required_plugins_active() {
	$activePlugins = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );
	return in_array( 'advanced-custom-fields/acf.php', $activePlugins ) ||
		in_array( 'advanced-custom-fields-pro/acf.php', $activePlugins );
}

/**
 * Display warning if required plugins are not active.
 *
 * @return void
 */
function evusel_required_plugins_warning() {
	$warning = "<div class='notice notice-error'>
    <p>Please install either <a href='https://wordpress.org/plugins/advanced-custom-fields/' target='_blank'><b>Advanced Custom Fields</b></a> or
    <a href='https://www.advancedcustomfields.com/pro/' target='_blank'><b>Advanced Custom Fields Pro</b></a> to access Eventim US' features.</p>
    <p><span class='dashicons dashicons-info-outline'></span> If you installed ACF or ACF Pro to a non-standard directory, please let us know.<p>
    </div>";

	echo esc_html( $warning );
}

/**
 * since 0.27.0b
 *
 * @return void
 */
function evusel_deactivate() {
	global $evuselConfig;
	if ( $evuselConfig->get( 'cleanup_on_deactivation' ) === 'on' ) {

		// Delete Events
		$seeEvents = get_posts(
			array(
				'numberposts'   => -1,
				'post_type'     => 'seetickets-event',
				'no_found_rows' => true,
			)
		);
		foreach ( $seeEvents as $seeEvent ) {
			wp_delete_post( $seeEvent->ID, true );
		}

		// Delete categories and tags
		$categoriesAndTags = get_terms(
			array(
				'taxonomy'   => array(
					'seetickets-event-category',
					'seetickets-event-tag',
				),
				'hide_empty' => false,
			)
		);

		foreach ( $categoriesAndTags as $categoryOrTag ) {
			wp_delete_term( $categoryOrTag->term_id, $categoryOrTag->taxonomy );
		}
	}
    //phpcs:ignore WordPressVIPMinimum.Functions.RestrictedFunctions.flush_rewrite_rules_flush_rewrite_rules
	flush_rewrite_rules();
}

/**
 * Remove all events and related data.
 *
 * @return void
 */
function evusel_remove_all() {

	$seeEvents = get_posts(
		array(
			'numberposts'   => -1,
			'post_type'     => 'seetickets-event',
			'no_found_rows' => true,
		)
	);
	foreach ( $seeEvents as $seeEvent ) {
		wp_delete_post( $seeEvent->ID, true );
	}

	// Delete categories and tags
	$categoriesAndTags = get_terms(
		array(
			'taxonomy'   => array(
				'seetickets-event-category',
				'seetickets-event-tag',
			),
			'hide_empty' => false,
		)
	);

	foreach ( $categoriesAndTags as $categoryOrTag ) {
		wp_delete_term( $categoryOrTag->term_id, $categoryOrTag->taxonomy );
	}
}


register_deactivation_hook( __FILE__, 'evusel_deactivate' );

/**
 * @param string  $postid
 * @param WP_Post $post
 * @since 0.27.0b
 * @return void
 */
function evusel_delete_attachments_on_event_delete( $postid, $post ) {
	global $evuselConfig;
	if ( $post->post_type === 'seetickets-event' && $evuselConfig->get( 'cleanup_on_deactivation' ) === 'on' ) {
		$attachments = get_attached_media( 'image', $postid );
		foreach ( $attachments as $attachment ) {
			wp_delete_attachment( $attachment->ID, true );
		}
	}
}
add_action( 'before_delete_post', 'evusel_delete_attachments_on_event_delete', 10, 2 );

/**
 * Save plugin settings.
 *
 * @return void
 */
function evusel_save_settings() {
	global $evuselConfig;

	$posted_nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
	if ( empty( $posted_nonce ) || ! wp_verify_nonce( $posted_nonce, $evuselConfig::NONCE_CODE ) ) {
		wp_die( esc_html__( 'Security check failed.', 'eventim-us-event-listings' ) );
	}

	if ( ! empty( $_POST['evusel_settings'] ) && is_array( $_POST['evusel_settings'] ) ) {
		$settings = map_deep( wp_unslash( $_POST['evusel_settings'] ), 'sanitize_text_field' );

		if ( ! isset( $settings['shortcodes']['calendar_view']['show_empty_months'] ) ) {
			$settings['shortcodes']['calendar_view']['show_empty_months'] = 'off';
		}

		$savedSettings = $evuselConfig->get( 'api.client_credentials' );
		$newSettings   = isset( $settings['api']['client_credentials'] ) ? $settings['api']['client_credentials'] : array();

		$removedClientIds = array();
		foreach ( $savedSettings as $savedCredentials ) {
			$found = false;
			foreach ( $newSettings as $newCredentials ) {
				if ( $savedCredentials['client_id'] === $newCredentials['client_id'] ) {
					$found = true;
					break;
				}
			}
			if ( ! $found ) {
				$removedClientIds[] = $savedCredentials['client_id'];
			}
		}

		if ( ! empty( $removedClientIds ) ) {
			evusel_delete_obsolete_terms( $removedClientIds );
			evusel_delete_obsolete_events( $removedClientIds );
		}

		$evuselConfig->setOptions( $settings );
		$evuselConfig->save();
	}

	wp_safe_redirect( admin_url( 'admin.php?page=eventim-us-settings' ) );
	exit;
}
