<?php
// File: modules/robots-manager.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', '/get-robots', [
        'methods'             => WP_REST_Server::READABLE, // GET
        'callback'            => 'myaio_sac_get_robots_txt',
        'permission_callback' => 'myaio_sac_permission_check',
    ]);

    register_rest_route('myaio/v1', '/update-robots', [
        'methods'             => WP_REST_Server::CREATABLE, // POST
        'callback'            => 'myaio_sac_update_robots_txt',
        'permission_callback' => 'myaio_sac_permission_check',
        'args' => [
            'content' => [
                'required' => true,
                'type'     => 'string',
            ],
        ],
    ]);
});

/**
 * Permission callback: return true or WP_Error.
 * Uses the shared myaio_sac_validate_api_key() from includes/sac-utils.php
 */
if ( ! function_exists('myaio_sac_permission_check') ) {
    function myaio_sac_permission_check( WP_REST_Request $request ) {
        if ( function_exists('myaio_sac_validate_api_key') && myaio_sac_validate_api_key( $request ) ) {
            return true;
        }
        return new WP_Error( 'rest_forbidden', 'Unauthorized', [ 'status' => 401 ] );
    }
}

function myaio_sac_get_robots_txt(WP_REST_Request $request) {
    $file_path  = trailingslashit(ABSPATH) . 'robots.txt';
    $robots_url = home_url('/robots.txt');

    if (!file_exists($file_path)) {
        return new WP_REST_Response([
            'content'    => '',
            'message'    => 'robots.txt not found.',
            'path'       => $file_path,
            'robots_url' => $robots_url,
            'issues'     => ['robots.txt file is missing.']
        ], 200);
    }

    $content = @file_get_contents($file_path);
    if ($content === false) {
        return new WP_Error('read_failed', 'Could not read robots.txt', ['status' => 500]);
    }

    $issues = [];

    // Check 1: Sitemap presence
    if (!preg_match('/^sitemap:\s*https?:\/\/.+/im', $content)) {
        $issues[] = 'Sitemap missing in robots.txt';
    }

    // Check 2: Assets not blocked
    if (preg_match('/disallow:\s*\/\*/i', $content)) {
        $issues[] = 'No assets blocked through robots.txt – contains wildcard block (/*)';
    }

    // Check 3: Correct syntax (basic validation)
    if (preg_match('/[^a-z0-9\/\-\:\s\*\.]/i', $content)) {
        $issues[] = 'Robots.txt file might contain invalid syntax characters';
    }

    // Check 4: Content not barebone (too small or simple)
    $lineCount = substr_count(trim($content), "\n");
    if ($lineCount < 4) {
        $issues[] = 'Robots.txt content is too simple, consider adding more directives';
    }

    // Check 6: No crawl-delay directive
    if (preg_match('/crawl-delay\s*:/i', $content)) {
        $issues[] = 'Robots.txt should not include crawl-delay directive';
    }

    // Check 8: Sitemaps must use absolute URLs
    if (preg_match('/^sitemap:\s*(?!https?:\/\/)/im', $content)) {
        $issues[] = 'Sitemap must use absolute URL';
    }

    // Check 10: Sitemap is accessible
    if (preg_match('/^sitemap:\s*(https?:\/\/[^\s]+)/im', $content, $matches)) {
        $sitemap_url = trim($matches[1]);
        $sitemap_check = wp_remote_get($sitemap_url);
        if (is_wp_error($sitemap_check) || wp_remote_retrieve_response_code($sitemap_check) >= 400) {
            $issues[] = 'Referenced sitemap is not accessible';
        }
    }

    if (!empty($issues)) {
        return new WP_REST_Response([
            'content'    => $content,
            'path'       => $file_path,
            'robots_url' => $robots_url,
            'issues'     => $issues,
            'status'     => 'issues_found'
        ], 200);
    }

    return new WP_REST_Response([
        'content'    => $content,
        'path'       => $file_path,
        'robots_url' => $robots_url,
        'status'     => 'ok',
        'message'    => 'robots.txt passed all SEO checks'
    ], 200);
}

function myaio_sac_update_robots_txt( WP_REST_Request $request ) {
    global $wp_filesystem;

    $content   = (string) $request->get_param( 'content' );
    $file_path = trailingslashit( ABSPATH ) . 'robots.txt';

    // Initialize WP_Filesystem
    if ( ! function_exists( 'WP_Filesystem' ) ) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
    }

    WP_Filesystem();

    // Ensure filesystem API initialized
    if ( ! $wp_filesystem ) {
        return new WP_Error( 'fs_unavailable', 'Unable to initialize WP_Filesystem.', [ 'status' => 500 ] );
    }

    // Create the file if missing
    if ( ! $wp_filesystem->exists( $file_path ) ) {
        if ( ! $wp_filesystem->is_writable( ABSPATH ) ) {
            return new WP_Error( 'write_denied', 'The WordPress root is not writable.', [ 'status' => 500 ] );
        }

        // Safely create an empty robots.txt file
        $wp_filesystem->put_contents( $file_path, '', FS_CHMOD_FILE );
    }

    // Check write permissions
    if ( ! $wp_filesystem->is_writable( $file_path ) ) {
        return new WP_Error( 'write_denied', 'robots.txt is not writable.', [ 'status' => 500 ] );
    }

    // Write new content using WP_Filesystem
    $written = $wp_filesystem->put_contents( $file_path, $content, FS_CHMOD_FILE );

    if ( ! $written ) {
        return new WP_Error( 'write_failed', 'Failed to write robots.txt', [ 'status' => 500 ] );
    }

    return new WP_REST_Response( [
        'updated'   => true,
        'file_path' => $file_path,
        'content'   => $content,
    ], 200 );
}
