<?php
// File: modules/page-depth-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', '/page-depth', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_get_pages_by_depth',
        'permission_callback' => 'myaio_sac_rest_permission_check',
        'args'                => [
            'depth' => [
                'required'          => true,
                'validate_callback' => function ($param) {
                    return is_numeric($param) && (int)$param >= 1 && (int)$param <= 5;
                }
            ]
        ]
    ]);
});

if (!function_exists('myaio_sac_get_pages_by_depth')) {
    function myaio_sac_get_pages_by_depth(WP_REST_Request $request) {
        $max_depth = (int) $request->get_param('depth');
        $all_results = [];

        $pages_by_parent = [];
        $pages = get_pages(['post_status' => 'publish']);

        foreach ($pages as $page) {
            $pages_by_parent[$page->post_parent][] = $page;
        }

        // Pre-fetch robots.txt (keep same behavior: if empty, checks reflect that)
        $robots_url = home_url('/robots.txt');
        $robots_res = wp_safe_remote_get($robots_url, ['timeout' => 12, 'redirection' => 3]);
        $robots_raw = is_wp_error($robots_res) ? '' : (string) wp_remote_retrieve_body($robots_res);
        $robots_lines = preg_split("/\r\n|\n|\r/", (string) $robots_raw);

        // Pre-fetch sitemap
        $sitemap_url = home_url('/sitemap.xml');
        $sitemap_res = wp_safe_remote_get($sitemap_url, ['timeout' => 12, 'redirection' => 3]);
        $sitemap_raw = is_wp_error($sitemap_res) ? '' : (string) wp_remote_retrieve_body($sitemap_res);
        preg_match_all('/<loc>(.*?)<\/loc>/', (string) $sitemap_raw, $matches);
        $sitemap_urls = array_map('trim', $matches[1] ?? []);

        $process_pages = function ($parent_id, $current_depth) use (
            &$process_pages,
            $pages_by_parent,
            &$all_results,
            $max_depth,
            $robots_lines,
            $sitemap_urls
        ) {
            if (!isset($pages_by_parent[$parent_id]) || $current_depth > $max_depth) return;

            foreach ($pages_by_parent[$parent_id] as $page) {
                $url = get_permalink($page);
                $title = get_the_title($page);
                $h1 = '';
                $h2 = [];

                // Fetch page HTML
                $page_res = wp_safe_remote_get($url, [
                    'timeout'     => 15,
                    'redirection' => 5,
                    'headers'     => [
                        'User-Agent' => 'MyAIO-SEO-PageDepth/1.0; ' . home_url(),
                    ],
                ]);
                $html = is_wp_error($page_res) ? '' : (string) wp_remote_retrieve_body($page_res);

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

                    // Get H1
                    $h1_tags = $dom->getElementsByTagName('h1');
                    if ($h1_tags->length > 0) {
                        $h1 = trim((string) $h1_tags->item(0)->nodeValue);
                    }

                    // Get H2
                    $h2_tags = $dom->getElementsByTagName('h2');
                    foreach ($h2_tags as $node) {
                        $text = trim((string) $node->nodeValue);
                        if ($text) $h2[] = $text;
                    }
                }

                // Robots.txt checks (same keys/values)
                $robot_checks = [
                    'present'            => !empty($robots_lines),
                    'has_sitemap'        => false,
                    'no_block_assets'    => true,
                    'correct_syntax'     => true,
                    'not_barebone'       => false,
                    'no_crawl_delay'     => true,
                    'canonical_only'     => true,
                    'absolute_sitemap'   => false,
                    'valid_directives'   => true,
                    'sitemap_accessible' => false,
                ];

                foreach ($robots_lines as $line) {
                    $line = trim((string) $line);

                    if (stripos($line, 'Sitemap:') === 0) {
                        $robot_checks['has_sitemap'] = true;

                        if (preg_match('/^Sitemap:\s*(https?:\/\/[^ ]+)/i', $line, $match)) {
                            $robot_checks['absolute_sitemap'] = true;

                            $resp = wp_safe_remote_head($match[1], ['timeout' => 10, 'redirection' => 3]);
                            $robot_checks['sitemap_accessible'] = !is_wp_error($resp) && (int) wp_remote_retrieve_response_code($resp) === 200;
                        }
                    }

                    if (preg_match('/Disallow:\s*\/.*\*/i', $line)) {
                        $robot_checks['no_block_assets'] = false;
                    }

                    if (stripos($line, 'Crawl-delay') !== false) {
                        $robot_checks['no_crawl_delay'] = false;
                    }

                    if (!preg_match('/^(User-agent|Disallow|Allow|Sitemap|#|$)/i', $line)) {
                        $robot_checks['valid_directives'] = false;
                    }
                }

                $directives = array_filter($robots_lines, function ($l) {
                    $l = trim((string) $l);
                    return $l !== '' && stripos($l, '#') !== 0;
                });
                $robot_checks['not_barebone'] = count($directives) >= 3;

                $in_sitemap = in_array($url, $sitemap_urls, true);

                // HTTP -> HTTPS redirect check (same output boolean)
                $parsed = wp_parse_url($url);
                $redirects_to_https = false;

                if (!empty($parsed['host'])) {
                    $http_url = 'http://' . $parsed['host'] . ($parsed['path'] ?? '/');
                    $check_https = wp_safe_remote_get($http_url, ['redirection' => 5, 'timeout' => 12]);

                    if (!is_wp_error($check_https)) {
                        $final_url = wp_remote_retrieve_header($check_https, 'location');
                        if (is_string($final_url) && stripos($final_url, 'https://') === 0) {
                            $redirects_to_https = true;
                        }
                    }
                }

                $slug_defined = !empty($page->post_name);

                $all_results[] = [
                    'url'               => $url,
                    'title'             => $title,
                    'h1'                => $h1,
                    'h2'                => $h2,
                    'depth'             => $current_depth,
                    'slug_defined'      => $slug_defined,
                    'in_sitemap'        => $in_sitemap,
                    'redirects_to_https'=> $redirects_to_https,
                    'robots_txt_checks' => $robot_checks
                ];

                $process_pages($page->ID, $current_depth + 1);
            }
        };

        $process_pages(0, 1);

        return rest_ensure_response([
            'depth'   => $max_depth,
            'results' => $all_results
        ]);
    }
}
