<?php
/**
 * Manage My Calendar templates.
 *
 * @category Core
 * @package  My Calendar
 * @author   Joe Dolson
 * @license  GPLv3
 * @link     https://www.joedolson.com/my-calendar/
 */

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

/**
 * Save template changes.
 */
function mc_templates_do_edit() {
	$legacy_templating = ( 'true' === mc_get_option( 'disable_legacy_templates' ) ) ? false : true;
	if ( isset( $_GET['page'] ) && 'my-calendar-design' === $_GET['page'] && $legacy_templating ) {
		if ( ! empty( $_POST ) ) {
			$nonce = $_REQUEST['_wpnonce'];
			if ( ! wp_verify_nonce( $nonce, 'my-calendar-nonce' ) ) {
				wp_die( 'My Calendar: Security check failed' );
			}
		}
		if ( isset( $_POST['mc_template_key'] ) ) {
			$key = sanitize_text_field( $_POST['mc_template_key'] );
		} else {
			$key = isset( $_GET['mc_template'] ) ? sanitize_text_field( $_GET['mc_template'] ) : '';
		}
		if ( isset( $_POST['delete'] ) ) {
			delete_option( 'mc_ctemplate_' . $key );
			wp_safe_redirect( admin_url( 'admin.php?page=my-calendar-design&action=deleted#my-calendar-templates' ) );
		} else {
			if ( mc_is_core_template( $key ) && isset( $_POST['add-new'] ) ) {
				wp_safe_redirect( admin_url( 'admin.php?page=my-calendar-design&action=duplicate#my-calendar-templates' ) );
			} else {
				if ( mc_is_core_template( $key ) && isset( $_POST['mc_template'] ) ) {
					// Curly braces are not allowed in style attributes, so replace plain color template tags with invalid color before sanitizing.
					$template = ( ! empty( $_POST['mc_template'] ) ) ? wp_kses_post( wp_unslash( str_replace( array( '{color}', '{inverse}' ), array( '#fff1a', '#000a1' ), $_POST['mc_template'] ) ) ) : '';
					$template = mc_kses_replacement( $template, $_POST['mc_template'] );
					// Restore template tag after sanitizing.
					$template          = str_replace( array( '#fff1a', '#000a1' ), array( '{color}', '{inverse}' ), $template );
					$templates         = mc_get_option( 'templates', array() );
					$templates[ $key ] = $template;
					mc_update_option( 'templates', $templates );
					mc_update_option( 'use_' . $key . '_template', ( empty( $_POST['mc_use_template'] ) ? 0 : 1 ) );
					wp_safe_redirect( esc_url_raw( admin_url( 'admin.php?page=my-calendar-design&action=core&mc_template=' . $key . '#my-calendar-templates' ) ) );
				} elseif ( isset( $_POST['mc_template'] ) ) {
					// Curly braces are not allowed in style attributes, so replace plain color template tags with invalid color before sanitizing.
					$template = ( ! empty( $_POST['mc_template'] ) ) ? wp_kses_post( wp_unslash( str_replace( array( '{color}', '{inverse}' ), array( '#fff1a', '#000a1' ), $_POST['mc_template'] ) ) ) : '';
					// Restore template tag after sanitizing.
					$template = str_replace( array( '#fff1a', '#000a1' ), array( '{color}', '{inverse}' ), $template );
					if ( mc_key_exists( $key ) ) {
						$key = mc_update_template( $key, $template );
					} else {
						$key = mc_create_template( $template, $_POST );
					}
					wp_safe_redirect( esc_url_raw( admin_url( 'admin.php?page=my-calendar-design&action=custom&mc_template=' . $key . '#my-calendar-templates' ) ) );
				}
			}
		}
	}
}
add_action( 'admin_init', 'mc_templates_do_edit' );

/**
 * Documentation for PHP templates.
 */
