<?php
if (!defined('ABSPATH')) {
	exit; // Exit if accessed directly
}

/**
 * Returns array of all pages.
 * For use in dropdowns.
 */
function wre_get_pages() {

	$args = array(
		'sort_order' => 'asc',
		'sort_column' => 'post_title',
		'hierarchical' => 1,
		'exclude' => '',
		'include' => '',
		'meta_key' => '',
		'meta_value' => '',
		'authors' => '',
		'child_of' => 0,
		'parent' => -1,
		'exclude_tree' => '',
		'number' => '',
		'offset' => 0,
		'post_type' => 'page',
		'post_status' => 'publish'
	);

	$pages = get_pages($args);
	$array = array();
	if ($pages) {
		foreach ($pages as $page) {
			$array[$page->ID] = $page->post_title;
		}
	}

	return $array;
}

/**
 * Output the archive button
 * @param  object $field_args Current field args
 * @param  object $field      Current field object
 */
function wre_admin_status_area($field_args, $field) {

	$post_id = $field->object_id;
	$enquiries = wre_meta('enquiries', $field->object_id);
	$count = !empty($enquiries) ? count($enquiries) : 0;
	$latest = is_array($enquiries) ? end($enquiries) : null;

	// listing enquiries section
	echo '<div class=""listing-enquiries>';
	echo '<span class="dashicons dashicons-admin-comments"></span> <a target="_blank" href="' . esc_url(admin_url('edit.php?post_type=listing-enquiry&listings=' . $post_id)) . '"><span>' . sprintf(_n('%s Enquiry', '%s Enquiries', $count, 'wp-real-estate'), $count) . '</a></span>';

	if ($latest) {
		echo '<p class="cmb2-metabox-description most-recent">' . __('Most Recent:', 'wp-real-estate') . ' ' . sprintf(_x('%s ago', '%s = human-readable time difference', 'wp-real-estate'), human_time_diff(get_the_date('U', $latest), current_time('timestamp'))) . '</p>';
	}
	echo '</div>';

	if ('archive' !== get_post_status($post_id)) {
		// archive button
		$button = ' <button id="archive-listing" type="button" class="button button-small">' . __('Archive This Listing', 'wp-real-estate') . '</button>';

		echo $button;
	} else {
		echo '<div class="archived-text warning">' . __('This listing is archived.', 'wp-real-estate') . '<br>' . __('It is no longer visible on the front end.', 'wp-real-estate') . '<br>' . __('Hit the Publish button to un-archive it.', 'wp-real-estate') . '</div>';
	}
	?>

	<script type="text/javascript" >

		jQuery(document).ready(function ($) {

			$("#archive-listing").click(function () {
				var btn = $(this);
				var data = {
					'action': 'wre_ajax_archive_listing',
					'post_id': <?php echo (int) $post_id; ?>,
					'nonce': '<?php echo wp_create_nonce('wre-archive-' . $post_id); ?>',
				};

				// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
				$.post(ajaxurl, data, function (response) {

					var obj = $.parseJSON(response);

					$(btn).hide();
					$(btn).after('<div class="archived-text ' + obj.result + '">' + obj.string + '</div>');

					// change the select input to be archived (in case listing is updated after our actions)
					$('#post-status-display').text('<?php esc_html_e('Archived', 'wp-real-estate') ?>');

				});

			});

		});
	</script>

	<?php
}

// Ajax Handler for archiving a listings
add_action('wp_ajax_wre_ajax_archive_listing', 'wre_ajax_archive_listing');

function wre_ajax_archive_listing() {
	// Get the Post ID
	$post_id = (int) $_REQUEST['post_id'];
	$response = false;

	// Proceed, again we are checking for permissions
	if (wp_verify_nonce($_REQUEST['nonce'], 'wre-archive-' . $post_id)) {

		$updated = wp_update_post(array(
			'ID' => $post_id,
			'post_status' => 'archive'
		));

		if (is_wp_error($updated)) {
			$response = false;
		} else {
			$response = true;
		}
	}

	if ($response == true) {
		$return = array(
			'string' => __('This listing is now archived. It is no longer visible on the front end.', 'wp-real-estate'),
			'result' => 'warning'
		);
	} else {
		$return = array(
			'string' => __('There was an error archiving this listing', 'wp-real-estate'),
			'result' => 'error'
		);
	}

	// Whatever the outcome, send the Response back
	echo json_encode($return);

	// Always exit when doing Ajax
	exit();
}