<?php
// File: modules/site-audit-checks.php

defined('ABSPATH') || exit;

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

/**
 * PHP 5.6+ safe "starts with" helper (avoid PHP 8 str_starts_with).
 */
if (!function_exists('myaio_sac_starts_with')) {
    function myaio_sac_starts_with($haystack, $needle) {
        $haystack = (string) $haystack;
        $needle   = (string) $needle;
        if ($needle === '') return true;
        return strncmp($haystack, $needle, strlen($needle)) === 0;
    }
}

/**
 * Register REST route
 */
add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/site-audit-checks', array(
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_run_site_audit_checks',
        // IMPORTANT: keep output same; only change auth mechanism to shared API-key check.
        'permission_callback' => 'myaio_sac_rest_permission_check',
    ));
});

/**
 * REST callback (PHP 5.6+ compatible)
 */
if (!function_exists('myaio_run_site_audit_checks')) {
    function myaio_run_site_audit_checks($request) {

        // 1) Gather site URLs (uses your existing helper in includes/sac-utils.php if present)
        $urls = myaio_sac_get_all_site_urls();

        // 2) SITEMAP
        $sitemap_url      = home_url('/sitemap.xml');
        $sitemap_includes = array();

        $sitemap_resp = wp_safe_remote_get($sitemap_url, array(
            'timeout'     => 10,
            'redirection' => 3,
            'headers'     => array(
                'User-Agent' => 'MyAIO-SEO-SiteAudit/1.0; ' . home_url(),
            ),
        ));

        if (!is_wp_error($sitemap_resp)) {
            $sitemap_body = wp_remote_retrieve_body($sitemap_resp);
            if (!empty($sitemap_body)) {
                if (function_exists('simplexml_load_string')) {
                    $xml = @simplexml_load_string($sitemap_body);
                    if ($xml && isset($xml->url)) {
                        foreach ($xml->url as $u) {
                            $loc = (string) $u->loc;
                            if ($loc !== '') {
                                $sitemap_includes[] = esc_url_raw(trim($loc));
                            }
                        }
                    } else {
                        $sitemap_includes = myaio_sac_extract_locs_from_xml($sitemap_body);
                    }
                } else {
                    $sitemap_includes = myaio_sac_extract_locs_from_xml($sitemap_body);
                }
            }
        }

        // 3) ROBOTS.TXT
        $robots_url   = home_url('/robots.txt');
        $robots_rules = array(); // Disallow rules
        $allow_all    = true;

        $robots_resp = wp_safe_remote_get($robots_url, array(
            'timeout'     => 10,
            'redirection' => 3,
            'headers'     => array(
                'User-Agent' => 'MyAIO-SEO-SiteAudit/1.0; ' . home_url(),
            ),
        ));

        if (!is_wp_error($robots_resp)) {
            $robots_txt = wp_remote_retrieve_body($robots_resp);
            if (!empty($robots_txt)) {
                $lines = preg_split('/\R/', strtolower($robots_txt));
                if (is_array($lines)) {
                    foreach ($lines as $line) {
                        $line = trim($line);
                        if ($line === '' || myaio_sac_starts_with($line, '#')) continue;

                        if (preg_match('/^disallow:\s*(\/[^\s]*)/i', $line, $m)) {
                            $rule = trim($m[1]);
                            if ($rule !== '') {
                                $robots_rules[] = $rule;
                                $allow_all      = false;
                            }
                        }
                    }
                }
            }
        }

        // 4) Fast lookup for sitemap membership (exact match on URL string)
        $sitemap_lookup = array();
        foreach ($sitemap_includes as $loc) {
            $sitemap_lookup[$loc] = true;
        }

        // 5) Evaluate each URL
        $results = array();
        foreach ($urls as $entry) {
            $url = isset($entry['url']) ? $entry['url'] : '';
            if ($url === '') continue;

            $parsed = wp_parse_url($url);
            if ($parsed === false || !is_array($parsed)) $parsed = array();

            $path = isset($parsed['path']) ? (string) $parsed['path'] : '/';
            $slug = trim($path, '/');

            $in_sitemap = isset($sitemap_lookup[$url]);

            // Robots allowed?
            $is_allowed = true;
            if (!$allow_all && !empty($robots_rules)) {
                foreach ($robots_rules as $rule) {
                    if ($rule === '/') {
                        $is_allowed = false;
                        break;
                    }
                    if ($rule !== '' && myaio_sac_starts_with($path, $rule)) {
                        $is_allowed = false;
                        break;
                    }
                }
            }

            // HTTP -> HTTPS redirect check (keep same logic/conditions)
            $http_url = myaio_sac_force_scheme($url, 'http');
            $https_redirect = false;

            if ($http_url !== $url) {
                $check = wp_safe_remote_get($http_url, array(
                    'redirection' => 0,
                    'timeout'     => 10,
                    'headers'     => array(
                        'User-Agent' => 'MyAIO-SEO-SiteAudit/1.0; ' . home_url(),
                    ),
                ));
                if (!is_wp_error($check)) {
                    $code     = (int) wp_remote_retrieve_response_code($check);
                    $location = wp_remote_retrieve_header($check, 'location');
                    if (($code === 301 || $code === 302) && is_string($location) && myaio_sac_starts_with($location, 'https://')) {
                        $https_redirect = true;
                    }
                }
            }

            $results[] = array(
                'url'            => $url,
                'slug'           => $slug,
                'slug_defined'   => ($slug !== '' && strpos($slug, '?') === false),
                'in_sitemap'     => (bool) $in_sitemap,
                'robots_allowed' => $allow_all || $is_allowed,
                'https_redirect' => $https_redirect,
                'type'           => isset($entry['type']) ? $entry['type'] : null,
            );
        }

        return rest_ensure_response(array(
            'sitemap_url' => $sitemap_url,
            'robots_url'  => $robots_url,
            'results'     => $results,
        ));
    }
}