function mc_php_templates_docs() {
	$transient = get_transient( 'mc_file_copy' );
	if ( $transient ) {
		$message = $transient['message'];
		$type    = $transient['type'];
		wp_admin_notice( $message, array( 'type' => $type ) );
		delete_transient( 'mc_file_copy' );
	}
	$theme        = wp_get_theme();
	$theme_name   = $theme->get( 'Name' );
	$theme_parent = $theme->get( 'Template' );
	if ( '' === $theme_parent ) {
		wp_admin_notice(
			// translators: The name of the currently active theme.
			sprintf( __( 'Your current theme, %s, is not a child theme. Updates to your theme will delete custom My Calendar templates.', 'my-calendar' ), $theme_name ),
			array(
				'type' => 'error',
			)
		);
	}

	$intro     = '<p>' . __( 'To customize templates, copy one or more of the following files into your theme directory.', 'my-calendar' ) . '</p>';
	$intro    .= '<p><a href="https://docs.joedolson.com/my-calendar/php-templates/">' . __( 'Read the documentation.', 'my-calendar' ) . '</a></p>';
	$templates = array(
		'event'    => array(
			'calendar-title',
			'calendar',
			'card-title',
			'card',
			'list-title',
			'list',
			'mini-title',
			'mini',
			'single-title',
			'single',
			'next',
			'now',
			'today',
			'upcoming',
		),
		'location' => array(
			'single',
		),
	);
	$output    = '';
	foreach ( $templates as $type => $template ) {
		$base    = 'mc-templates/' . $type;
		$output .= '<li><code>/' . $base . '</code><ul>';
		foreach ( $template as $temp ) {
			$exists    = mc_template_exists( '/' . $base . '/' . $temp . '.php' );
			$edit_link = ( $exists ) ? add_query_arg( 'file', $base . '/' . $temp . '.php', admin_url( 'theme-editor.php' ) ) : '';
			$id        = 'template_' . $type . '-' . $temp;
			$nonce     = wp_nonce_field( 'mc-copy-file', '_wpnonce', true, false );
			$button    = '<form method="post">' . $nonce . '<input type="hidden" name="mc_file_template" value="' . $type . '/' . $temp . '"><button type="submit" class="button button-compact" aria-describedby="' . $id . '">Copy to Theme</button></form>';
			$append    = ( $exists ) ? '<span><span class="dashicons dashicons-yes" aria-hidden-"true"></span> <a href="' . esc_url( $edit_link ) . '">' . __( 'Edit in Theme', 'my-calendar' ) . '</a></span></span>' : $button;
			$output   .= '<li>' . $append . '<code id="' . $id . '">/' . $base . '/' . $temp . '.php' . '</code></li>';
		}
		$output .= '</ul></li>';
	}
	$file_list = '<ul class="mc-file-list">' . $output . '</ul>';
	$file_list = '<h3>' . __( 'Available Templates', 'my-calendar' ) . '</h3>' . $file_list;

	return $intro . $file_list;
}

/**
 * Copy a template from the plugin into the theme.
 */
