cart->empty_cart();
}
add_action("wp_footer", "show_modal");
render_dialog_html();
}
}
}
function modal_styles()
{
wp_enqueue_style(
"prijs-per-postcode",
plugins_url("/assets/postcode_modal.css", __FILE__),
);
}
function show_modal()
{
?>
get_params();
$nonce = $data->get_header("X-WP-Nonce");
if (wp_verify_nonce($nonce, "wp_rest")) {
if (!verify_postcode($params["postcode"])) {
$resp = [
"status" => "error",
"message" => "postcode",
];
echo json_encode($resp);
exit();
}
if (!verify_huisnummer($params["huisnummer"])) {
$resp = [
"status" => "error",
"message" => "huisnummer",
];
echo json_encode($resp);
exit();
}
$result = getStraatnaam($params["postcode"], $params["huisnummer"]);
if (isset($result["error"])) {
$resp = [
"status" => "error",
"message" => $result["error"],
"apirequest" => "openpostcode.nl",
];
echo json_encode($resp);
exit();
}
$_SESSION["postcode"] = $params["postcode"];
$_SESSION["huisnummer"] = $params["huisnummer"];
$_SESSION["straatnaam"] = $result["straatnaam"];
$_SESSION["woonplaats"] = $result["woonplaats"];
$_SESSION["postcode_is_local"] = postcode_in_range(
$params["postcode"],
5000,
5800,
);
$resp = [
"status" => "success",
"message" => "all good",
"straatnaam" => $result["straatnaam"],
"lokaal_trarief" => postcode_in_range(
$params["postcode"],
5000,
5800,
),
];
} else {
$resp = [
"status" => "error",
"message" => "nononce",
];
}
echo json_encode($resp);
exit();
}
function register_modal_api()
{
register_rest_route("postcode-modal/v1", "submit", [
"methods" => "POST",
"callback" => "handle_postcode_modal",
]);
}
function verify_postcode($postcode)
{
if (!preg_match('/^[0-9]{4}\s?[A-Za-z]{2}$/', $postcode) === 1) {
return false;
}
return true;
}
function verify_huisnummer($huisnummer)
{
if (!preg_match('/^[0-9]{4}\s?[A-Za-z]{2}$/', $huisnummer) === 1) {
return false;
}
return true;
}
function getStraatnaam($postcode, $huisnummer)
{
$url =
"https://openpostcode.nl/api/v2/address?postcode=" .
urlencode($postcode) .
"&huisnummer=" .
urlencode($huisnummer);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_USERAGENT, "PHP/OpenPostcodeClient");
$response = curl_exec($ch);
if (curl_error($ch)) {
curl_close($ch);
return ["error" => "cURL error: " . curl_error($ch)];
}
curl_close($ch);
$data = json_decode($response, true);
if (isset($data["error"])) {
return [
"error" => $data["error"]["message"],
"code" => $data["error"]["code"],
];
}
return [
"straatnaam" => $data["results"][0]["straat"],
"woonplaats" => $data["results"][0]["woonplaats"],
];
}
function postcode_in_range($postcode, $start, $end)
{
$cleanPostcode = strtoupper(preg_replace("/\s+/", "", $postcode));
if (!preg_match('/^\d{4}[A-Z]{2}$/', $cleanPostcode)) {
return false;
}
$numberPart = (int) substr($cleanPostcode, 0, 4);
return $numberPart >= $start && $numberPart <= $end;
}