<?php
/**
 * Dashboard and admin menu functionality.
 *
 * @package EventimUSEventListings
 */

defined( 'ABSPATH' ) || exit;

add_action( 'admin_menu', 'evusel_menu' );
/**
 * Add admin menu page for Eventim US settings.
 *
 * @return void
 */
function evusel_menu() {
	add_menu_page(
		'Eventim US',
		'Client Portal',
		'manage_options',
		'eventim-us-settings',
		'evusel_render_dashboard',
		'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0MDAgNTMzLjAxNjk0Ij4KICA8ZGVmcz4KICAgIDxzdHlsZT4KICAgICAgLmNscy0xIHsKICAgICAgICBmaWxsOiAjZmZmOwogICAgICB9CiAgICA8L3N0eWxlPgogIDwvZGVmcz4KICA8ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIi8+CiAgPGcgaWQ9IkxheWVyXzIiIGRhdGEtbmFtZT0iTGF5ZXIgMiI+CiAgICA8ZyBpZD0iQ2FscXVlXzEiIGRhdGEtbmFtZT0iQ2FscXVlIDEiPgogICAgICA8Zz4KICAgICAgICA8cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik00MDAsMTAzLjQyNTcxQzM0Mi44OTg3Niw0LjUyMzMxLDIxNi40MzI4My0yOS4zNjMyMywxMTcuNTMwNDMsMjcuNzM4MDEsMTguNjI4MDMsODQuODM5MjUtMTUuMjU4NTEsMjExLjMwNTE4LDQxLjg0MjczLDMxMC4yMDc1OEw0MDAsMTAzLjQyNTcxWiIvPgogICAgICAgIDxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTAsNDI5LjU5MTJjNTcuMTAxMjIsOTguOTAyNDEsMTgzLjU2NzE0LDEzMi43ODg5OCwyODIuNDY5NTYsNzUuNjg3NzYsOTguOTAyNDEtNTcuMTAxMjIsMTMyLjc4ODk4LTE4My41NjcxNCw3NS42ODc3Ni0yODIuNDY5NTZMMCw0MjkuNTkxMloiLz4KICAgICAgPC9nPgogICAgPC9nPgogIDwvZz4KPC9zdmc+',
		30
	);
}

/**
 * Render the main dashboard page.
 *
 * @return void
 */
