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

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

/**
 * Create event from post
 */

add_action( 'admin_menu', 'mcs_add_outer_box' );
/**
 * Add metabox for event posting.
 *
 * @return void;
 */
function mcs_add_outer_box() {
	$known = mcs_known_posts();
	if ( isset( $_GET['post'] ) && in_array( $_GET['post'], $known, true ) ) {
		return;
	}
	$post_events = ( is_array( get_option( 'mcs_post_event_types' ) ) ) ? get_option( 'mcs_post_event_types' ) : array();
	if ( is_array( $post_events ) ) {
		foreach ( $post_events as $post_type ) {
			add_meta_box( 'mcs_add_event', __( 'My Calendar Event', 'my-calendar-pro' ), 'mcs_add_inner_box', $post_type, 'normal', 'high' );
		}
	}
}

/**
 * Inner box
 */
function mcs_add_inner_box() {
	global $post;
	?>
	<div class="mcs_add_event mc-submissions">
	<?php
	if ( isset( $_GET['action'] ) && 'edit' === $_GET['action'] ) {
		$event_id = get_post_meta( $post->ID, '_mc_generated_event', true );
		if ( $event_id ) {
			$url   = admin_url( 'admin.php?page=my-calendar&mode=edit&event_id=' . $event_id );
			$event = mc_get_first_event( $event_id );
			if ( is_object( $event ) ) {
				$content = '<p><strong>' . wp_kses_post( $event->event_title ) . '</strong><br />' . $event->event_begin . ' - ' . $event->event_time . '</p>';
				if ( ! ( 'S' === $event->event_recur || 'S1' === $event->event_recur ) ) {
					$recur    = mc_event_recur_string( $event, $event->event_begin );
					$content .= wpautop( $recur );
				}
				$elabel = '';
				if ( property_exists( $event, 'location' ) && is_object( $event->location ) ) {
					$elabel = $event->location->location_label;
				}
				if ( '' !== $elabel ) {
					// Translators: Location label.
					$content .= '<p>' . sprintf( __( '<strong>Location:</strong> %s', 'my-calendar-pro' ), wp_kses_post( $elabel ) ) . '</p>';
				}
				// Translators: Event editing URL.
				$content .= '<p>' . sprintf( __( '<a href="%s">Edit event</a>.', 'my-calendar-pro' ), $url ) . '</p>';
				echo wp_kses_post( $content );
			} else {
				mc_meta_box_form();
			}
		} else {
			mc_meta_box_form();
		}
	} else {
		mc_meta_box_form();
	}
	?>
	</div>
	<?php
}

/**
 * Contents of meta box.
 */
