<?php
// File: modules/twitter-card-data.php
if ( ! defined('ABSPATH') ) { exit; }

require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

// Twitter Card API
add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/twitter-card-data', [
        'methods'  => WP_REST_Server::READABLE, // GET
        'callback' => 'myaio_sac_get_twitter_card_data',
        // keep output unchanged (Unauthorized handled in callback)
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

function myaio_sac_get_twitter_card_data(WP_REST_Request $request) {

    // ✅ Consistent auth across all modules (same output)
    $auth = function_exists('myaio_sac_require_api_key_or_401') ? myaio_sac_require_api_key_or_401($request) : null;
    if ($auth !== true) {
        return $auth instanceof WP_REST_Response ? $auth : new WP_REST_Response(['error' => 'Unauthorized'], 401);
    }

    $urls = function_exists('myaio_sac_get_all_site_urls') ? myaio_sac_get_all_site_urls() : [];
    $results = [];

    foreach ($urls as $entry) {
        $url  = isset($entry['url'])  ? esc_url_raw($entry['url'])  : '';
        $type = isset($entry['type']) ? sanitize_text_field($entry['type']) : '';

        if (empty($url)) {
            continue;
        }

        $response = wp_remote_get($url);
        if (is_wp_error($response)) {
            continue;
        }

        $html = wp_remote_retrieve_body($response);
        if (empty($html) || !class_exists('DOMDocument')) {
            continue;
        }

        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        libxml_clear_errors();

        $metaTags = $dom->getElementsByTagName('meta');

        $twitter_data = [
            'twitter:card'        => '',
            'twitter:title'       => '',
            'twitter:description' => '',
            'twitter:image'       => '',
            'twitter:site'        => ''
        ];

        foreach ($metaTags as $meta) {
            $name = strtolower((string) $meta->getAttribute('name'));
            if (!isset($twitter_data[$name])) {
                continue;
            }
            $content = $meta->getAttribute('content');
            $twitter_data[$name] = is_string($content) ? $content : '';
        }

        $results[] = [
            'url' => $url,
            'type' => $type,
            'twitter_card' => $twitter_data['twitter:card'],
            'twitter_title' => $twitter_data['twitter:title'],
            'twitter_description' => $twitter_data['twitter:description'],
            'twitter_image' => $twitter_data['twitter:image'],
            'twitter_site' => $twitter_data['twitter:site']
        ];
    }

    return rest_ensure_response(['results' => $results]);
}
