<?php
$dir = __DIR__;
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach ($files as $file) {
    if ($file->isDir()) continue;
    if ($file->getExtension() !== 'php') continue;
    if ($file->getFilename() === 'fix_capabilities.php') continue;
    
    $content = file_get_contents($file->getPathname());
    
    // We want to find check_ajax_referer(...) and if it doesn't have current_user_can after it, we insert it.
    // A regex to match check_ajax_referer line
    $lines = explode("\n", $content);
    $modified = false;
    
    for ($i = 0; $i < count($lines); $i++) {
        if (strpos($lines[$i], 'check_ajax_referer') !== false) {
            // Check next lines for current_user_can
            $has_cap_check = false;
            for ($j = $i + 1; $j <= min($i + 5, count($lines) - 1); $j++) {
                if (strpos($lines[$j], 'current_user_can') !== false) {
                    $has_cap_check = true;
                    break;
                }
                // If we encounter another check_ajax_referer, break
                if (strpos($lines[$j], 'check_ajax_referer') !== false) {
                    break;
                }
            }
            
            if (!$has_cap_check) {
                // Determine indentation
                preg_match('/^(\s*)/', $lines[$i], $matches);
                $indent = $matches[1] ?? '        ';
                
                $cap_block = [
                    "",
                    $indent . "if ( ! current_user_can( 'manage_options' ) ) {",
                    $indent . "    wp_send_json_error( esc_html__( 'Unauthorized', 'seo-help' ) );",
                    $indent . "    wp_die();",
                    $indent . "}"
                ];
                
                array_splice($lines, $i + 1, 0, $cap_block);
                $modified = true;
                $i += count($cap_block); // Skip the newly inserted lines
            }
        }
    }
    
    if ($modified) {
        file_put_contents($file->getPathname(), implode("\n", $lines));
        echo "Modified: " . $file->getPathname() . "\n";
    }
}