function mc_meta_box_form() {
	global $wpdb;
	$has_data   = false;
	$data       = false;
	$event_desc = mc_show_block( 'event_desc', $has_data, $data, false );
	if ( $event_desc ) {
		$description = "<div class='event_description'>
							<label for='event_desc'>" . __( 'Event Description', 'my-calendar-pro' ) . "</label><br />
							<textarea id='event_desc' class='event_desc widefat' cols='80' rows='8' name='event_desc'></textarea>
						</div>";
	} else {
		$description = '';
	}
	$event_host     = mc_show_block( 'event_host', $has_data, $data, false );
	$event_category = mc_show_block( 'event_category', $has_data, $data, false );
	$event_link     = mc_show_block( 'event_link', $has_data, $data, false );
	$event_recurs   = mc_show_block( 'event_recurs', $has_data, $data, false );
	$mc_datetime    = apply_filters( 'mc_datetime_inputs', '', $has_data, $data, 'admin' );
	if ( mc_show_edit_block( 'event_location' ) ) {
		$locs = ( function_exists( 'mc_get_locations' ) ) ? mc_get_locations( 'post-events' ) : $wpdb->get_results( 'SELECT location_id,location_label FROM ' . my_calendar_locations_table() . ' ORDER BY location_label ASC' ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
		if ( ! empty( $locs ) ) {
			$location = '
			<p>
				<label for="l_preset">' . __( 'Event Location', 'my-calendar-pro' ) . '</label>
				<select name="location_preset" id="l_preset">
				<option value="none"> -- </option>';
			foreach ( $locs as $loc ) {
				if ( is_object( $loc ) ) {
					$location .= '<option value="' . $loc->location_id . '">' . wp_kses_post( stripslashes( $loc->location_label ) ) . '</option>';
				}
			}
			$location .= '</select></p>';
		} else {
			$location = '<input type="hidden" name="location_preset" value="none" />';
		}
	} else {
		$location = '<input type="hidden" name="location_preset" value="none" />';
	}
	if ( 'true' === get_option( 'mcs_automatic_approval' ) || current_user_can( 'mc_approve_events' ) ) {
		$publish_type = '<input type="hidden" name="save" value="true" />';
	} else {
		$publish_type = '<input type="hidden" name="draft" value="true" />';
	}
	$return = '
	<div class="mcs_enable_events checkbox">
		<p>
			<input type="checkbox" name="mcs_enable_events" value="true" id="mcs_enable_events"> <label for="mcs_enable_events">' . esc_html__( 'Cross post to My Calendar', 'my-calendar-pro' ) . '</label>
		</p>
	</div>
	<div class="mcs-submit-post-event">
		<div>
			<input type="hidden" name="event_group_id" value="' . mc_group_id() . '" />
			<input type="hidden" name="event_action" value="add" />
			<input type="hidden" name="event_source" value="post" />
			' . $publish_type . '
			<input type="hidden" name="event_nonce_name" value="' . wp_create_nonce( 'event_nonce' ) . '" />
		</div>
		<fieldset class="details">
			<legend class="screen-reader-text">' . __( 'Event Details', 'my-calendar-pro' ) . '</legend>
			<p>
				<label for="e_title">' . __( 'Event Title', 'my-calendar-pro' ) . ' <span class="required">(required)</span></label>
				<input type="text" id="e_title" name="event_title" size="50" maxlength="255" value="" />' . "
				<span class='checkbox'><input type='checkbox' id='mcs_use_post_title' name='mcs_use_post_title' value='true' /> <label for='mcs_use_post_title'>" . __( 'Use post title', 'my-calendar-pro' ) . '</label></span>
			</p>
			' . $description . $event_host . $event_category . $event_link . "
			<p class='checkbox'>
				<input type='checkbox' id='mc_use_permalink' name='mc_use_permalink' value='true' /> <label for='mc_use_permalink'>" . __( 'Use post permalink', 'my-calendar-pro' ) . '</label>
			</p>' . '
		</fieldset>
		<fieldset class="datetime">
			<legend class="screen-reader-text">' . __( 'Event Date and Time', 'my-calendar-pro' ) . '</legend>
			<div id="e_schedule">' . $mc_datetime . '</div>
		</fieldset>
		' . $event_recurs . '
		<fieldset class="locations">
			<legend class="screen-reader-text">' . __( 'Event Location', 'my-calendar-pro' ) . '</legend>' . $location . '
		</fieldset>
	</div>';

	echo wp_kses( $return, mc_kses_elements() );
}

add_action( 'save_post', 'mc_save_event_post', 15 );
/**
 * Save details for event post.
 *
 * @param integer $id Post ID.
 *
 * @return void|integer
 */
function mc_save_event_post( $id ) {
	$post_types    = ( is_array( get_option( 'mcs_post_event_types' ) ) ) ? get_option( 'mcs_post_event_types' ) : array();
	$is_valid_type = ( ! empty( $post_types ) && in_array( get_post_type( $id ), $post_types, true ) ) ? true : false;
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE || wp_is_post_revision( $id ) || ! $is_valid_type ) {

		return $id;
	}
	$event_post = get_post_meta( $id, '_mc_generated_event', true );
	if ( $event_post ) {
		return;
	}

	if ( isset( $_POST['event_nonce_name'] ) && isset( $_POST['event_source'] ) && 'post' === $_POST['event_source'] ) {

		if ( isset( $_POST['mcs_use_post_title'] ) ) {
			$title                = get_the_title( $id );
			$_POST['event_title'] = $title;
		} else {
			if ( ! isset( $_POST['event_title'] ) || empty( $_POST['event_title'] ) ) {
				return $id;
			}
		}
		// Copy POST data into separate array for modification.
		$post = map_deep( $_POST, 'sanitize_textarea_field' );
		if ( isset( $_POST['event_desc'] ) ) {
			$post['content'] = sanitize_textarea_field( $_POST['event_desc'] );
		} else {
			$post['content'] = '';
		}
		$attach_id      = get_post_thumbnail_id( $id );
		$featured_image = wp_get_attachment_url( $attach_id );
		if ( isset( $_POST['post_author_override'] ) ) {
			$post['event_author'] = intval( $_POST['post_author_override'] );
		} else {
			$post['event_author'] = get_current_user_id();
		}
		if ( 'draft' === get_post_status( $id ) ) {
			$post['event_approved'] = 0;
		}
		$check = mc_check_data( 'add', $post, 0 );
		if ( $check[0] ) {
			$response = my_calendar_save( 'add', $check );
			$event_id = $response['event_id'];
			$response = $response['message'];
			$event    = mc_get_first_event( $event_id );
			$post_id  = $event->event_post;
			set_post_thumbnail( $post_id, $attach_id );
			mc_update_data( $event_id, 'event_image', $featured_image, '%s' );
			if ( isset( $_POST['mc_use_permalink'] ) && 'true' === $_POST['mc_use_permalink'] ) {
				$permalink = get_permalink( $id );
				mc_update_data( $event_id, 'event_link', $permalink, '%s' );
			}
			update_post_meta( $id, '_mc_new_event', $response );
			update_post_meta( $id, '_mc_generated_event', $event_id );
		}
	}

	return $id;
}