function mc_move_template_to_theme_dir() {
	if ( isset( $_POST['mc_file_template'] ) ) {
		$nonce = $_REQUEST['_wpnonce'];
		if ( ! wp_verify_nonce( $nonce, 'mc-copy-file' ) ) {
			wp_die( 'My Calendar: Security check failed.' );
		}
		// Value should be a slash separated directory and filename, without extension.
		$template        = array_map( 'sanitize_file_name', explode( '/', $_POST['mc_file_template'] ) );
		$file            = $template[1];
		$type            = $template[0];
		$mc_template     = plugin_dir_path( __FILE__ ) . 'mc-templates/' . $type . '/' . $file . '.php';
		$custom_template = get_template_directory() . '/mc-templates/' . $type . '/' . $file . '.php';
		$transient       = false;

		global $wp_filesystem;
		require_once ABSPATH . '/wp-admin/includes/file.php';
		WP_Filesystem();

		if ( ! $wp_filesystem->exists( $mc_template ) ) {
			$transient = __( 'My Calendar template not found.', 'my-calendar' );
			$transient = array(
				'message' => $transient,
				'type'    => 'error',
			);
		}
		if ( $wp_filesystem->exists( $custom_template ) ) {
			$transient = __( 'My Calendar template already exists in the target theme.', 'my-calendar' );
			$transient = array(
				'message' => $transient,
				'type'    => 'error',
			);
		}
		if ( ! $transient ) {
			// If directories don't exist yet, create them.
			if ( ! $wp_filesystem->exists( get_template_directory() . '/mc-templates/' ) ) {
				$wp_filesystem->mkdir( get_template_directory() . '/mc-templates/' );
			}
			if ( ! $wp_filesystem->exists( get_template_directory() . '/mc-templates/' . $type . '/' ) ) {
				$wp_filesystem->mkdir( get_template_directory() . '/mc-templates/' . $type . '/' );
			}
			// Attempt to copy file.
			if ( ! $wp_filesystem->copy( $mc_template, $custom_template ) ) {
				$transient = __( 'Failed to copy My Calendar template into theme directory.', 'my-calendar' );
				$transient = array(
					'message' => $transient,
					'type'    => 'error',
				);
			} else {
				// translators: Name of template file copied.
				$transient = sprintf( __( 'My Calendar template %s has been copied to your theme.', 'my-calendar' ), '<code>' . $type . '/' . $file . '.php</code>' );
				$transient = array(
					'message' => $transient,
					'type'    => 'success',
				);
			}
		}
		set_transient( 'mc_file_copy', $transient, 15 );
	}
}
add_action( 'init', 'mc_move_template_to_theme_dir' );

/**
 * Check whether a template already exists in the custom theme directory.
 *
 * @param string $path Template path.
 *
 * @return bool
 */
function mc_template_exists( $path ) {
	global $wp_filesystem;
	require_once ABSPATH . '/wp-admin/includes/file.php';
	WP_Filesystem();

	$path = get_template_directory() . $path;
	if ( $wp_filesystem->exists( $path ) ) {
		return true;
	}

	return false;
}

/**
 * Throw an admin notice if PHP templates are enabled but a legacy template is still active.
 */
function mc_legacy_admin_notice() {
	if ( isset( $_GET['page'] ) && 'my-calendar-design' === $_GET['page'] ) {
		$legacy_templating = ( 'true' === mc_get_option( 'disable_legacy_templates' ) ) ? false : true;
		if ( ! $legacy_templating ) {
			$grid_template   = ( mc_get_option( 'use_grid_template' ) === '1' ) ? true : false;
			$list_template   = ( mc_get_option( 'use_list_template' ) === '1' ) ? true : false;
			$mini_template   = ( mc_get_option( 'use_mini_template' ) === '1' ) ? true : false;
			$card_template   = ( mc_get_option( 'use_card_template' ) === '1' ) ? true : false;
			$single_template = ( mc_get_option( 'use_details_template' ) === '1' ) ? true : false;
			if ( $grid_template || $list_template || $mini_template || $card_template || $single_template ) {
				$args = array(
					'type' => 'warning',
				);
				wp_admin_notice(
					sprintf(
						// translators: URL for help document on this topic.
						__( 'You have PHP templating enabled, but a legacy template is also enabled. The legacy template will override your PHP template. <a href="%s">Fix this issue</a>', 'my-calendar' ),
						'https://docs.joedolson.com/my-calendar/disabling-legacy-templates/'
					),
					$args
				);
			}
		}
	}
}
add_action( 'admin_notices', 'mc_legacy_admin_notice' );

/**
 * Template editing page.
 */
