<?php
/**
 * Submit posts from events.
 *
 * @category Features
 * @package  My Calendar Pro
 * @author   Joe Dolson
 * @license  GPLv3
 * @link     https://www.joedolson.com/my-calendar-pro/
 */

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

/**
 * Create a post when an event is created.
 */

add_action( 'mc_update_event_post', 'my_event_post', 20, 5 );
/**
 * Save event data for post & create post.
 *
 * @param string  $event_post Event post ID.
 * @param array   $post Posted data.
 * @param array   $data Event data.
 * @param integer $new_event New Event ID.
 * @param string  $action Action being taken.
 */
function my_event_post( $event_post, $post, $data, $new_event, $action ) {
	if ( ! ( 'true' === get_option( 'mcs_create_post' ) ) ) {
		return;
	}
	// if the event save was successful.
	$options = get_option( 'mcs_event_post' );
	switch ( $options['content'] ) {
		case 'event':
			$content = "[my_calendar_event event='$new_event' template='details' list='']";
			break;
		case 'custom':
			$content = ( isset( $post['mcs_custom_content'] ) ) ? wp_kses_post( $post['mcs_custom_content'] ) : '';
			break;
		default:
			$content = $data['event_desc'];
			break;
	}
	$event   = mc_get_first_event( $new_event );
	$details = mc_create_tags( $event );
	if ( 'custom' === $options['content'] ) {
		$content = mc_draw_template( $details, apply_filters( 'mcs_new_post_template', $content, $event ) );
	}

	switch ( $options['title'] ) {
		case 'custom':
			$title = sprintf( $options['custom_title'], $data['event_title'] );
			$title = mc_draw_template( $details, $title );
			break;
		default:
			$title = $data['event_title'];
	}

	switch ( $options['author'] ) {
		case 'host':
			$auth = $data['event_host'];
			break;
		default:
			$auth = isset( $data['event_author'] ) ? $data['event_author'] : get_current_user_id();
	}

	switch ( $options['excerpt'] ) {
		case 'event_short':
			$excerpt = $data['event_short'];
			break;
		case 'auto':
			$excerpt = wp_trim_words( $data['event_desc'] );
			break;
		case 'custom':
			$excerpt = ( isset( $post['mcs_custom_content'] ) ) ? wp_kses_post( $post['mcs_custom_content'] ) : '';
			break;
		default:
			$excerpt = $data['event_short'];
	}

	if ( 'custom' === $options['excerpt'] ) {
		$excerpt = mc_draw_template( $details, apply_filters( 'mcs_new_post_template', $excerpt, $event ) );
	}

	$status = ( isset( $options['status'] ) ) ? $options['status'] : 'publish';

	switch ( $options['timestamp'] ) {
		case 'event':
			$date = strtotime( $data['event_begin'] . ' ' . $data['event_time'] );
			break;
		case 'custom':
			if ( intval( $options['custom_time'] ) < 0 ) {
				// if custom time is negative, subtract the absolute value from the event time.
				$date = strtotime( $data['event_begin'] . ' ' . $data['event_time'] ) - abs( intval( $options['custom_time'] ) );
			} else {
				// if custom time is postive, add the value to the event time.
				$date = strtotime( $data['event_begin'] . ' ' . $data['event_time'] ) + intval( $options['custom_time'] );
			}
			break;
		default:
			$date = current_time( 'timestamp' ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
	}

	$type = ( isset( $options['post_type'] ) ) ? $options['post_type'] : 'post';

	if ( 'add' === $action && ! ( isset( $post['event_source'] ) && 'post' === $post['event_source'] ) ) {
		if ( $date > current_time( 'timestamp' ) && 'publish' === $status ) { // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
			// Switch to future if this is to be published automatically. Otherwise, leave as draft.
			$status = 'future';
		}

		$my_post = array(
			'post_title'   => $title,
			'post_content' => $content,
			'post_excerpt' => $excerpt,
			'post_status'  => $status,
			'post_author'  => $auth,
			'post_name'    => sanitize_title( $title ),
			'post_date'    => gmdate( 'Y-m-d H:i:s', $date ),
			'post_type'    => $type,
		);

		$post_id = wp_insert_post( $my_post );
		// check POST data.
		$attachment_id = ( isset( $post['event_image_id'] ) && is_numeric( $post['event_image_id'] ) ) ? (int) $post['event_image_id'] : false;
		// check event object.
		if ( $attachment_id ) {
			set_post_thumbnail( $post_id, $attachment_id );
		}
		$category = mc_get_category_detail( $data['event_category'], 'category_name' );
		$taxonomy = ( isset( $options['custom_taxonomy'] ) && '' !== $options['custom_taxonomy'] ) ? $options['custom_taxonomy'] : 'category';
		wp_set_post_tags( $post_id, $category );
		wp_set_object_terms( $post_id, $category, $taxonomy );
		if ( isset( $options['custom_category'] ) && '' !== $options['custom_category'] ) {
			wp_set_object_terms( $post_id, $options['custom_category'], $taxonomy );
		}
		$mc_event_id = get_post_meta( $post_id, '_mc_event_id', true );
		if ( ! $mc_event_id ) {
			add_post_meta( $post_id, '_mc_event_id', $new_event );
		}

		add_post_meta( $event_post, '_mc_related_post', $post_id );
		/**
		 * Action when a My Calendar Pro blog post is created from an event.
		 *
		 * @hook mcp_post_published
		 *
		 * @param {int}    $post_id New post ID.
		 * @param {object} $event Event object.
		 */
		do_action( 'mcp_post_published', $post_id, $event );

		if ( 'publish' === $status ) {
			wp_publish_post( $post_id );
		}

		if ( 'true' === $options['custom_url'] && 'publish' === $status ) {
			mc_update_data( $new_event, 'event_link', get_permalink( $post_id ), '%s' );
		}
	}
}

add_filter( 'mcs_custom_settings_update', 'mcs_event_posts_update', 10, 2 );
/**
 * Update event posts settings.
 *
 * @param boolean $value Is updated.
 * @param array   $post POST data.
 *
 * @return string update info.
 */
function mcs_event_posts_update( $value, $post ) {
	// save settings.
	if ( isset( $post['event_posts_settings'] ) ) {
		$options = get_option( 'mcs_event_post' );
		if ( isset( $post['mcs_create_post'] ) ) {
			update_option( 'mcs_create_post', 'true' );
		} else {
			delete_option( 'mcs_create_post' );
		}
		$options['content']         = sanitize_textarea_field( $post['mcs_content'] );
		$options['title']           = sanitize_text_field( $post['mcs_title'] );
		$options['custom_title']    = sanitize_text_field( $post['mcs_custom_title'] );
		$options['custom_url']      = isset( $post['mcs_custom_url'] ) ? sanitize_text_field( $post['mcs_custom_url'] ) : '';
		$options['custom_category'] = isset( $post['mcs_custom_category'] ) ? sanitize_text_field( $post['mcs_custom_category'] ) : '';
		$options['custom_taxonomy'] = isset( $post['mcs_custom_taxonomy'] ) ? sanitize_text_field( $post['mcs_custom_taxonomy'] ) : '';
		$options['author']          = sanitize_text_field( $post['mcs_author'] );
		$options['excerpt']         = sanitize_textarea_field( $post['mcs_excerpt'] );
		$options['template']        = isset( $post['mcs_template'] ) ? sanitize_textarea_field( $post['mcs_template'] ) : '';
		$options['status']          = sanitize_text_field( $post['mcs_status'] );
		$options['timestamp']       = sanitize_text_field( $post['mcs_timestamp'] );
		$options['custom_time']     = isset( $post['mcs_custom_time'] ) ? sanitize_text_field( $post['mcs_custom_time'] ) : '';
		$options['type']            = sanitize_text_field( $post['mcs_type'] );
		update_option( 'mcs_event_post', $options );

		return __( 'Event Post Settings Updated', 'my-calendar-pro' );
	}

	return $value;
}

add_filter( 'mcs_settings_tabs', 'mcs_event_posts_tabs' );
/**
 * Set up settings tab for event posts.
 *
 * @param array $tabs All My Calendar pro tabs.
 *
 * @return array updated tabs.
 */
function mcs_event_posts_tabs( $tabs ) {
	$tabs['event_posts'] = __( 'Blog New Events', 'my-calendar-pro' );

	return $tabs;
}

add_filter( 'mcs_settings_panels', 'mcs_event_posts_settings' );
/**
 * Set up settings for event posts.
 *
 * @param array $panels All My Calendar pro panels.
 *
 * @return array updated panels.
 */
function mcs_event_posts_settings( $panels ) {
	$mcs_create_post     = get_option( 'mcs_create_post' );
	$options             = get_option(
		'mcs_event_post',
		array(
			'excerpt'         => '',
			'template'        => '',
			'custom_title'    => '',
			'custom_url'      => '',
			'custom_category' => '',
			'custom_taxonomy' => 'category',
			'custom_time'     => 3600,
			'content'         => '',
			'title'           => '',
			'author'          => '',
			'status'          => '',
			'timestamp'       => '',
			'type'            => '',
		)
	);
	$excerpt             = ( isset( $options['excerpt'] ) ) ? $options['excerpt'] : '';
	$mcs_template        = ( isset( $options['template'] ) ) ? $options['template'] : '';
	$mcs_custom_title    = ( isset( $options['custom_title'] ) ) ? $options['custom_title'] : 'New Event: %s';
	$mcs_custom_url      = ( isset( $options['custom_url'] ) ) ? $options['custom_url'] : 'false';
	$mcs_custom_category = ( isset( $options['custom_category'] ) ) ? $options['custom_category'] : '';
	$mcs_custom_taxonomy = ( isset( $options['custom_taxonomy'] ) ) ? $options['custom_taxonomy'] : '';
	$mcs_custom_time     = ( isset( $options['custom_time'] ) ) ? $options['custom_time'] : 3600;
	$diff                = human_time_diff( current_time( 'timestamp' ), current_time( 'timestamp' ) + (int) $mcs_custom_time ); // phpcs:ignore WordPress.DateTime.CurrentTimeTimestamp.Requested
	if ( $mcs_custom_time < 0 ) {
		// Translators: Time unit.
		$diff = sprintf( __( '<strong>%s</strong> before event happens', 'my-calendar-pro' ), $diff );
	} else {
		// Translators: Time unit.
		$diff = sprintf( __( '<strong>%s</strong> after event is published', 'my-calendar-pro' ), $diff );
	}

	if ( 'true' === $mcs_create_post ) {
		$post_types = get_post_types(
			array(
				'public'  => true,
				'show_ui' => true,
			),
			'objects'
		);
		$types      = '';
		$skip_types = array( 'mc-events', 'attachment', 'mc-locations' );
		foreach ( $post_types as $type ) {
			if ( in_array( $type->name, $skip_types, true ) ) {
				continue;
			}
			$types .= "<option value='$type->name'" . selected( $options['type'], $type->name, false ) . '>' . $type->labels->name . '</option>';
		}
		$post_taxonomies = get_taxonomies(
			array(
				'public' => true,
			),
			'objects'
		);
		$taxonomies      = '';
		foreach ( $post_taxonomies as $taxonomy ) {
			$tax   = $taxonomy->name;
			$label = $taxonomy->label;
			if ( 'mc-event-category' === $tax ) {
				continue;
			}
			$taxonomies .= "<option value='" . esc_attr( $tax ) . "'" . selected( $mcs_custom_taxonomy, $tax, false ) . '>' . $label . '</option>';
		}
		$controls = '
		<fieldset>
			<legend>' . __( 'Create Post from Events Settings', 'my-calendar-pro' ) . "</legend>
			<p>
				<label for='mcs_content'>" . __( 'Blog Post Content', 'my-calendar-pro' ) . "</label><br />
				<select name='mcs_content' id='mcs_content'>
					<option value='default'>" . __( 'Event Description', 'my-calendar-pro' ) . "</option>
					<option value='event'" . selected( $options['content'], 'event', false ) . '>' . __( 'Full Event Template', 'my-calendar-pro' ) . "</option>
					<option value='custom'" . selected( $options['content'], 'custom', false ) . '>' . __( 'Custom Content added at event creation', 'my-calendar-pro' ) . "</option>
				</select>
			</p>
			<p>
				<label for='mcs_excerpt'>" . __( 'Blog Post Excerpt', 'my-calendar-pro' ) . "</label><br />
				<select name='mcs_excerpt' id='mcs_excerpt'>
					<option value='default'>" . __( 'Event Excerpt', 'my-calendar-pro' ) . "</option>
					<option value='auto'" . selected( $excerpt, 'auto', false ) . '>' . __( 'Auto-excerpt Event Description', 'my-calendar-pro' ) . "</option>
					<option value='custom'" . selected( $excerpt, 'custom', false ) . '>' . __( 'Custom Content added at event creation', 'my-calendar-pro' ) . "</option>
				</select>
			</p>
			<p>
				<label for='mcs_title'>" . __( 'Blog Post Title', 'my-calendar-pro' ) . "</label><br />
				<select name='mcs_title' id='mcs_title'>
					<option value='default'>" . __( 'Event Title', 'my-calendar-pro' ) . "</option>
					<option value='custom'" . selected( $options['title'], 'custom', false ) . '>' . __( 'Custom Format', 'my-calendar-pro' ) . "</option>
				</select>
			</p>
			<p>
				<label for='mcs_custom_title'>" . __( 'Custom Title Format', 'my-calendar-pro' ) . "</label><br />
				<input type='text' name='mcs_custom_title' id='mcs_custom_title' value='" . esc_attr( stripslashes( $mcs_custom_title ) ) . "' />
			</p>
			<p>
				<label for='mcs_ep_template'>" . __( 'Custom Post Excerpt or Content Template', 'my-calendar-pro' ) . '</label><br />';
			// Translators: Link to template tag help.
			$note      = sprintf( __( 'Accepts <a href="%s">template tags</a>', 'my-calendar-pro' ), admin_url( 'admin.php?page=my-calendar-design#my-calendar-templates' ) );
			$controls .= "
				<textarea name='mcs_template' id='mcs_ep_template'  aria-describedby='mcs_template_note' rows='6' cols='60'>" . esc_attr( stripslashes( $mcs_template ) ) . "</textarea> <span id='mcs_template_note'>" . $note . "</span>
			</p>
			<p>
				<label for='mcs_author'>" . __( 'Blog Post Author', 'my-calendar-pro' ) . "</label><br />
				<select name='mcs_author' id='mcs_author'>
					<option value='default'>" . __( 'Event Author', 'my-calendar-pro' ) . "</option>
					<option value='host'" . selected( $options['author'], 'host', false ) . '>' . __( 'Event Host', 'my-calendar-pro' ) . "</option>
				</select>
			</p>
			<p>
				<label for='mcs_status'>" . __( 'Blog Post Status', 'my-calendar-pro' ) . "</label><br />
				<select name='mcs_status' id='mcs_status'>
					<option value='publish'>" . __( 'Published', 'my-calendar-pro' ) . "</option>
					<option value='pending'" . selected( $options['status'], 'pending', false ) . '>' . __( 'Pending', 'my-calendar-pro' ) . "</option>
					<option value='draft'" . selected( $options['status'], 'draft', false ) . '>' . __( 'Draft', 'my-calendar-pro' ) . "</option>
					<option value='private'" . selected( $options['status'], 'private', false ) . '>' . __( 'Private', 'my-calendar-pro' ) . "</option>
					<option value='future'" . selected( $options['status'], 'future', false ) . '>' . __( 'Future', 'my-calendar-pro' ) . "</option>
				</select>
			</p>
			<p class='checkbox'>
				<input type='checkbox' name='mcs_custom_url' id='mcs_custom_url' value='true' " . checked( $mcs_custom_url, 'true', false ) . " /> <label for='mcs_custom_url'>" . __( 'Use Post permalink for Event URL (if post is published)', 'my-calendar-pro' ) . "</label>
			</p>
			<p>
				<label for='mcs_type'>" . __( 'Post Type', 'my-calendar-pro' ) . "</label><br />
				<select name='mcs_type' id='mcs_type'>
					$types
				</select>
			</p>
			<fieldset>
				<legend>" . __( 'Categorize your event post', 'my-calendar-pro' ) . "</legend>
				<div class='mc-flex'>
				<p>
					<label for='mcs_custom_category'>" . __( 'Add Post Term', 'my-calendar-pro' ) . "</label><br />
					<input type='text' name='mcs_custom_category' id='mcs_custom_category' value='" . esc_attr( stripslashes( $mcs_custom_category ) ) . "' />
				</p>
				<p>
					<label for='mcs_custom_taxonomy'>" . __( 'Term Taxonomy', 'my-calendar-pro' ) . "</label><br />
					<select name='mcs_custom_taxonomy' id='mcs_custom_taxonomy'>
						$taxonomies
					</select>
				</p>
				</div>
			</fieldset>
			<fieldset>
				<legend>" . __( 'Set your post publication date', 'my-calendar-pro' ) . "</legend>
				<div class='mc-flex'>
				<p>
					<label for='mcs_timestamp'>" . __( 'Post Publish Date', 'my-calendar-pro' ) . "</label><br />
					<select name='mcs_timestamp' id='mcs_timestamp'>
						<option value='default'>" . __( 'Publication Date', 'my-calendar-pro' ) . "</option>
						<option value='event'" . selected( $options['timestamp'], 'event', false ) . '>' . __( 'Event Date', 'my-calendar-pro' ) . "</option>
						<option value='custom'" . selected( $options['timestamp'], 'custom', false ) . '>' . __( 'Custom Date', 'my-calendar-pro' ) . "</option>
					</select>
				</p>
				<p>
					<label for='mcs_custom_time'>" . __( 'Custom Post Time (in seconds)', 'my-calendar-pro' ) . "</label><br />
					<input type='text' name='mcs_custom_time' id='mcs_custom_time' value='" . esc_attr( $mcs_custom_time ) . "' aria-describedby='mcs_custom_time_diff' /> <span id='mcs_custom_time_diff'>$diff</span>
				</p>
				</div>
			</fieldset>
		</fieldset>
		";
	} else {
		$controls = "
		<div class='mcs-about'>
			<p>
				" . __( 'Set up a template and rules for automatically generating a blog post about new events.', 'my-calendar-pro' ) . "
			</p>
		</div>
		<div>
			<input type='hidden' name='mcs_content' value='" . esc_attr( $options['content'] ) . "' />
			<input type='hidden' name='mcs_excerpt' value='" . esc_attr( $options['excerpt'] ) . "' />
			<input type='hidden' name='mcs_title' value='" . esc_attr( $options['title'] ) . "' />
			<input type='hidden' name='mcs_custom_title' value='" . esc_attr( $mcs_custom_title ) . "' />
			<input type='hidden' name='mcs_author' value='" . esc_attr( $options['author'] ) . "' />
			<input type='hidden' name='mcs_status' value='" . esc_attr( $options['status'] ) . "' />
			<input type='hidden' name='mcs_timestamp' value='" . esc_attr( $options['timestamp'] ) . "' />
			<input type='hidden' name='mcs_custom_time' value='" . esc_attr( $mcs_custom_time ) . "' />
			<input type='hidden' name='mcs_type' value='" . esc_attr( $options['type'] ) . "' />
		</div>";
	}
	$panels['event_posts'] = '
		<h2>' . __( 'Post New Events as Posts', 'my-calendar-pro' ) . '</h2>
		<div class="inside">
			<p>
				<input type="checkbox" name="mcs_create_post" id="mcs_create_post" value="true" ' . checked( $mcs_create_post, 'true', false ) . '/> <label for="mcs_create_post">' . __( 'Copy new events as posts', 'my-calendar-pro' ) . '</label>
			</p>' . $controls . '
			{submit}
		</div>';

	return $panels;
}

add_filter( 'mc_event_details', 'mcs_custom_content', 10, 4 );
/**
 * Generate form within My Calendar submission forms to provide custom content for a blog post.
 *
 * @param string  $form Form HTML.
 * @param boolean $has_data Has data already.
 * @param object  $event Event object.
 * @param string  $context Current view context.
 *
 * @return string.
 */
function mcs_custom_content( $form, $has_data, $event, $context ) {
	if ( 'true' === get_option( 'mcs_create_post' ) ) {
		$options        = get_option( 'mcs_event_post' );
		$custom_content = $options['content'];
		$custom_excerpt = $options['excerpt'];
		$template       = ( isset( $options['template'] ) ) ? $options['template'] : '';
		$template       = apply_filters( 'mcs_custom_content_template', $template );

		if ( 'custom' === $custom_content xor 'custom' === $custom_excerpt ) {
			if ( ! ( is_object( $event ) && $has_data ) ) {
				$label = ( 'custom' === $custom_content ) ? __( 'Custom Content for Post', 'my-calendar-pro' ) : __( 'Custom Excerpt for Post', 'my-calendar-pro' );
				$form .= "<p><label for='mcs_custom_content'>" . $label . "</label><br /><textarea name='mcs_custom_content' id='mcs_custom_content' rows='8' cols='60' class='widefat' />" . esc_attr( $template ) . '</textarea></p>';
			}
		} elseif ( 'custom' === $custom_content && 'custom' === $custom_excerpt ) {
			$form .= "<div class='update error'><p>" . __( '<strong>Settings error:</strong> You can either create the post excerpt with custom content or the post content, but not both.', 'my-calendar-pro' ) . '</p></div>';
		}

		if ( is_object( $event ) && property_exists( $event, 'event_post' ) && $has_data ) {
			$related = get_post_meta( $event->event_post, '_mc_related_post', true );
			$url     = ( $related ) ? get_edit_post_link( $related ) : false;
			if ( $url ) {
				$form .= "<p><a href='$url'>" . __( 'Edit blog post associated with this event', 'my-calendar-pro' ) . '</a></p>';
			}
		}
	}

	return $form;
}

add_action( 'mc_update_event_post', 'mcs_custom_content_save', 10, 5 );
/**
 * Save custom content settings.
 *
 * @param int    $post_id Post ID.
 * @param array  $post POST data.
 * @param object $data Event data.
 * @param int    $event_id Event ID.
 * @param string $action Action taken.
 */
function mcs_custom_content_save( $post_id, $post, $data, $event_id, $action ) {
	if ( 'true' === get_option( 'mcs_create_post' ) ) {
		$options        = get_option( 'mcs_event_post' );
		$custom_content = $options['content'];
		if ( 'custom' === $custom_content ) {
			$content = isset( $post['mcs_custom_content'] ) ? sanitize_textarea_field( $post['mcs_custom_content'] ) : '';
			update_post_meta( $post_id, '_mc_custom_content', $content );
		}
	}
}