/**
 * Enqueue scripts for My Calendar Event posts
 */
function mcs_enqueue_post_scripts() {
	if ( is_admin() ) {
		$post_events = ( is_array( get_option( 'mcs_post_event_types' ) ) ) ? get_option( 'mcs_post_event_types' ) : array();
		global $current_screen;
		if ( 'post' === $current_screen->base && in_array( $current_screen->post_type, $post_events, true ) ) {
			$version = get_option( 'mc_version' );
			if ( SCRIPT_DEBUG ) {
				$version .= '-' . wp_rand( 10000, 100000 );
			}
			wp_enqueue_style( 'mc-styles' );
			// Script needs to be aware of current Pro version.
			$mcs_version = ( get_option( 'mcs_version', '' ) ) ? get_option( 'mcs_version' ) : 1.0;
			wp_enqueue_script( 'mc.admin' );
			wp_localize_script(
				'mc.admin',
				'mcAdmin',
				array(
					'thumbHeight'   => get_option( 'thumbnail_size_h' ),
					'deleteButton'  => __( 'Cancel', 'my-calendar-pro' ),
					'restoreButton' => __( 'Restore', 'my-calendar-pro' ),
					'imageRemoved'  => __( 'Featured image removed', 'my-calendar-pro' ),
					'modalTitle'    => __( 'Choose an Image', 'my-calendar-pro' ),
					'buttonName'    => __( 'Select', 'my-calendar-pro' ),
					'mcs'           => $mcs_version,
				)
			);
			wp_enqueue_script( 'mc.ajax' );
			$event_id = ( isset( $_GET['event_id'] ) ) ? (int) $_GET['event_id'] : '';
			wp_localize_script(
				'mc.ajax',
				'mc_data',
				array(
					'action'   => 'delete_occurrence',
					'recur'    => 'add_date',
					'security' => wp_create_nonce( 'mc-delete-nonce' ),
					'url'      => esc_url( add_query_arg( 'event_id', $event_id, admin_url( 'admin.php?page=my-calendar&mode=edit' ) ) ),
				)
			);
			wp_localize_script(
				'mc.ajax',
				'mc_recur',
				array(
					'action'   => 'display_recurrence',
					'security' => wp_create_nonce( 'mc-recurrence-nonce' ),
				)
			);
			wp_localize_script(
				'mc.ajax',
				'mc_cats',
				array(
					'action'   => 'add_category',
					'security' => wp_create_nonce( 'mc-add-category-nonce' ),
				)
			);
			mcs_setup_duetjs();
		}
	}
}
add_action( 'admin_enqueue_scripts', 'mcs_enqueue_post_scripts', 11 );

