<?php
// File: modules/seo-summary.php

if ( ! defined('ABSPATH') ) { exit; }

// Use the 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', '/seo-summary', [
        'methods'             => 'GET',
        'callback'            => 'myaio_sac_seo_summary',
        'permission_callback' => 'myaio_sac_seo_summary_permission',
    ]);
});

/**
 * Permission callback for seo-summary endpoint
 * Uses the shared myaio_sac_validate_api_key() from includes/sac-utils.php
 */
if ( ! function_exists('myaio_sac_seo_summary_permission') ) {
    function myaio_sac_seo_summary_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]);
    }
}

function myaio_sac_seo_summary(WP_REST_Request $request) {
    $post_types = ['post', 'page'];
    $total_titles = 0;
    $total_meta_desc = 0;
    $no_meta_desc = 0;
    $total_pages = 0;
    $data = [];

    $all_posts = get_posts([
        'post_type'   => $post_types,
        'post_status' => 'publish',
        'numberposts' => -1
    ]);

    foreach ($all_posts as $post) {
        $title = trim($post->post_title);
        $has_title = !empty($title);

        if ($has_title) {
            $total_titles++;
        }

        // Try fetching meta description from popular SEO plugins
        $meta_desc = get_post_meta($post->ID, '_yoast_wpseo_metadesc', true); // Yoast
        if (!$meta_desc) {
            $meta_desc = get_post_meta($post->ID, '_aioseo_description', true); // AIOSEO
        }

        $has_meta = $meta_desc && trim($meta_desc) !== '';
        if ($has_meta) {
            $total_meta_desc++;
        } else {
            $no_meta_desc++;
        }

        if ($post->post_type === 'page') {
            $total_pages++;
        }

        $data[] = [
            'id' => $post->ID,
            'title' => $title,
            'type' => ucfirst($post->post_type),
            'url' => get_permalink($post),
            'has_meta_description' => $has_meta
        ];
    }

    return rest_ensure_response([
        'summary' => [
            'total_posts_and_pages' => count($all_posts),
            'total_pages' => $total_pages,
            'total_titles' => $total_titles,
            'meta_descriptions_found' => $total_meta_desc,
            'missing_meta_descriptions' => $no_meta_desc
        ],
        'data' => $data
    ]);
}