function mc_templates_edit() {
	if ( ! current_user_can( 'mc_edit_templates' ) ) {
		echo wp_kses_post( '<p>' . __( 'You do not have permission to customize templates on this site.', 'my-calendar' ) . '</p>' );
		return;
	}
	if ( 'true' === mc_get_option( 'disable_legacy_templates' ) ) {
		echo wp_kses( mc_php_templates_docs(), mc_kses_elements() );
		return;
	}
	$templates = mc_get_option( 'templates', array() );
	$key       = ( isset( $_GET['mc_template'] ) ) ? sanitize_text_field( $_GET['mc_template'] ) : false;

	if ( isset( $_GET['action'] ) && 'delete' === $_GET['action'] ) {
		mc_show_notice( __( 'Custom template deleted', 'my-calendar' ), true, false, 'success' );
		$key = '';
	} else {
		if ( mc_is_core_template( $key ) && isset( $_GET['action'] ) && 'duplicate' === $_GET['action'] ) {
			mc_show_error( __( 'Custom templates cannot have the same key as a core template', 'my-calendar' ) );
		} else {
			if ( mc_is_core_template( $key ) && isset( $_GET['action'] ) && 'core' === $_GET['action'] ) {
				// Translators: unique key for template.
				mc_show_notice( sprintf( __( '%s Template saved', 'my-calendar' ), ucfirst( $key ) ), true, false, 'success' );
			} elseif ( isset( $_GET['action'] ) && 'custom' === $_GET['action'] ) {
				mc_show_notice( __( 'Custom Template saved', 'my-calendar' ), true, false, 'success' );
			}
		}
	}

	$template = ( mc_is_core_template( $key ) ) ? $templates[ $key ] : mc_get_custom_template( $key );
	$template = wp_unslash( $template );
	$core     = mc_admin_template_description( $key );
	if ( $key ) {
		?>
	<div class="mc-postbox" id="mc-edit-template">
		<h2>
		<?php
		$heading = ( 'add-new' === $key ) ? __( 'Add New Template', 'my-calendar' ) : __( 'Edit Template', 'my-calendar' );
		echo esc_html( $heading );
		?>
		</h2>
		<div class="mc-inside">
			<?php echo ( '' !== $core ) ? wp_kses_post( "<div class='template-description'>$core</div>" ) : ''; ?>
			<form method="post" action="<?php echo esc_url( add_query_arg( 'mc_template', $key, admin_url( 'admin.php?page=my-calendar-design' ) ) ); ?>#my-calendar-templates">
				<div>
					<input type="hidden" name="_wpnonce" value="<?php echo esc_attr( wp_create_nonce( 'my-calendar-nonce' ) ); ?>"/>
				</div>
			<?php
			if ( 'add-new' === $key ) {
				?>
				<p>
					<label for="mc_template_key"><?php esc_html_e( 'Template Description (required)', 'my-calendar' ); ?></label><br />
					<input type="text" class="widefat" name="mc_template_key" id="mc_template_key" value="" required />
				</p>
				<p>
					<label for="mc_template"><?php esc_html_e( 'Custom Template', 'my-calendar' ); ?></label><br/>
					<textarea id="mc_template" name="mc_template" class="template-editor widefat" rows="16" cols="76"></textarea>
				</p>
				<p>
					<input type="submit" name="save" class="button-primary" value="<?php esc_attr_e( 'Add Template', 'my-calendar' ); ?>" /> <a class="button-secondary" href="<?php echo esc_url( admin_url( 'admin.php?page=my-calendar-design' ) ); ?>#my-calendar-templates"><?php esc_html_e( 'Cancel', 'my-calendar' ); ?></a>
				</p>
				<?php
			} else {
				if ( mc_is_core_template( $key ) ) {
					?>
				<p>
					<input type="checkbox" id="mc_use_template" name="mc_use_template" value="1" <?php checked( mc_get_option( 'use_' . $key . '_template' ), '1' ); ?> /> <label for="mc_use_template"><?php esc_html_e( 'Use this template', 'my-calendar' ); ?></label>
				</p>
					<?php
				}
				?>
				<p>
					<label for="mc_template">
					<?php
					// Translators: template type.
					printf( esc_html__( 'Custom Template (%s)', 'my-calendar' ), esc_html( $key ) );
					?>
					</label><br/>
					<textarea id="mc_template" name="mc_template" class="template-editor widefat" rows="16" cols="76"><?php echo esc_textarea( $template ); ?></textarea>
				</p>
				<p>
					<input type="submit" name="save" class="button-primary" value="<?php esc_attr_e( 'Update Template', 'my-calendar' ); ?>" />
				<?php if ( ! mc_is_core_template( $key ) ) { ?>
					<input type="submit" name="delete" class="button-secondary" value="<?php esc_attr_e( 'Delete Template', 'my-calendar' ); ?>" />
				<?php } ?>
				</p>
			<?php } ?>
			</form>
		</div>
	</div>
		<?php
	}
	?>
	<div class="ui-sortable meta-box-sortables" id="core-templates">
		<div class="mc-postbox">
			<h2><?php esc_html_e( 'Core Templates', 'my-calendar' ); ?></h2>
			<div class="mc-inside">
			<?php
			echo wp_kses( mc_list_core_templates( $key ), mc_kses_elements() );
			?>
			</div>
		</div>
	</div>
	<div class="ui-sortable meta-box-sortables">
		<div class="mc-postbox">
			<h2><?php esc_html_e( 'Custom Templates', 'my-calendar' ); ?></h2>
			<div class="mc-inside">
			<?php
			echo wp_kses( mc_list_custom_templates( $key ), mc_kses_elements() );
			echo ( 'add-new' !== $key ) ? wp_kses_post( '<p><a class="button" href="' . esc_url( add_query_arg( 'mc_template', 'add-new', admin_url( 'admin.php?page=my-calendar-design' ) ) ) . '#my-calendar-templates">' . __( 'Add Custom Template', 'my-calendar' ) . '</a></p>' ) : '';
			?>
			</div>
		</div>
	</div>
	<?php
}

