<?php


// add_action('wp_loaded', 'dragblock_form_submission', 1);
add_action('init', 'dragblock_form_submission', 100);
// add_action('wp', 'dragblock_form_submission', 10);

/**
 * We stopped supporting $_GET to minify the approval process
 */
function dragblock_form_submission()
{
	// verify if this submit is for out plugin action processor
	if (
		empty($_POST['dragblock/form-nonce-field']) ||
		!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['dragblock/form-nonce-field'])), 'dragblock/form-nonce-action')
	) {
		return;
	}

	// submitted successfully => form security check
	// - prevent multiple submissions
	// - prevent bots
	if (
		// this is submited from a remote source
		!isset($_POST[DRAGBLOCK_FORM_TITLE_FIELD_NAME]) ||

		// this is submitted by a auto fill bot
		!empty($_POST[DRAGBLOCK_FORM_TITLE_FIELD_NAME]) ||

		// this is submitted from a non-js bot
		empty($_POST['dragblock/form-session-token'])
	) {
		return;
	}


	// this is submitted by a js bot (to fast in filling)
	// Start the session
	if (!session_id()) {
		session_start();
	}

	// Get the session variable
	$unique_id = sanitize_text_field(wp_unslash($_POST['dragblock/form-session-token']));
	if (empty($_SESSION[$unique_id])) {
		return;
	}
	$createdFormTime = sanitize_text_field(wp_unslash($_SESSION[$unique_id]));

	// $createdFormTime = intval($_SESSION[$unique_id]);
	if (!$createdFormTime || time() - $createdFormTime < 1) {
		return;
	}

	// init form

	$formClientId = '';
	if (isset($_POST[DRAGBLOCK_FORM_CLIENT_ID_FIELD_NAME])) {
		$formClientId = sanitize_text_field(wp_unslash($_POST[DRAGBLOCK_FORM_CLIENT_ID_FIELD_NAME]));
	} else {
		$formClientId = 'dragblock-form-unorganized';
	}

	// clean up form
	unset($_POST[DRAGBLOCK_FORM_CLIENT_ID_FIELD_NAME]);
	unset($_POST['dragblock/form-nonce-field']);
	unset($_POST['dragblock/form-session-token']);
	unset($_POST[DRAGBLOCK_FORM_TITLE_FIELD_NAME]);
	unset($_POST['submit']);


	// prepare content
	global $dragblock_form_entries_message_error;
	$dragblock_form_entries_message_error[$formClientId] = false; // notify that the summission is successful at default

	// - check for duplicate submission
	$transientHash = get_transient('dragblock/form-transient-' . $formClientId);
	$sanitized_post = array();
	foreach ($_POST as $key => $value) {
		$sanitized_post[sanitize_text_field($key)] = sanitize_textarea_field(wp_unslash($value));		
	}

	$newTransientHash = sha1(http_build_query($sanitized_post));
	if ($transientHash === $newTransientHash) {
		set_transient('dragblock/form-transient-' . $formClientId, $newTransientHash, 3600);
		$dragblock_form_entries_message_error[$formClientId] = __('Duplicate submission', 'dragblock');
		return;
	}
	set_transient('dragblock/form-transient-' . $formClientId, $newTransientHash, 3600);


	// create new custom post here	
	$post_id = wp_insert_post(
		array(
			'post_content'  => '',
			'post_status'   => 'publish',
			'post_type'     => DRAGBLOCK_FORM_ENTRY
		)
	);

	if (is_wp_error($post_id)) {
		// update message error for the form
		$dragblock_form_entries_message_error[$formClientId] = $post_id->get_error_message();

		return;
	}

	/**
	Still cannot creat term successfully.
	Needed to check after finishing all demos
	 */
	// create custom taxonomy from form client id here
	// $term_tag = 'dragblock-form-' . $formClientId;
	// $term_id = term_exists($term_tag);
	// if (!$term_id) {

	// 	$taxonomy = register_taxonomy(DRAGBLOCK_FORM_ENTRY, DRAGBLOCK_FORM_ENTRY, array(
	// 		'label' => ucfirst(DRAGBLOCK_FORM_ENTRY),
	// 		'rewrite' => array('slug' => DRAGBLOCK_FORM_ENTRY),
	// 	));
	// 	if (is_wp_error($taxonomy)) {

	// 		$dragblock_form_entries_message_error[$formClientId] = $taxonomy->get_error_message();
	// 		return;
	// 	}

	// 	$term = wp_insert_term($term_tag, DRAGBLOCK_FORM_ENTRY);
	// 	if (is_wp_error($term)) {
	// 		$dragblock_form_entries_message_error[$formClientId] = $term->get_error_message();
	// 		return;
	// 	}
	// }
	// if ($term_id) {
	// 	wp_set_object_terms($post_id, array($term_id), DRAGBLOCK_FORM_ENTRY);
	// }

	// - create the form entry content and metadata
	$content = '';
	$title = ucwords(str_replace('-', ' ', sanitize_title($formClientId))) . ': #' . $post_id;
	$keys = array();
	foreach ($sanitized_post as $key => $value) {
		
		// to restore the keys that collide with the wp_reserved_terms
		if (strpos($key, DRAGBLOCK_WP_RESEVED_TERMS_PLACEHOLDER) !== false) {
			$key = str_replace(DRAGBLOCK_WP_RESEVED_TERMS_PLACEHOLDER, '', $key);
		}

		if ('_wp_http_referer' !== $key) {
			$content .= '<p><strong>' . esc_html($key) . ':</strong> ' . esc_html($value) . '</p>';
		}
		array_push($keys, $key);

		// Add custom fields to the post
		// remeber using -- to distinguish between custom fields and system fields
		update_post_meta($post_id, DRAGBLOCK_FORM_ENTRY . '--' . $key, $value);
	}
	// - save key list so we can access them if needed
	// keys is a system field so use only one '-'
	update_post_meta($post_id, DRAGBLOCK_FORM_ENTRY . '-keys', $keys);

	wp_update_post(
		array(
			'ID' => $post_id,
			'post_title' => $title,
			'post_content' => $content
		)
	);


	// send email here
	// usually fail on localhost
	////////////////////////////////////////////////////////////////
	// - Not Send email on localhost
	// Set email variables
	$to = get_option('admin_email');
	$headers = array('Content-Type: text/html; charset=UTF-8');
	$subject = get_bloginfo('name') . ' - DragBlock Form – ' . $title;

	if (DRAGBLOCK_IS_LOCAL) {
		return;
	}

	// - Email failed to send
	// - At this time, we don't notify the user but to show to admin that the email is failed
	if (!wp_mail($to, $subject, $content, $headers)) {
		// $dragblock_form_entries_message_error[$formClientId] = __('It was failed for sending email to the site owner.', 'dragblock');
		update_post_meta($post_id, DRAGBLOCK_FORM_ENTRY . '-failed-email', time());
		return;
	}

	update_post_meta($post_id, DRAGBLOCK_FORM_ENTRY . '-failed-email', 'PASSED');
	// submitted successfully => form security update

}
