<?php
/**
 * Virtual text file responses for root requests.
 *
 * @package ProRank\SEO\Frontend
 */

declare(strict_types=1);

namespace ProRank\SEO\Frontend;

use ProRank\SEO\Core\Config\Settings;
defined( 'ABSPATH' ) || exit;

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

    /**
     * Serve virtual root files.
     */
    public function maybe_serve_virtual_file(): 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;
        }

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

    /**
     * Get IndexNow API key for virtual key file.
     *
     * @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 plain text response and exit.
     *
     * @param string $content
     * @return void
     */
    private function send_text_response( string $content ): void {
        nocache_headers();
        header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) );
        echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Plain text output.
        exit;
    }
}
