<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
// SEO Audit Module - Crawl Pages and Prepare API Endpoint (with API Key protection)

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

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/crawl-site', [
        'methods'  => 'GET',
        'callback' => 'myaio_sac_crawl_site',
        'permission_callback' => 'myaio_sac_crawl_site_permission',
    ]);
});

/**
 * Permission callback for crawl-site endpoint
 * Uses the shared myaio_sac_validate_api_key() from includes/sac-utils.php
 */
if ( ! function_exists('myaio_sac_crawl_site_permission') ) {
    function myaio_sac_crawl_site_permission( WP_REST_Request $request ) {
        if ( function_exists('myaio_sac_validate_api_key') && myaio_sac_validate_api_key($request) ) {
            return true;
        }
        return new WP_Error('unauthorized', 'Invalid or unverified API key', ['status' => 401]);
    }
}


/**
 * Main crawl function
 */
function myaio_sac_crawl_site() {
    try {
        $urls = myaio_sac_audit_get_all_site_urls();
        $results = [];

        foreach ($urls as $entry) {
            $url = $entry['url'];
            $type = $entry['type'];

            $post_id = url_to_postid($url);
            if (!$post_id) continue;

            $post = get_post($post_id);
            if (!$post) continue;

            $content_html = $post->post_content;
            if (empty($content_html)) continue;

            libxml_use_internal_errors(true);
            $dom = new DOMDocument();
            @$dom->loadHTML(mb_convert_encoding($content_html, 'HTML-ENTITIES', 'UTF-8'));

            // Title
            $seo_title = get_post_meta($post_id, '_myaio_seo_title', true);
            $title = !empty($seo_title) ? $seo_title : wp_get_document_title($post_id);
            $title_length = mb_strlen($title);

            // Meta
            $metaDesc = get_post_meta($post_id, '_myaio_meta_description', true);
            $metaDesc_length = mb_strlen($metaDesc);

            $metaKeywords = get_post_meta($post_id, '_myaio_meta_keywords', true);
            $metaKeywords_length = mb_strlen($metaKeywords);

            // Headings H1-H4
            $heading_data = [];
            $heading_tags = ['h1','h2','h3','h4'];
            foreach ($heading_tags as $tag) {
                $nodes = $dom->getElementsByTagName($tag);
                $items = [];
                $index = 1;
                foreach ($nodes as $node) {
                    $text = trim($node->nodeValue);
                    $items[] = [
                        'index' => $index,
                        'text' => $text,
                        'length' => mb_strlen($text),
                        'within_limit' => mb_strlen($text) <= 60
                    ];
                    $index++;
                }
                $heading_data[$tag] = $items;
            }

            // Images missing alt
            $missingAltImages = [];
            foreach ($dom->getElementsByTagName('img') as $img) {
                $src = $img->getAttribute('src');
                $alt = trim($img->getAttribute('alt'));
                if ($src && $alt === '') {
                    $missingAltImages[] = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif|webp))/i', '', $src);
                }
            }

            // Compile issues
            $issues = [];
            if (empty($title)) $issues[] = 'Missing title tag';
            if ($title_length > 60) $issues[] = 'Title exceeds 60 characters';
            if (empty($metaDesc)) $issues[] = 'Missing meta description';
            if ($metaDesc_length > 160) $issues[] = 'Meta description exceeds 160 characters';
            if (empty($metaKeywords)) $issues[] = 'Missing meta keywords';
            if ($metaKeywords_length > 255) $issues[] = 'Meta keywords exceeds 255 characters';
            foreach ($heading_tags as $tag) {
                if (empty($heading_data[$tag])) $issues[] = "Missing $tag tag";
            }
            foreach ($missingAltImages as $imgUrl) {
                $issues[] = "Image missing alt: $imgUrl";
            }

            $results[] = [
                'url' => $url,
                'type' => $type,
                'title' => $title,
                'title_length' => $title_length,
                'meta_description' => $metaDesc,
                'meta_description_length' => $metaDesc_length,
                'meta_keywords' => $metaKeywords,
                'meta_keywords_length' => $metaKeywords_length,
                'headings' => $heading_data,
                'images_missing_alt' => $missingAltImages,
                'issues' => $issues
            ];
        }

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

    } catch (Throwable $e) {
        return new WP_REST_Response([
            'error' => 'Internal Server Error',
            'message' => $e->getMessage(),
        ], 500);
    }
}

/**
 * Helper function to get all site URLs (posts + pages)
 */
function myaio_sac_audit_get_all_site_urls() {
    $urls = [];
    $args = [
        'post_type' => ['post','page'],
        'post_status' => 'publish',
        'fields' => 'ids',
        'posts_per_page' => -1
    ];
    $posts = get_posts($args);
    foreach ($posts as $post_id) {
        $urls[] = [
            'url' => get_permalink($post_id),
            'type' => get_post_type($post_id)
        ];
    }
    return $urls;
}
