<?php
	declare(strict_types = 1);
	namespace Kimendisch\Sbgg_Jetzt;
	use Flake\Excuse;
	use Flake\Id64;
	
	// CHECK CSRF PROTECTION //
	$x_cookieless_csrf_protection = getallheaders()["x-cookieless-csrf-protection"] ?? null;
	if($x_cookieless_csrf_protection !== "42"){
		// show an excuse page
		Excuse::show("invalid_csrf_token");
	}
	
	
	// DECODE REQUEST //
	// get json string
	$json_body = file_get_contents("php://input");
	if(strlen($json_body) <= 0){
		http_response_code(400);
		echo("malformed request body");
		die();
	}
	
	// try decoding json
	$request = json_decode($json_body, true);
	if(json_last_error() != JSON_ERROR_NONE){
		http_response_code(400);
		echo("malformed request body");
		die();
	}
	
	
	// VALIDATE VALUES //
	// mail address
	$mail_address = $request["mail_address"] ?? "";
	if(!is_string($mail_address)){
		http_response_code(400);
		echo("invalid mail address");
		die();
	}
	if(!preg_match("/^[a-zA-Z0-9\.\-\_\+]+@([a-z0-9\-]+\.)+[a-z0-9\-]{2,}$/", $mail_address)){
		http_response_code(400);
		echo("invalid mail address");
		die();
	}
	
	// verify key
	$verify_key = $request["verify_key"] ?? null;
	if(!Id64::is_valid($verify_key)){
		http_response_code(400);
		echo("invalid verify key");
		die();
	}
	
	
	// TRY SUBSCRIBING //
	// make sure session isn't locked
	if(extension_loaded("session")) session_write_close();
	
	// acquire runlock
	ignore_user_abort(true);
	
	// subscribe
	if(Newsletter::subscribe(mail_address: $mail_address, verify_key: $verify_key)){
		http_response_code(200);
		echo(json_encode([
			"success" => true
		]));
		
	} else {
		http_response_code(200);
		echo(json_encode([
			"success" => false
		]));
	}
	
	
	// EXECUTE WORK //
	// close connection
	Newsletter::api_helper_http_close_connection();
	
	// execute queued work
	Newsletter::queue_work();
?>