/**
 * Get template tags for use in previews.
 *
 * @param int|bool $mc_id Event occurrence id.
 * @param string   $return_type Type of data to return.
 *
 * @return array|int
 */
function mc_get_template_tag_preview( $mc_id, $return_type = 'array' ) {
	$event = ( 'array' === $return_type ) ? array() : 0;
	$data  = array();
	if ( ! isset( $_GET['mc-event'] ) && ! $mc_id ) {
		$args   = array(
			'before' => 1,
			'after'  => 1,
		);
		$events = mc_get_all_events( $args );
		if ( isset( $events[0] ) ) {
			$event = $events[0];
			$mc_id = $event->occur_id;
		}
	} else {
		$mc_id = ( $mc_id ) ? $mc_id : absint( $_GET['mc-event'] );
		$event = mc_get_event( $mc_id );
	}
	if ( $event ) {
		$data = mc_create_tags( $event );
	}

	return ( 'array' === $return_type ) ? $data : $mc_id;
}

/**
 * Display a specific template rendered.
 *
 * @param string   $template Template identifier.
 * @param int|bool $mc_id Event occurrence ID.
 *
 * @return string
 */
function mc_display_template_preview( $template, $mc_id = false ) {
	$data = mc_get_template_tag_preview( $mc_id );
	if ( empty( $data ) ) {
		return '';
	}
	$temp   = mc_get_template( $template );
	$output = mc_draw_template( $data, $temp );
	$output = html_entity_decode( $output );
	$class  = ( 'list' === $template ) ? 'list-event' : 'calendar-event';
	$class  = ( 'mini' === $template ) ? 'mini-event' : $class;
	$class  = ( 'card' === $template ) ? 'card-event' : $class;
	$class  = ( 'details' === $template ) ? 'single-event' : $class;

	return '<div class="mc-main ' . $class . ' ' . $template . '">' . $output . '</div>';
}

/**
 * Display a list of all available template tags.
 *
 * @param int|bool $mc_id Event occurence ID.
 * @param string   $render 'code' or 'html'.
 *
 * @return string
 */
