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

// Register the API route properly
add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/set-twitter-card', [
        'methods' => 'POST',
        'callback' => 'myaio_sac_set_twitter_card_data',
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

function myaio_sac_set_twitter_card_data(WP_REST_Request $request) {
    // Validate URL
    $url = esc_url_raw($request->get_param('url'));
    if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) {
        return new WP_REST_Response(['error' => 'Invalid or missing URL'], 400);
    }

    // Resolve 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) {
        $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('card')) {
        $card = sanitize_text_field($request->get_param('card'));
        if ($card !== '') {
            update_post_meta($post_id, '_myaio_twitter_card', $card);
            $updated['twitter:card'] = $card;
        }
    }

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

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

    if ($request->has_param('image')) {
        $image = esc_url_raw($request->get_param('image'));
        if ($image !== '') {
            update_post_meta($post_id, '_myaio_twitter_image', $image);
            $updated['twitter:image'] = $image;
        }
    }

    if ($request->has_param('site')) {
        $site = sanitize_text_field($request->get_param('site'));
        if ($site !== '') {
            // Stored for completeness; current continuity layer does not output twitter:site.
            update_post_meta($post_id, '_myaio_twitter_site', $site);
            $updated['twitter:site'] = $site;
        }
    }

    return rest_ensure_response([
        'success' => true,
        'message' => "Twitter card meta tags stored for $url",
        'data'    => $updated,
    ]);
}