add_filter( 'mcs_custom_settings_update', 'mcs_post_events_update', 10, 2 );
/**
 * Update settings for event posting.
 *
 * @param mixed $value Posted value.
 * @param array $post POST data.
 *
 * @return string
 */
function mcs_post_events_update( $value, $post ) {
	// save settings.
	if ( isset( $_POST['post_events_settings'] ) ) {
		if ( isset( $_POST['mcs_post_events'] ) ) {
			update_option( 'mcs_post_events', 'true' );
		} else {
			delete_option( 'mcs_post_events' );
		}
		if ( isset( $_POST['mcs_approve_from_post'] ) ) {
			update_option( 'mcs_approve_from_post', 'true' );
		} else {
			delete_option( 'mcs_approve_from_post' );
		}
		$post_events = isset( $_POST['mcs_post_event_types'] ) ? map_deep( $_POST['mcs_post_event_types'], 'sanitize_text_field' ) : array();
		update_option( 'mcs_post_event_types', $post_events );

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

	return $value;
}

add_filter( 'mcs_settings_tabs', 'mcs_post_events_tabs' );
/**
 * Add settings tab.
 *
 * @param array $tabs All tabs.
 *
 * @return array all tabs.
 */
function mcs_post_events_tabs( $tabs ) {
	$tabs['post_events'] = __( 'Events from Posts', 'my-calendar-pro' );

	return $tabs;
}

add_filter( 'mcs_settings_panels', 'mcs_post_events_settings' );
/**
 * Add settings panel.
 *
 * @param array $panels All panels.
 *
 * @return array
 */
function mcs_post_events_settings( $panels ) {
	$mcs_post_events = get_option( 'mcs_post_events' );
	$post_events     = ( is_array( get_option( 'mcs_post_event_types' ) ) ) ? get_option( 'mcs_post_event_types' ) : array();
	if ( 'true' === $mcs_post_events ) {
		$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;
			}
			$selected = ( in_array( $type->name, $post_events, true ) ) ? ' checked="checked"' : '';
			$types   .= "<li><input type='checkbox' name='mcs_post_event_types[]' id='mcs_post_event_types_$type->name' value='$type->name'" . $selected . " /> <label for='mcs_post_event_types_$type->name'>" . $type->labels->name . '</label></li>';
		}
		$controls = '
			<fieldset>
				<legend>' . __( 'Supported Post Types', 'my-calendar-pro' ) . "</legend>
				<ul>$types</ul>
			</fieldset>
			<p>
				<input type='checkbox' name='mcs_approve_from_post' id='mcs_approve_from_post' " . checked( get_option( 'mcs_approve_from_post' ), 'true', false ) . " > <label for='mcs_approve_from_post'>" . __( 'Events from Posts are always created as drafts.', 'my-calendar-pro' ) . '</label>
			</p>';
	} else {
		$controls = "<div>
		<div class='mcs-about'>
			<p>
				" . __( 'Create events from the post editor. Enable to select support post types.', 'my-calendar-pro' ) . '
			</p>
		</div>';
		if ( is_array( $post_events ) ) {
			foreach ( $post_events as $post_type ) {
				$controls .= "<input type='hidden' name='mcs_post_event_types[]' value='" . esc_attr( $post_type ) . "' />";
			}
		}
		$controls .= '</div>';
	}
	$panels['post_events'] = '
		<h2>' . __( 'Create Event from Posts Settings', 'my-calendar-pro' ) . '</h2>
		<div class="inside">
			<p>
				<input type="checkbox" name="mcs_post_events" id="mcs_post_events" value="true" ' . checked( $mcs_post_events, 'true', false ) . '/> <label for="mcs_post_events">' . __( 'Post events from posts', 'my-calendar-pro' ) . '</label>
			</p>' . $controls . '
			{submit}
		</div>';

	return $panels;
}