function mc_display_template_tags( $mc_id = false, $render = 'code' ) {
	$data          = mc_get_template_tag_preview( $mc_id );
	$output        = '';
	$empty         = '';
	$oddball       = '';
	$php_templates = ( 'true' === mc_get_option( 'disable_legacy_templates' ) ) ? true : false;
	// Translators: Event title being shown.
	$post_title = sprintf( __( 'Template tags for &ldquo;%1$s&rdquo;, on %2$s', 'my-calendar' ), $data['title'], $data['date'] );

	ksort( $data );
	if ( empty( $data ) ) {
		return __( 'Template tag index will display after you create an event.', 'my-calendar' );
	}
	// In preview, don't show all items.
	$skipping = array(
		'author_id',
		'cat_id',
		'icon_html', // Now an alias for `icon`.
		'category_id',
		'dateid',
		'duration',
		'event_span',
		'dtend',
		'dtstart',
		'group',
		'guid',
		'host_id',
		'ical_categories',
		'ical_category',
		'ical_desc',
		'ical_end',
		'ical_location',
		'ical_start',
		'ical_recur',
		'event_status',
		'id',
		'location_source',
		'post',
		'shortdesc',
		'repeats',
		'skip_holiday',
		'term',
		'description',
		'description_raw',
		'description_stripped',
		'shortdesc_raw',
		'shortdesc_stripped',
		'details_ical',
		'ical_date_end',
		'ical_date_start',
		'ical_excerpt',
		'ical_location',
	);
	foreach ( $data as $key => $value ) {
		$uncommon = false;
		if ( in_array( $key, $skipping, true ) ) {
			if ( 'preview' === $render ) {
				continue;
			} else {
				$uncommon = true;
			}
		}
		if ( is_array( $value ) ) {
			$value = implode( ', ', $value );
		}
		$tag        = ( $php_templates ) ? 'mc_template_tag( $event, ' . "'" . $key . "'" . ' );' : '{' . $key . '}';
		$tag_output = ( 'code' === $render ) ? '<pre>' . esc_html( $value ) . '</pre>' : wp_kses( $value, mc_kses_elements() );
		if ( '' === $value ) {
			$empty .= '<section class="mc-template-card"><div class="mc-tag-' . $key . '"><code>' . $tag . '</code></div>';
			$empty .= '<div class="mc-output-' . $key . '">' . $tag_output . '</div></section>';
		} elseif ( true === $uncommon ) {
			$oddball .= '<section class="mc-template-card"><div class="mc-tag mc-tag-' . $key . '"><code>' . $tag . '</code></div>';
			$oddball .= '<div class="mc-output mc-output-' . $key . '">' . $tag_output . '</div></section>';
		} else {
			$output .= '<section class="mc-template-card"><div class="mc-tag mc-tag-' . $key . '"><code>' . $tag . '</code></div>';
			$output .= '<div class="mc-output mc-output-' . $key . '">' . $tag_output . '</div></section>';
		}
	}
	$output_uncommon = '';
	if ( '' !== $oddball ) {
		$output_uncommon = '<h3>' . __( 'Uncommon Template Tags', 'my-calendar' ) . '</h3><div class="mc-template-cards">' . $oddball . '</div>';
	}

	return '<h3>' . $post_title . '</h3><div class="mc-template-cards">' . $output . '</div><h3>' . __( 'Template tags without values for this event', 'my-calendar' ) . '</h3><div class="mc-template-cards">' . $empty . '</div>' . $output_uncommon;
}

/**
 * Get stored data for custom template
 *
 * @param string $key Template unique key.
 *
 * @return string template
 */
function mc_get_custom_template( $key ) {
	$return = get_option( "mc_ctemplate_$key" );

	return $return;
}

/**
 * Check whether key exists in database
 *
 * @param string $key Template unique key.
 *
 * @return boolean
 */
function mc_key_exists( $key ) {
	// Keys are md5 hashed, so should always be 32 chars.
	if ( 32 !== strlen( $key ) ) {
		return false;
	}

	if ( 'missing' !== get_option( "mc_ctemplate_$key", 'missing' ) ) {
		return true;
	}

	return false;
}

/**
 * Create a new template from posted data. If this template key already exists, will update existing.
 *
 * @param string $template Full template.
 * @param array  $post POST data or array of relevant data.
 *
 * @return string $key
 */
