<?php
// File: modules/social-links-api.php

defined('ABSPATH') || exit;

// Shared key validation used across ALL modules
require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/get-social-links', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_get_social_links',
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ]);
});

/**
 * Fetch all social media links from homepage HTML
 * Output MUST remain same.
 */
if (!function_exists('myaio_sac_get_social_links')) {
    function myaio_sac_get_social_links(WP_REST_Request $request) {
        $homepage = home_url('/');

        // Use wp_safe_remote_get with timeout/redirection (does not change your output)
        $res = wp_safe_remote_get($homepage, [
            'timeout'     => 12,
            'redirection' => 3,
            'headers'     => [
                'User-Agent' => 'MyAIO-SEO-SocialLinks/1.0; ' . home_url(),
            ],
        ]);

        if (is_wp_error($res)) {
            return new WP_REST_Response([
                'error'   => 'Failed to fetch homepage',
                'details' => $res->get_error_message()
            ], 500);
        }

        $html = (string) wp_remote_retrieve_body($res);

        // Keep behavior forgiving, but avoid fatal if body is empty
        if ($html === '') {
            return new WP_REST_Response([
                'error'   => 'Failed to fetch homepage',
                'details' => 'Empty response body'
            ], 500);
        }

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

        $social_patterns = [
            'facebook'  => 'facebook.com',
            'twitter'   => 'twitter.com',
            'linkedin'  => 'linkedin.com',
            'instagram' => 'instagram.com',
            'youtube'   => 'youtube.com',
            'pinterest' => 'pinterest.com',
            'tiktok'    => 'tiktok.com',
            'whatsapp'  => 'wa.me',
            'threads'   => 'threads.net',
            'x'         => 'x.com'
        ];

        $found_links = [];

        foreach ($xpath->query('//a[@href]') as $a) {
            $href = (string) $a->getAttribute('href');

            // Keep logic same; just ignore empty hrefs
            if ($href === '') continue;

            foreach ($social_patterns as $platform => $pattern) {
                if (stripos($href, $pattern) !== false) {
                    $found_links[$platform][] = esc_url_raw($href);
                }
            }
        }

        // Normalize: ensure unique URLs per platform (same behavior)
        foreach ($found_links as $platform => $urls) {
            $found_links[$platform] = array_values(array_unique($urls));
        }

        return new WP_REST_Response([
            'homepage'       => $homepage,
            'social_links'   => $found_links,
            'platform_count' => count($found_links),
            'total_links'    => array_sum(array_map('count', $found_links))
        ], 200);
    }
}
