<?php 
if ( ! defined( 'ABSPATH' ) ) exit;

// Register custom API-endpoint to save data to the database
add_action('rest_api_init', function () {
    register_rest_route('renesse/v1', '/check-data-timestamp', [
        'methods' => 'GET',
        'callback' => 'renesse_check_data_timestamp',
        'permission_callback' => '__return_true', // Adjust permission as needed
    ]);
});

function renesse_check_data_timestamp($request) {
    $type = $request->get_param('type');

    // Validate the type parameter
    if (!in_array($type, ['events', 'activities'])) {
        return new WP_Error('invalid_type', 'Invalid type provided', ['status' => 400]);
    }

    // Construct option name and retrieve the last updated timestamp
    $option_name = 'renesse_widget_' . sanitize_text_field($type);
    $last_updated = get_option($option_name . '_updated', null);

    // Handle cases where the last_updated field is null
    if (is_null($last_updated)) {
        return rest_ensure_response([
            'last_updated' => null,
            'message' => 'No data found or timestamp not set for this type.'
        ]);
    }

    // Return the last updated timestamp
    return rest_ensure_response([
        'last_updated' => $last_updated
    ]);
}