function mc_create_template( $template, $post = array() ) {
	$key         = md5( $template );
	$description = wp_strip_all_tags( $post['mc_template_key'] );
	update_option( "mc_template_desc_$key", $description );
	update_option( "mc_ctemplate_$key", $template );

	return $key;
}

/**
 * Update an existing template from posted data
 *
 * @param string $key template key.
 * @param string $template full template.
 *
 * @return string $key
 */
function mc_update_template( $key, $template ) {
	update_option( "mc_ctemplate_$key", $template );

	return $key;
}

/**
 * Get description of current key
 *
 * @param string $key Template unique key.
 *
 * @return string
 */
function mc_admin_template_description( $key ) {
	if ( 'add-new' === $key ) {
		return '';
	}

	$return = '';
	switch ( $key ) {
		case 'grid':
			$return = __( '<strong>Core Template:</strong> used in the details popup in the main calendar view.', 'my-calendar' );
			break;
		case 'details':
			$return = __( '<strong>Core Template:</strong> used on the single event view.', 'my-calendar' );
			break;
		case 'list':
			$return = __( '<strong>Core Template:</strong> used when viewing events in the main calendar list view.', 'my-calendar' );
			break;
		case 'mini':
			$return = __( '<strong>Core Template:</strong> used in popups for the mini calendar.', 'my-calendar' );
			break;
		case 'card':
			$return = __( '<strong>Core Template:</strong> used for event display in the Card view.', 'my-calendar' );
			break;
	}

	if ( ! mc_is_core_template( $key ) ) {
		$return = wp_strip_all_tags( wp_unslash( get_option( "mc_template_desc_$key" ) ) );
	}

	return wpautop( $return );
}

/**
 * List of core templates available
 *
 * @param string $current Currently visible.
 *
 * @return string
 */
function mc_list_core_templates( $current = '' ) {
	$check           = "<span class='dashicons dashicons-yes' aria-hidden='true'></span><span>" . __( 'Enabled', 'my-calendar' ) . '</span>';
	$uncheck         = "<span class='dashicons dashicons-no' aria-hidden='true'></span><span>" . __( 'Not Enabled', 'my-calendar' ) . '</span>';
	$switched        = ( isset( $_POST['mc_use_template'] ) ) ? true : false;
	$type            = ( isset( $_GET['mc_template'] ) ) ? $_GET['mc_template'] : '';
	$grid_enabled    = ( ( 'grid' === $type && $switched ) || mc_get_option( 'use_grid_template' ) === '1' ) ? $check : $uncheck;
	$list_enabled    = ( ( 'list' === $type && $switched ) || mc_get_option( 'use_list_template' ) === '1' ) ? $check : $uncheck;
	$mini_enabled    = ( ( 'mini' === $type && $switched ) || mc_get_option( 'use_mini_template' ) === '1' ) ? $check : $uncheck;
	$card_enabled    = ( ( 'card' === $type && $switched ) || mc_get_option( 'use_card_template' ) === '1' ) ? $check : $uncheck;
	$details_enabled = ( ( 'details' === $type && $switched ) || mc_get_option( 'use_details_template' ) === '1' ) ? $check : $uncheck;

	$list = "
	<table class='widefat'>
		<thead>
			<tr><th scope='col'>" . __( 'Template', 'my-calendar' ) . '</th><th scope="col">' . __( 'Status', 'my-calendar' ) . '</th><th scope="col">' . __( 'Description', 'my-calendar' ) . "</th>
		</thead>
		<tbody>
			<tr class='alternate'>
				<td><a " . ( ( 'grid' === $current ) ? ' aria-current="true"' : '' ) . " href='" . esc_url( add_query_arg( 'mc_template', 'grid', admin_url( 'admin.php?page=my-calendar-design' ) ) ) . "#my-calendar-templates'>grid</a></td><td>$grid_enabled</td><td>" . mc_admin_template_description( 'grid' ) . '</td>
			</tr>
			<tr>
				<td><a ' . ( ( 'list' === $current ) ? ' aria-current="true"' : '' ) . " href='" . esc_url( add_query_arg( 'mc_template', 'list', admin_url( 'admin.php?page=my-calendar-design' ) ) ) . "#my-calendar-templates'>list</a></td><td>$list_enabled</td><td>" . mc_admin_template_description( 'list' ) . "</td>
			</tr>
			<tr class='alternate'>
				<td><a " . ( ( 'mini' === $current ) ? ' aria-current="true"' : '' ) . " href='" . esc_url( add_query_arg( 'mc_template', 'mini', admin_url( 'admin.php?page=my-calendar-design' ) ) ) . "#my-calendar-templates'>mini</a></td><td>$mini_enabled</td><td>" . mc_admin_template_description( 'mini' ) . '</td>
			</tr>
			<tr>
				<td><a ' . ( ( 'card' === $current ) ? ' aria-current="true"' : '' ) . " href='" . esc_url( add_query_arg( 'mc_template', 'card', admin_url( 'admin.php?page=my-calendar-design' ) ) ) . "#my-calendar-templates'>card</a></td><td>$card_enabled</td><td>" . mc_admin_template_description( 'card' ) . '</td>
			</tr>
			<tr class="alternate">
				<td><a ' . ( ( 'details' === $current ) ? ' aria-current="true"' : '' ) . " href='" . esc_url( add_query_arg( 'mc_template', 'details', admin_url( 'admin.php?page=my-calendar-design' ) ) ) . "#my-calendar-templates'>details</a></td><td>$details_enabled</td><td>" . mc_admin_template_description( 'details' ) . '</td>
			</tr>
		</tbody>
	</table>';

	return $list;
}


