<?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', '/save-data', [
        'methods' => 'POST',
        'callback' => 'renesse_save_data_to_db',
        'permission_callback' => '__return_true', // Adjust permission as needed
    ]);
});

function renesse_save_data_to_db($request) {
    $params = $request->get_json_params();

    // Validate and sanitize input
    if (!isset($params['type']) || !in_array($params['type'], ['events', 'activities'])) {
        return new WP_Error('invalid_type', 'Invalid type provided', ['status' => 400]);
    }

    $data = isset($params['data']) ? $params['data'] : [];
    if (empty($data) || !is_array($data)) {
        return new WP_Error('invalid_data', 'Invalid or missing data', ['status' => 400]);
    }

    // Save data in the options table
    $option_name = 'renesse_widget_' . sanitize_text_field($params['type']);
    update_option($option_name, $data);

    // Save timestamp for last update
    $t = time();
    update_option($option_name . '_updated', date('Y-m-d', $t));

    return rest_ensure_response(['success' => true]);
}