<?php

/**
 * Virtual IndexNow key file responder.
 *
 * @package ProRank\SEO\Frontend
 */

declare(strict_types=1);

namespace ProRank\SEO\Frontend;

use ProRank\SEO\Core\Config\Settings;

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




defined( 'ABSPATH' ) || exit;

class IndexNowVirtualFile {
    /**
     * Register hooks.
     */
    public function init(): void {
        add_action( 'template_redirect', [ $this, 'maybe_serve_key' ], 0 );
    }

    /**
     * Serve the IndexNow key as a virtual root file.
     */
    public function maybe_serve_key(): void {
        if ( is_admin() || wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
            return;
        }

        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
        if ( $request_uri === '' ) {
            return;
        }

        $path = wp_parse_url( $request_uri, PHP_URL_PATH );
        if ( ! is_string( $path ) || $path === '' ) {
            return;
        }

        $path = trim( $path, '/' );
        if ( $path === '' ) {
            return;
        }

        $key = $this->get_indexnow_key();
        if ( $key !== '' && $path === $key . '.txt' ) {
            $this->send_text_response( $key );
        }
    }

    /**
     * Fetch IndexNow key from settings.
     *
     * @return string
     */
    private function get_indexnow_key(): string {
        $settings = Settings::get( 'robots_indexing', [] );
        if ( ! is_array( $settings ) ) {
            return '';
        }

        if ( empty( $settings['enable_indexnow'] ) ) {
            return '';
        }

        $key = $settings['indexnow_api_key'] ?? '';
        return is_string( $key ) ? trim( $key ) : '';
    }

    /**
     * Send a plain-text response and exit.
     *
     * @param string $content Response body.
     */
    private function send_text_response( string $content ): void {
        if ( headers_sent() ) {
            return;
        }

        nocache_headers();
        header( 'Content-Type: text/plain; charset=utf-8' );
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- plain text verification response
        echo $content;
        exit;
    }
}
