<?php

function mp_is_precise($post, $id, $location) {

	// is presentiel but not complete address ?
	$presentiel = get_field("mode", $id);
	if ($presentiel[0] === "En présentiel") {
		if ($location->approximate) {
			return false;
		}
	}

	return true;
}

function mp_is_address_complete($post, $id, $location) {

	// is presentiel but not complete address ?
	$presentiel = get_field("mode", $id);
	if ($presentiel[0] === "En présentiel") {
		if (strlen($location->street) == 0) {
			return false;
		}
		if (strlen($location->city) == 0) {
			return false;
		}
	}

	return true;
}

function mp_is_valid_address($post, $id, $location) {

	// is coordinates ?
	if ($location->coordinates == null)
		return false;

	return true;
}

function mp_fill_address_message($post, $id, $location) {

	$message = '<br /><p>article : "'
		. $post->post_title . '"</p><p>- adresse fournie : "'
		. get_field('adresse', $id) . ', '
		. get_field('ville', $id) . ', '
		. get_field('pays', $id)
		. '"</p><p>- adresse trouvée : "'
		. $location->address
		. '"</p>';

	return $message;
}

function mp_find_address_errors() {

	$errors = "";
	$incompletes = "";
	$approximates = "";
	$count_errors = 0;
	$count_incompletes = 0;
	$count_approximates = 0;

	$get_posts_args = array(
		'numberposts' => -1,
		'post_status' => 'publish',
		'post_type'   => 'post',
	);
	$posts = get_posts($get_posts_args);
	foreach ($posts as $post) {
		$id = $post->ID;
		$location = get_field('location', $id);
		if (! mp_is_valid_address($post, $id, $location)) {
			$count_errors++;
			$errors .= mp_fill_address_message($post, $id, $location);
		}
	//	else if (! mp_is_address_complete($post, $id, $location)) {
	//		$count_incompletes++;
	//		$incompletes .= mp_fill_address_message($post, $id, $location);
	//	}
		else if (! mp_is_precise($post, $id, $location)) {
			$count_approximates++;
			$approximates .= mp_fill_address_message($post, $id, $location);
		}
	}
	$message  = "<h2>nombre d'erreurs : " . $count_errors . "</h2>";
//	$message .= "<h2>nombre d'adresses incompletes pour des evenements en presentiels : " . $count_incompletes . "</h2>";
	$message .= "<h2>nombre d'adresses approximatives pour des evenements en presentiels : " . $count_approximates . "</h2>";
	$message .= "<br /><h2>erreurs :</h2>" . $errors;
//	$message .= "<br /><h2>adresses incompletes:</h2>" . $incompletes;
	$message .= "<br /><h2>approximatives :</h2>" . $approximates;

	return $message;
}

?>