/**
 * List of templates available
 *
 * @param string $current Currently visible template.
 *
 * @return string
 */
function mc_list_custom_templates( $current = '' ) {
	$header = "<table class='widefat'>
				<thead>
					<tr><th scope='col'>" . __( 'Template', 'my-calendar' ) . '</th><th scope="col">' . __( 'Description', 'my-calendar' ) . '</th>
				</thead>
				<tbody>';
	$body   = '';
	global $wpdb;
	$results = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . "options WHERE option_name LIKE '%mc_ctemplate_%'" );
	$class   = 'normal';
	foreach ( $results as $result ) {
		$key   = str_replace( 'mc_ctemplate_', '', $result->option_name );
		$desc  = mc_admin_template_description( $key );
		$class = ( 'alternate' === $class ) ? 'normal' : 'alternate';
		$curr  = ( $current === $key ) ? ' aria-current="true"' : '';
		$body .= "<tr class='$class'><td><a $curr href='" . esc_url( add_query_arg( 'mc_template', $key, admin_url( 'admin.php?page=my-calendar-design' ) ) ) . "#my-calendar-templates'>$key</a></td><td>$desc</td></tr>";
	}

	$list = $header . $body . '</tbody>
	</table>';

	return ( '' !== $body ) ? $list : '';
}

add_action(
	'admin_enqueue_scripts',
	function () {
		if ( ! function_exists( 'wp_enqueue_code_editor' ) ) {
			return;
		}

		if ( sanitize_title( __( 'My Calendar', 'my-calendar' ) ) . '_page_my-calendar-design' !== get_current_screen()->id ) {
			return;
		}

		if ( isset( $_GET['mc_template'] ) ) {
			// Enqueue code editor and settings for manipulating HTML.
			$settings = wp_enqueue_code_editor(
				array(
					'type'       => 'text/html',
					'codemirror' => array(
						'autoRefresh' => true,
					),
				)
			);
			// Bail if user disabled CodeMirror.
			if ( false === $settings ) {
				return;
			}

			wp_add_inline_script(
				'code-editor',
				sprintf(
					'jQuery( function() { wp.codeEditor.initialize( "mc_template", %s ); } );',
					wp_json_encode( $settings )
				)
			);
		}
	}
);
