<?php
	declare(strict_types = 1);
	namespace Kimendisch\Sbgg_Jetzt;
	use Flake\Csrf;
	
	// HANDLE AUTHENTICATION //
	require("./page/admin/auth_handler.php");
	
	
	// 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 //
	// csrf token
	Csrf::check(token: $request["csrf_token"] ?? "");
	
	// content name
	$content_name = $request["content_name"] ?? "";
	if(!is_string($content_name)){
		http_response_code(400);
		echo("invalid content name");
		die();
	}
	if(!preg_match("/^\d{4}-\d{2}-\d{2}(-[a-z0-9]+)+$/", $content_name)){
		http_response_code(400);
		echo("invalid content name");
		die();
	}
	
	
	// TRY SENDING //
	// make sure session isn't locked
	if(extension_loaded("session")) session_write_close();
	
	// add jobs to queue
	Newsletter::send_all(content_name: $content_name);
	
	// positive response
	http_response_code(200);
	echo(json_encode([
		"success" => true
	]));
	
	
	// EXECUTE WORK //
	// close connection
	Newsletter::api_helper_http_close_connection();
	
	// execute queued work
	Newsletter::queue_work();
?>