/**
 * Helper: extract <loc>…</loc> values from sitemap XML (fallback).
 */
if (!function_exists('myaio_sac_extract_locs_from_xml')) {
    function myaio_sac_extract_locs_from_xml($xml_string) {
        $locs = array();
        if (!is_string($xml_string) || $xml_string === '') return $locs;

        if (preg_match_all('/<\s*loc\s*>\s*([^<]+)\s*<\s*\/\s*loc\s*>/i', $xml_string, $m)) {
            if (!empty($m[1]) && is_array($m[1])) {
                foreach ($m[1] as $loc) {
                    $loc = trim($loc);
                    if ($loc !== '') {
                        $locs[] = esc_url_raw($loc);
                    }
                }
            }
        }
        return $locs;
    }
}

/**
 * Helper: force URL scheme (http/https) safely on PHP 5.6+.
 */
if (!function_exists('myaio_sac_force_scheme')) {
    function myaio_sac_force_scheme($url, $scheme) {
        $scheme = ($scheme === 'https') ? 'https' : 'http';
        $parts = wp_parse_url($url);
        if ($parts === false || !is_array($parts)) return $url;

        $parts['scheme'] = $scheme;

        $rebuilt = $parts['scheme'] . '://';

        if (isset($parts['user'])) {
            $rebuilt .= $parts['user'];
            if (isset($parts['pass'])) $rebuilt .= ':' . $parts['pass'];
            $rebuilt .= '@';
        }

        if (isset($parts['host'])) $rebuilt .= $parts['host'];
        if (isset($parts['port'])) $rebuilt .= ':' . $parts['port'];
        if (isset($parts['path'])) $rebuilt .= $parts['path'];
        if (isset($parts['query'])) $rebuilt .= '?' . $parts['query'];
        if (isset($parts['fragment'])) $rebuilt .= '#' . $parts['fragment'];

        return $rebuilt;
    }
}
