<?php
// File: modules/logo-api.php

defined('ABSPATH') || exit;

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

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

/**
 * Get site logo from customizer or fallback from header image
 * Output MUST remain the same as your original.
 */
if (!function_exists('myaio_sac_get_site_logo')) {
    function myaio_sac_get_site_logo(WP_REST_Request $request) {
        $logo_id = get_theme_mod('custom_logo');

        // Step 1: Check if a custom logo is set via Customizer
        if ($logo_id) {
            $logo_url = wp_get_attachment_image_url($logo_id, 'full');
            $alt_text = get_post_meta($logo_id, '_wp_attachment_image_alt', true);

            return new WP_REST_Response([
                'logo_url' => $logo_url,
                'alt'      => $alt_text ?: get_bloginfo('name'),
                'source'   => 'customizer'
            ], 200);
        }

        // Step 2: Fallback — Try to detect logo from homepage HTML
        $homepage = home_url('/');
        $response = wp_safe_remote_get($homepage, ['timeout' => 12, 'redirection' => 3]);

        if (is_wp_error($response)) {
            return new WP_REST_Response([
                'logo_url' => null,
                'alt'      => null,
                'message'  => 'Could not fetch homepage HTML.',
            ], 200);
        }

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

        $xpath = new DOMXPath($dom);

        // Keep the SAME query as your original
        $img_query = "//*[contains(@class,'logo') or contains(@id,'logo') or ancestor::header]//img";
        $imgs = $xpath->query($img_query);

        if ($imgs && $imgs->length > 0) {
            foreach ($imgs as $img) {
                $src = $img->getAttribute('src');

                // Keep the SAME relative handling as your original
                if (strpos($src, 'http') !== 0) {
                    $src = home_url('/') . ltrim($src, '/');
                }

                $alt = $img->getAttribute('alt') ?: get_bloginfo('name');

                return new WP_REST_Response([
                    'logo_url' => $src,
                    'alt'      => $alt,
                    'source'   => 'header-detected'
                ], 200);
            }
        }

        // No logo found
        return new WP_REST_Response([
            'logo_url' => null,
            'alt'      => null,
            'message'  => 'Logo not found in customizer or header.',
        ], 200);
    }
}
