<?php
// Prevent direct file access
if (!defined('ABSPATH')) {
    exit;
}

// Register the endpoint properly within rest_api_init
add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/set-open-graph', [
        'methods' => 'POST',
        'callback' => 'myaio_sac_set_open_graph_data',
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

function myaio_sac_set_open_graph_data(WP_REST_Request $request) {
    // URL is required
    $url = esc_url_raw($request->get_param('url'));
    if (empty($url)) {
        return new WP_REST_Response(['error' => 'Missing required field url'], 400);
    }

    // Resolve the URL to a post ID so the data survives MYAIO deactivation (stored in post meta)
    $post_id = (int) url_to_postid($url);
    if (!$post_id) {
        // Try a best-effort path-based resolution
        $path = wp_parse_url($url, PHP_URL_PATH);
        if ($path) {
            $post_id = (int) url_to_postid(home_url($path));
        }
    }

    if (!$post_id) {
        return new WP_REST_Response(['error' => 'Unable to resolve url to a post/page'], 404);
    }

    $updated = [
        'post_id' => $post_id,
        'url' => get_permalink($post_id),
    ];

    if ($request->has_param('title')) {
        $og_title = sanitize_text_field($request->get_param('title'));
        if ($og_title !== '') {
            update_post_meta($post_id, '_myaio_og_title', $og_title);
            $updated['og:title'] = $og_title;
        }
    }

    if ($request->has_param('description')) {
        $og_desc = sanitize_textarea_field($request->get_param('description'));
        if ($og_desc !== '') {
            update_post_meta($post_id, '_myaio_og_description', $og_desc);
            $updated['og:description'] = $og_desc;
        }
    }

    if ($request->has_param('og_url')) {
        $og_url = esc_url_raw($request->get_param('og_url'));
        if ($og_url !== '') {
            update_post_meta($post_id, '_myaio_og_url', $og_url);
            $updated['og:url'] = $og_url;
        }
    }

    // Optional og:image
    if ($request->has_param('image')) {
        $img = esc_url_raw($request->get_param('image'));
        if ($img !== '') {
            update_post_meta($post_id, '_myaio_og_image', $img);
            $updated['og:image'] = $img;
        }
    }

    return rest_ensure_response([
        'success' => true,
        'message' => 'Open Graph meta tags stored for URL',
        'stored'  => $updated,
    ]);
}
