<?php
/**
 * The Tools AJAX handler.
 *
 * @package SEO_Pro_Stack
 * @subpackage SEO_Pro_Stack/Admin/Settings/AJAX
 */

// If this file is called directly, abort.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * The Tools AJAX handler.
 */
class SEOProStack_AJAX_Tools {

    /**
     * Initialize the AJAX handlers.
     */
    public function init() {
        add_action('wp_ajax_seoprostack_generate_robots', array($this, 'generate_robots'));
    }

    /**
     * Generate robots.txt file content.
     */
    public function generate_robots() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'seoprostack_ajax_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed'));
        }

        // Check capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to generate robots.txt'));
        }

        // Generate robots.txt content
        $site_url = get_home_url();
        $parsed_url = parse_url($site_url);
        $host = $parsed_url['host'];

        $content = "# SEO Pro Stack generated robots.txt\n";
        $content .= "# Generated on: " . date('Y-m-d H:i:s') . "\n\n";
        $content .= "User-agent: *\n";
        
        // Disallow WordPress admin
        $content .= "Disallow: /wp-admin/\n";
        
        // Allow assets and ajax
        $content .= "Allow: /wp-admin/admin-ajax.php\n";
        $content .= "Allow: /wp-includes/*.js\n";
        $content .= "Allow: /wp-includes/*.css\n";
        $content .= "Allow: /wp-content/uploads/\n";
        
        // Disallow common WordPress files and directories
        $content .= "Disallow: /wp-includes/\n";
        $content .= "Disallow: /readme.html\n";
        $content .= "Disallow: /license.txt\n";
        $content .= "Disallow: /xmlrpc.php\n";
        $content .= "Disallow: /wp-json/\n";
        
        // Add sitemap if Yoast SEO or other SEO plugin is active
        if (function_exists('wpseo_init') || defined('AIOSEO_VERSION') || defined('RANK_MATH_VERSION')) {
            $content .= "\n# XML Sitemap\n";
            $content .= "Sitemap: " . trailingslashit($site_url) . "sitemap_index.xml\n";
        }
        
        // Send response
        wp_send_json_success(array(
            'message' => 'Robots.txt content generated successfully.',
            'content' => $content
        ));
    }
}