function evusel_render_dashboard() {

	global $evuselConfig, $wpdb;

	$nonce = wp_create_nonce( $evuselConfig::NONCE_CODE );

	if (
		isset( $_POST['submit'] ) &&
		isset( $_POST['nonce'] ) &&
		current_user_can( 'manage_options' )
	) {
		$posted_nonce = sanitize_text_field( wp_unslash( $_POST['nonce'] ) );

		if ( wp_verify_nonce( $posted_nonce, $evuselConfig::NONCE_CODE ) ) {
			$action = sanitize_text_field( wp_unslash( $_POST['submit'] ) );

			switch ( $action ) {

				case 'Save':
					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();
					}

					break;

				/**
				 * Deprecated feed runner case.
				 *
				 * @deprecated This case is deprecated.
				 */
				case 'run_feed':
					echo wp_kses( evusel_cron_exec(), array() );
					break;
			}
		}
	}

	// Set up data for rendering.
	$categories = get_terms(
		array(
			'taxonomy' => 'seetickets-event-category',
			'get'      => 'all',
		)
	);

	$tags = get_terms(
		array(
			'taxonomy' => 'seetickets-event-tag',
			'get'      => 'all',
		)
	);

	$parameters         = $evuselConfig->get( 'shortcodes.event_search.search_parameters' );
	$selectedTags       = $evuselConfig->get( 'shortcodes.tag_filter.selected_tags' );
	$tagParameters      = $evuselConfig->get( 'shortcodes.just_announced.selected_tags' );
	$selectedCategories = $evuselConfig->get( 'shortcodes.category_filter.selected_categories' );
	$passedIf           = $evuselConfig->get( 'shortcodes.past_events.past_event_if' );

	$defaultImageId  = $evuselConfig->get( 'default_event_image_id' );
	$defaultImageUrl = intval( $defaultImageId ) > 0 ?
		wp_get_attachment_image_url( $defaultImageId, 'large', false ) :
		$evuselConfig->get( 'default_event_image' );

	$buttonLabels = get_field_object( 'field_604944373ed26' )['choices'];

	$cache_key          = 'evusel_custom_button_labels';
	$customButtonLabels = wp_cache_get( $cache_key, 'seetickets' );
	if ( false === $customButtonLabels ) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Necessary for custom labels, cached above
		$customButtonLabels = $wpdb->get_col(
			$wpdb->prepare(
				"SELECT DISTINCT meta_value FROM {$wpdb->prefix}postmeta WHERE meta_key = %s",
				'custom_ticket_status'
			)
		);
		wp_cache_set( $cache_key, $customButtonLabels, 'seetickets', HOUR_IN_SECONDS );
	}
	$customButtonLabels = array_combine( $customButtonLabels, $customButtonLabels );
	$buttonLabels       = array_merge( $buttonLabels, $customButtonLabels );

	$customButtonClasses = $evuselConfig->get( 'button_status_classes' );

    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Using WordPress core filter
	$activePlugins                    = apply_filters( 'active_plugins', get_option( 'active_plugins' ) );
	$suggestDisabingMaterialResources = in_array( 'material-design/material-design.php', $activePlugins );

	$cardLabelsOrder         = $evuselConfig->get( 'event_card_elements_order' );
	$cardLabelsOrderDefaults = $evuselConfig->get( 'event_card_elements_order', true );
	$extraCardLabels         = array_diff( $cardLabelsOrderDefaults, $cardLabelsOrder );
	$cardLabelLabels         = $evuselConfig->get( 'event_card_element_labels' );

	?>

	<div class="container display-event-listing-dashboard">
		<form method="POST" id="see-settings-form"
			action="<?php echo esc_url( get_admin_url( null, 'admin.php?page=eventim-us-settings' ) ); ?>">

			<input type="hidden" name="nonce" value="<?php echo esc_attr( $nonce ); ?>" />

			<?php include 'evusel-menu.php'; ?>

			<div id='settings-container' style="display: none;">
				<h1>Settings</h1>
				<div style="display: flex; flex-direction: column; gap: 20px;">
					<?php include 'containers/settings/block-api-credentials.php'; ?>
					<?php include 'containers/settings/block-exclude-fields-from-updating.php'; ?>
					<?php include 'containers/settings/block-default-event-image.php'; ?>
					<?php include 'containers/settings/block-multi-day-pass-events.php'; ?>
					<?php include 'containers/settings/block-link-event.php'; ?>
					<?php include 'containers/settings/block-feed-control.php'; ?>
				</div>
			</div>

			<div id='event-listing-container' style="display: none;">
				<h1>Event Listing</h1>
				<h4 style=" color: #949494;  margin: 20px 0; font-weight: 100px">
				Shortcodes in the plugin allow you to include dynamic content and functionality to your website,
				without coding skills. These shortcodes will need to be inserted onto your pages, widgets, or theme files to display the content.</h4>
				<div style="display: flex; flex-direction: column; gap: 20px;">
					<?php include 'containers/event-listing/block-list-view.php'; ?>
					<?php include 'containers/event-listing/block-calendar-view.php'; ?>
					<?php include 'containers/event-listing/block-event-slider.php'; ?>
				</div>
			</div>
	  
			<div id='filters-container' style="display: none;">
				<h1>Filters</h1>
				<h4 style=" color: #949494;  margin: 20px 0; font-weight: 100px">
				Shortcodes in the plugin allow you to include dynamic content and functionality to your website, without coding skills. These shortcodes will need to be inserted onto your pages, widgets, or theme files to display the content.</h4>
				<div style="display: flex; flex-direction: column; gap: 20px;">
					<?php include 'containers/filters/block-just-announced.php'; ?>
					<?php include 'containers/filters/block-categories.php'; ?>
					<?php include 'containers/filters/block-tags.php'; ?>
					<?php include 'containers/filters/block-search.php'; ?>
				</div>
			</div>

			<div id='color-selection-setup' style="display: none;">
				<h1>Customize</h1>
				<div style="display: flex; flex-direction: column; gap: 20px;">
					<?php include 'containers/customize/block-custom-labels.php'; ?>
					<?php include 'containers/customize/block-order-event-card-elements.php'; ?>
					<?php include 'containers/customize/block-social-media-sharing.php'; ?>
					<?php include 'containers/customize/block-event-card-design.php'; ?>
					<?php include 'containers/customize/block-custom-button-css-classes-by-status.php'; ?>
					<?php include 'containers/customize/block-force-button-text.php'; ?>
					<?php include 'containers/customize/block-custom-css-classes.php'; ?>
					<?php include 'containers/customize/block-color-customization.php'; ?>
				</div>
			</div>

			<div id='debug-setup' style="display: none;">
				<h1 id="custom-css">Debug</h1>
				<table>
					<tr>
						<th scope="row">Skip checking content for shortcodes when loading plugin scripts</th>
						<td>
							<input id="force-script-load" type="checkbox"
								name="evusel_settings[debug][force_script_load]"
								<?php echo $evuselConfig->get( 'debug.force_script_load' ) === 'on' ? 'checked' : ''; ?>>
						</td>
					</tr>
				</table>
			</div>
			<?php include 'evusel-footer.php'; ?>
		</form>
		
	<?php
	if (
			isset( $_POST['nonce'] ) &&
			isset( $_POST['see-delete'] ) &&
			current_user_can( 'manage_options' )
		) {
		$posted_nonce = sanitize_text_field( wp_unslash( $_POST['nonce'] ) );

		if ( wp_verify_nonce( $posted_nonce, $evuselConfig::NONCE_CODE ) ) {
			$see_delete = sanitize_text_field( wp_unslash( $_POST['see-delete'] ) );

			if ( $see_delete === 'all' ) {
				evusel_remove_all();
			}
		}
	}
	?>

		<p>Trigger cron manually: <a href="<?php echo esc_url( $evuselConfig->get( 'api.cron_endpoint' ) ); ?>"
				target="_blank"><?php echo esc_html( $evuselConfig->get( 'api.cron_endpoint' ) ); ?></a></p>
	</div>
	<?php
}