<?php
// Защита от прямого доступа
if (!defined('ABSPATH')) {
    exit;
}

function ai_content_wizard_system_check_page() {
    echo '<div class="wrap">';
    echo '<h1>' . __('System Check for AI Content Wizard', 'ai-content-wizard') . '</h1>';
    ai_content_wizard_display_system_check();
    echo '</div>';
}

function ai_content_wizard_display_system_check() {
    $results = ai_content_wizard_system_check();

    // Подсчёт статусов
    $okCount = 0; $warnCount = 0; $failCount = 0;
    foreach ($results as $r) {
        $s = isset($r[3]) ? $r[3] : 'Fail';
        if ($s === 'OK') { $okCount++; }
        elseif ($s === 'warning') { $warnCount++; }
        else { $failCount++; }
    }

    // Стили (только для этой страницы)
    echo '<style>'
        .'.acw-sys-wrap{max-width:1200px;margin-top:14px}'
        .'.acw-sys-summary{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin:12px 0 16px 0}'
        .'.acw-card{border-radius:12px;padding:14px 16px;background:#fff;box-shadow:0 6px 20px rgba(0,0,0,.06),0 1px 3px rgba(0,0,0,.07);display:flex;align-items:center;gap:12px}'
        .'.acw-card h3{margin:0;font-size:13px;color:#6b7280;font-weight:600;letter-spacing:.2px;text-transform:uppercase}'
        .'.acw-card .val{margin-left:auto;font-size:18px;font-weight:700}'
        .'.ok .val{color:#16a34a}.warn .val{color:#d97706}.fail .val{color:#dc2626}'
        .'.acw-toolbar{margin:14px 0 8px;display:flex;gap:8px;flex-wrap:wrap}'
        .'.acw-table{width:100%;border-collapse:separate;border-spacing:0 8px}'
        .'.acw-table thead th{font-size:12px;text-transform:uppercase;letter-spacing:.3px;color:#6b7280;font-weight:700;text-align:left;padding:10px 12px}'
        .'.acw-row{background:#fff;border-radius:12px;box-shadow:0 3px 14px rgba(0,0,0,.05),0 1px 2px rgba(0,0,0,.06)}'
        .'.acw-row td{padding:12px 12px;border-top:1px solid #eef2f7}'
        .'.acw-row td:first-child{border-left:1px solid #eef2f7;border-top-left-radius:12px;border-bottom-left-radius:12px}'
        .'.acw-row td:last-child{border-right:1px solid #eef2f7;border-top-right-radius:12px;border-bottom-right-radius:12px}'
        .'.acw-status{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;font-size:12px;font-weight:700}'
        .'.acw-status--ok{background:#ecfdf5;color:#065f46}.acw-status--warning{background:#fff7ed;color:#9a3412}.acw-status--fail{background:#fef2f2;color:#991b1b}'
        /* Column separators */
        .'.acw-row td:not(:last-child){border-right:1px solid #e5e7eb;}'
        /* Bold first column */
        .'.acw-row td:first-child{font-weight:600;}'
        /* Gentle row background by status */
        .'.acw-row.ok{background-color:#f0fdf4;}'
        .'.acw-row.warning{background-color:#fffbeb;}'
        .'.acw-row.fail{background-color:#fef2f2;}'
        .'.help-link{font-size:12px}'
        .'.acw-sys-note{font-size:12px;color:#6b7280;margin-top:6px}'
        .'.acw-sys-modal-overlay{position:fixed;inset:0;z-index:100000;background:rgba(0,0,0,.45);backdrop-filter:saturate(120%) blur(4px);display:none}'
        .'.acw-sys-modal{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(720px,calc(100% - 40px));background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.25),0 2px 10px rgba(0,0,0,.08)}'
        .'.acw-sys-head{display:flex;align-items:center;gap:12px;padding:16px 18px;background:linear-gradient(135deg,#1f2937 0%,#111827 100%);color:#fff}'
        .'.acw-sys-title{margin:0;font-size:17px;font-weight:700}'
        .'.acw-sys-body{padding:18px 20px;color:#1d2327}'
        .'.acw-sys-actions{display:flex;gap:10px;justify-content:flex-end;padding:14px 18px;background:#f8fafc;border-top:1px solid #eef2f7}'
        .'.acw-sys-copy{border:1px solid #e5e7eb;background:#fff;border-radius:8px;height:36px;padding:0 12px}'
        .'.acw-sys-close{border:none;background:linear-gradient(135deg,#10b981,#059669);color:#fff;border-radius:8px;height:36px;padding:0 14px;font-weight:600;box-shadow:0 6px 16px rgba(16,185,129,.25)}'
        .'.acw-msg{white-space:pre-wrap;word-break:break-word;background:#f9fafb;border:1px solid #eef2f7;border-radius:8px;padding:12px;font-size:13px}'
        .'@media(max-width:720px){.acw-sys-summary{grid-template-columns:1fr}}'
        .'</style>';

    echo '<div class="acw-sys-wrap">';

    // Summary
    echo '<div class="acw-sys-summary">';
    echo '<div class="acw-card ok"><h3>' . esc_html__('OK', 'ai-content-wizard') . '</h3><span class="val">' . intval($okCount) . '</span></div>';
    echo '<div class="acw-card warn"><h3>' . esc_html__('Warnings', 'ai-content-wizard') . '</h3><span class="val">' . intval($warnCount) . '</span></div>';
    echo '<div class="acw-card fail"><h3>' . esc_html__('Fails', 'ai-content-wizard') . '</h3><span class="val">' . intval($failCount) . '</span></div>';
    echo '</div>';

    echo '<h2 style="margin-top:6px;">' . esc_html__('System Check', 'ai-content-wizard') . '</h2>';

    // Toolbar
    $export_url = wp_nonce_url( admin_url('admin-post.php?action=acw_export_diagnostics'), 'acw_export_diag');
    $phpinfo_url = wp_nonce_url( admin_url('admin-post.php?action=acw_phpinfo'), 'acw_phpinfo');
    echo '<div class="acw-toolbar">';
    echo '<a class="button button-primary" href="' . esc_url($export_url) . '">' . esc_html__('Export Diagnostics (JSON)', 'ai-content-wizard') . '</a>';
    echo '<a class="button" target="_blank" rel="noopener" href="' . esc_url($phpinfo_url) . '">' . esc_html__('Open PHP Info (new tab)', 'ai-content-wizard') . '</a>';
    echo '</div>';

    // Table
    echo '<table class="acw-table">';
    echo '<thead><tr>'
        .'<th>' . esc_html__('Requirement', 'ai-content-wizard') . '</th>'
        .'<th>' . esc_html__('Current Value', 'ai-content-wizard') . '</th>'
        .'<th>' . esc_html__('Required Value', 'ai-content-wizard') . '</th>'
        .'<th>' . esc_html__('Status', 'ai-content-wizard') . '</th>'
        .'<th>' . esc_html__('Recommendation', 'ai-content-wizard') . '</th>'
        .'</tr></thead><tbody>';

    foreach ($results as $result) {
        $status = isset($result[3]) ? $result[3] : 'Fail';
        $status_text = ($status === 'OK') ? esc_html__('OK', 'ai-content-wizard') : (($status === 'warning') ? esc_html__('Warning', 'ai-content-wizard') : esc_html__('Fail', 'ai-content-wizard'));
        $status_class = ($status === 'OK') ? 'ok' : (($status === 'warning') ? 'warning' : 'fail');

        $helpMessage = ai_content_wizard_get_help_message($result[5]);

        echo '<tr class="acw-row">';
        echo '<td>' . esc_html($result[0]) . '</td>';
        echo '<td>' . esc_html($result[1]) . '</td>';
        echo '<td>' . esc_html($result[2]) . '</td>';
        echo '<td><span class="acw-status acw-status--' . esc_attr($status_class) . '">' . $status_text . '</span></td>';
        echo '<!-- Debug: Help ID = ' . esc_html($result[5]) . ' -->';
        echo '<td>' . esc_html($result[4]) . ' <a href="#" class="help-link" data-help-id="' . esc_attr($result[5]) . '" data-help-message="' . esc_attr($helpMessage) . '">' . esc_html__('Need help contacting your host?', 'ai-content-wizard') . '</a></td>';
        echo '</tr>';
    }

    echo '</tbody></table>';

    echo '<p class="acw-sys-note">' . esc_html__( 'Tip: Fewer warnings and no fails generally mean smoother long-running tasks.', 'ai-content-wizard') . '</p>';

    // Современное модальное окно для подсказок
    echo '<div id="acw-help-modal" class="acw-sys-modal-overlay" role="dialog" aria-modal="true" aria-labelledby="acw-help-title">';
    echo '  <div class="acw-sys-modal">';
    echo '    <div class="acw-sys-head">';
    echo '      <h3 id="acw-help-title" class="acw-sys-title">' . esc_html__('Help message for your host', 'ai-content-wizard') . '</h3>';
    echo '    </div>';
    echo '    <div class="acw-sys-body">';
    echo '      <div id="help-popup-message" class="acw-msg"></div>';
    echo '    </div>';
    echo '    <div class="acw-sys-actions">';
    echo '      <button type="button" class="acw-sys-copy" id="acw-help-copy">' . esc_html__('Copy', 'ai-content-wizard') . '</button>';
    echo '      <button type="button" class="acw-sys-close" id="acw-help-close">' . esc_html__('Close', 'ai-content-wizard') . '</button>';
    echo '    </div>';
    echo '  </div>';
    echo '</div>';

    // JS: обработка кликов по ссылкам и копирование
    echo '<script>'
        .'(function(){'
        .'var modal=document.getElementById("acw-help-modal");'
        .'var msgEl=document.getElementById("help-popup-message");'
        .'var btnCopy=document.getElementById("acw-help-copy");'
        .'var btnClose=document.getElementById("acw-help-close");'
        .'function openModal(html){ if(msgEl){ msgEl.innerHTML=html; } if(modal){ modal.style.display="block"; } }'
        .'function closeModal(){ if(modal){ modal.style.display="none"; } }'
        .'document.addEventListener("click",function(e){ var t=e.target; if(t && t.classList && t.classList.contains("help-link")){ e.preventDefault(); var m=t.getAttribute("data-help-message")||""; openModal(m); } });'
        .'btnClose && btnClose.addEventListener("click", closeModal);'
        .'modal && modal.addEventListener("click", function(e){ if(e.target===modal){ closeModal(); } });'
        .'document.addEventListener("keydown", function(e){ if(e.key==="Escape"){ closeModal(); } });'
        .'btnCopy && btnCopy.addEventListener("click", function(){ try{ var sel=window.getSelection(); var r=document.createRange(); r.selectNodeContents(msgEl); sel.removeAllRanges(); sel.addRange(r); document.execCommand("copy"); sel.removeAllRanges(); btnCopy.textContent="' . esc_js(__('Copied!', 'ai-content-wizard')) . '"; setTimeout(function(){ btnCopy.textContent="' . esc_js(__('Copy', 'ai-content-wizard')) . '"; }, 1500); }catch(err){} });'
        .'})();'
        .'</script>';

    echo '</div>'; // .acw-sys-wrap
}

function ai_content_wizard_get_help_message($helpId) {
    switch ($helpId) {
        case 'php-version':
            return __('Dear Hosting Provider,<br><br>I am writing to request an upgrade to the PHP version on my server. My website requires PHP version 7.1 or higher for optimal performance and security. Could you please assist with upgrading the PHP version on my server?<br><br>Thank you for your support.', 'ai-content-wizard');
        case 'memory-limit':
            return __('Dear Hosting Provider,<br><br>My website requires at least 256M of PHP memory limit to operate efficiently. I kindly ask for your assistance in increasing the PHP memory limit on my server to meet this requirement.<br><br>Thank you for your help.', 'ai-content-wizard');
        case 'max-execution-time':
            return __('Dear Hosting Provider,<br><br>I am encountering issues with timeouts on my website. To resolve this, I need the PHP maximum execution time to be at least 300 seconds. Could you please increase this limit on my server?<br><br>Your assistance is greatly appreciated.', 'ai-content-wizard');
        case 'seo-plugin':
            return __('Dear Plugin Developer,<br><br>I am using the AI Content Wizard plugin on my WordPress website and noticed it recommends having an SEO plugin like Yoast, Rank Math, or All in One SEO for optimal features. Can you please provide guidance or assistance in selecting and installing the right SEO plugin for my site?<br><br>Thank you for your support.', 'ai-content-wizard');
        case 'uploads-directory':
            return __('Dear Hosting Provider,<br><br>My website requires the ability to upload files and generate media, but currently, the uploads directory is not writable. Can you please assist in ensuring that the uploads directory on my server is writable?<br><br>Thank you for your help.', 'ai-content-wizard');
        case 'http-timeout':
            return __('Dear Hosting Provider,<br><br>I am experiencing issues with HTTP request timeouts on my website. To resolve this, I need the server to handle HTTP requests with a timeout of at least 15 seconds. Could you please assist in adjusting this setting?<br><br>Your help is much appreciated.', 'ai-content-wizard');
        case 'max-input-time':
            return __('Dear Hosting Provider,<br><br>I am encountering issues with long-running input operations that require a higher PHP max_input_time. Please increase max_input_time to at least 300 seconds on my server.<br><br>Thank you.', 'ai-content-wizard');
        case 'default-socket-timeout':
            return __('Dear Hosting Provider,<br><br>My website is experiencing socket timeouts during HTTP requests. To resolve this, please increase default_socket_timeout to at least 15 seconds.<br><br>Thank you for your assistance.', 'ai-content-wizard');
        case 'litespeed-request-timeout':
            return __('Dear Hosting Provider,<br><br>I have noticed that LiteSpeed is terminating requests after 240 seconds by default. Please increase the LSAPI Request Timeout to at least 500 seconds to ensure long-running operations complete successfully.<br><br>Thank you for your assistance.', 'ai-content-wizard');
        case 'apache-timeout':
            return __('Dear Hosting Provider,<br><br>Please set Apache Timeout to at least 500 seconds to support long-running requests. This can be configured in the Apache httpd.conf or appropriate includes.<br><br>Thank you.', 'ai-content-wizard');
        case 'apache-reqtimeout':
            return __('Dear Hosting Provider,<br><br>Please adjust Apache mod_reqtimeout (RequestReadTimeout) to avoid premature terminations. Recommended: header=0 body=0 (disabled) or values equivalent to ≥ 500 seconds.<br><br>Thank you.', 'ai-content-wizard');
        case 'nginx-fastcgi-read-timeout':
            return __('Dear Hosting Provider,<br><br>Please set Nginx fastcgi_read_timeout to 500–600 seconds to allow long-running PHP responses.<br><br>Thank you.', 'ai-content-wizard');
        case 'nginx-proxy-read-timeout':
            return __('Dear Hosting Provider,<br><br>If a reverse proxy is used, please set Nginx proxy_read_timeout to 500–600 seconds to prevent upstream timeouts.<br><br>Thank you.', 'ai-content-wizard');
        case 'php-fpm-request-terminate-timeout':
            return __('Dear Hosting Provider,<br><br>Please set PHP-FPM request_terminate_timeout to 0 (no limit) or at least 500 seconds in the pool configuration file to avoid killing long-running PHP scripts.<br><br>Thank you.', 'ai-content-wizard');
        default:
            error_log('Returning default message for unknown ID: ' . $helpId); // Для отладки
            return __('No specific help message available for this issue.', 'ai-content-wizard');
    }
}


function ai_content_wizard_system_check() {
    $results = [];

    // Проверка версии PHP
    $results[] = [
        'PHP Version >= 7.1', 
        phpversion(), 
        '7.1', 
        version_compare(phpversion(), '7.1', '>=') ? 'OK' : 'Fail', 
        'Ensure your server is running PHP version 7.1 or higher for optimal performance and security.',
        'php-version'
    ];

    // Проверка памяти
    $memory_limit = ini_get('memory_limit');
    $required_memory = '256M';
    $results[] = [
        'Memory Limit >= 256M', 
        $memory_limit, 
        $required_memory, 
        ai_content_wizard_compare_memory($memory_limit, $required_memory) ? 'OK' : 'Fail', 
        'Increase the PHP memory limit to at least 256M to handle intensive operations.',
        'memory-limit'
    ];

    // Проверка таймаута
    $max_execution_time = ini_get('max_execution_time');
    $execution_status = $max_execution_time < 100 ? 'Fail' : ($max_execution_time < 300 ? 'warning' : 'OK');
    $execution_color = $execution_status === 'OK' ? 'green' : ($execution_status === 'warning' ? 'orange' : 'red');
    $results[] = [
        'Max Execution Time', 
        $max_execution_time . ' seconds', 
        '>= 300 seconds', 
        $execution_status, 
        'Set the PHP maximum execution time to at least 300 seconds to prevent timeouts during resource-intensive tasks.',
        'max-execution-time'
    ];

    // Проверка времени ожидания ввода (max_input_time)
    $max_input_time = ini_get('max_input_time');
    $input_status = ($max_input_time >= 300) ? 'OK' : 'warning';
    $results[] = [
        'Max Input Time', 
        $max_input_time . ' seconds', 
        '>= 300 seconds', 
        $input_status, 
        'Set the PHP max_input_time to at least 300 seconds to allow long-running input operations.',
        'max-input-time'
    ];

    // Проверка таймаута сокета (default_socket_timeout)
    $socket_timeout = ini_get('default_socket_timeout');
    $socket_status = ($socket_timeout >= 15) ? 'OK' : 'warning';
    $results[] = [
        'Default Socket Timeout', 
        $socket_timeout . ' seconds', 
        '>= 15 seconds', 
        $socket_status, 
        'Increase default_socket_timeout to at least 15 seconds to avoid premature socket closures.',
        'default-socket-timeout'
    ];

    // Web server & SAPI (informational row)
    $server_software = $_SERVER['SERVER_SOFTWARE'] ?? 'unknown';
    $sapi = php_sapi_name();
    $results[] = [
        'Web Server / PHP SAPI',
        $server_software . ' / ' . $sapi,
        '—',
        'OK',
        'Detected runtime environment (informational).',
        'web-server-info'
    ];

    // Effective Request Timeout from last probe (if any)
    $probe_summary = get_option('acw_timeout_probe_last');
    if (is_array($probe_summary) && !empty($probe_summary['effective'])) {
        $eff = intval($probe_summary['effective']);
        $req = '>= 500 seconds';
        $status = ($eff >= 500) ? 'OK' : (($eff >= 300) ? 'warning' : 'Fail');
        $results[] = [
            'Effective Request Timeout (probe)',
            $eff . ' seconds',
            $req,
            $status,
            'Detected limiter: ' . ($probe_summary['suspected'] ?? 'Unknown') . '. Consider raising limits to meet recommended value.',
            'effective-probe-timeout'
        ];
    }

    // LiteSpeed timeout check
    if (stripos($server_software, 'litespeed') !== false) {
        // LiteSpeed по умолчанию обрывает запросы через 240 секунд
        $lts_ini = ini_get('litespeed.req_timeout');
        $lts_current = ($lts_ini && $lts_ini > 0) ? $lts_ini . ' seconds' : 'Unknown';
        $lts_required = '500–600 seconds';
        $lts_status = ($lts_ini && $lts_ini >= 500) ? 'OK' : 'Fail';
        $lts_recommendation = 'Set LiteSpeed LSAPI Request Timeout to 500–600 seconds in the server configuration (external app settings).';
        $results[] = [
            'LiteSpeed Request Timeout',
            $lts_current,
            $lts_required,
            $lts_status,
            $lts_recommendation,
            'litespeed-request-timeout'
        ];
    }

    // Apache checks
    if (stripos($server_software, 'apache') !== false) {
        $results[] = [
            'Apache Timeout',
            'Unknown',
            '>= 500 seconds',
            'warning',
            'Set Apache Timeout to ≥ 500 seconds for long-running requests (httpd.conf). Default may be 300s.',
            'apache-timeout'
        ];
        $results[] = [
            'Apache mod_reqtimeout (RequestReadTimeout)',
            'Unknown',
            'header=0 body=0 (disabled) or ≥ 500 seconds',
            'warning',
            'Adjust RequestReadTimeout to avoid premature termination during large uploads/long responses.',
            'apache-reqtimeout'
        ];
    }

    // Nginx checks
    if (stripos($server_software, 'nginx') !== false || stripos($sapi, 'fpm') !== false) {
        $results[] = [
            'Nginx fastcgi_read_timeout',
            'Unknown',
            '>= 500 seconds',
            'warning',
            'Set fastcgi_read_timeout to 500–600s in nginx.conf / site config to allow long PHP responses.',
            'nginx-fastcgi-read-timeout'
        ];
        $results[] = [
            'Nginx proxy_read_timeout',
            'Unknown',
            '>= 500 seconds',
            'warning',
            'If using a reverse proxy, set proxy_read_timeout to 500–600s to prevent upstream timeouts.',
            'nginx-proxy-read-timeout'
        ];
    }

    // PHP-FPM check
    if (stripos($sapi, 'fpm') !== false) {
        $results[] = [
            'PHP-FPM request_terminate_timeout',
            'Unknown',
            '0 (disabled) or ≥ 500 seconds',
            'warning',
            'Set request_terminate_timeout = 0 (no limit) or ≥ 500s in pool.d/*.conf.',
            'php-fpm-request-terminate-timeout'
        ];
    }

    // Проверка наличия SEO плагинов
    $seo_plugin_status = ai_content_wizard_is_seo_plugin_active() ? 'OK' : 'warning';
    $results[] = [
        'SEO Plugin Installed', 
        ai_content_wizard_get_seo_plugins_list(), 
        'Yoast, Rank Math, or All in One SEO', 
        $seo_plugin_status, 
        'Having an SEO plugin like Yoast, Rank Math, or All in One SEO is recommended for optimal SEO features.',
        'seo-plugin'
    ];

    // Проверка возможности записи в директорию
    $upload_dir = wp_upload_dir();
    $upload_dir_writable = is_writable($upload_dir['basedir']);
    $results[] = [
        'Writable Uploads Directory', 
        $upload_dir_writable ? 'Writable' : 'Not Writable', 
        'Writable', 
        $upload_dir_writable ? 'OK' : 'Fail', 
        'Ensure the uploads directory is writable to allow file uploads and media generation.',
        'uploads-directory'
    ];
    
    // Проверка таймаута HTTP-запросов
    $http_timeout_ok = ai_content_wizard_check_http_timeout();
    $results[] = [
        'HTTP Request Timeout', 
        $http_timeout_ok ? 'OK' : 'Fail', 
        'OK', 
        $http_timeout_ok ? 'OK' : 'Fail', 
        'Ensure the server can handle HTTP requests with a timeout of at least 15 seconds.',
        'http-timeout'
    ];
    
    return $results;
}


function ai_content_wizard_is_seo_plugin_active() {
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');
    return is_plugin_active('wordpress-seo/wp-seo.php') || is_plugin_active('seo-by-rank-math/rank-math.php') || is_plugin_active('all-in-one-seo-pack/all_in_one_seo_pack.php');
}

function ai_content_wizard_get_seo_plugins_list() {
    $plugins = [];
    if (is_plugin_active('wordpress-seo/wp-seo.php')) {
        $plugins[] = 'Yoast SEO';
    }
    if (is_plugin_active('seo-by-rank-math/rank-math.php')) {
        $plugins[] = 'Rank Math SEO';
    }
    if (is_plugin_active('all-in-one-seo-pack/all_in_one_seo_pack.php')) {
        $plugins[] = 'All in One SEO Pack';
    }
    return implode(', ', $plugins) ?: 'None';
}

function ai_content_wizard_compare_memory($current_limit, $required_limit) {
    $current_bytes = ai_content_wizard_convert_to_bytes($current_limit);
    $required_bytes = ai_content_wizard_convert_to_bytes($required_limit);
    return $current_bytes >= $required_bytes;
}

function ai_content_wizard_convert_to_bytes($value) {
    $value = trim($value);
    $last = strtolower($value[strlen($value) - 1]);
    $value = (int) $value;
    switch($last) {
        case 'g':
            $value *= 1024;
        case 'm':
            $value *= 1024;
        case 'k':
            $value *= 1024;
    }
    return $value;
}


function ai_content_wizard_check_http_timeout() {
    // Устанавливаем рекомендуемый таймаут
    $recommended_timeout = 15; // секунды

    // Делаем тестовый запрос для проверки таймаута
    $response = wp_remote_post('https://example.com', ['timeout' => $recommended_timeout]);

    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        // Проверяем, не связана ли ошибка с таймаутом
        return strpos($error_message, 'timed out') === false;
    }

    return true;
}

add_action('admin_post_acw_export_diagnostics', 'ai_content_wizard_export_diagnostics');
function ai_content_wizard_export_diagnostics() {
    if (!current_user_can('manage_options') || !check_admin_referer('acw_export_diag')) {
        wp_die(__('Not allowed', 'ai-content-wizard'));
    }
    $diag = ai_content_wizard_collect_diagnostics();
    nocache_headers();
    header('Content-Type: application/json; charset=utf-8');
    header('Content-Disposition: attachment; filename="acw-diagnostics-' . date('Ymd-His') . '.json"');
    echo wp_json_encode($diag, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

add_action('admin_post_acw_phpinfo', 'ai_content_wizard_phpinfo');
function ai_content_wizard_phpinfo() {
    if (!current_user_can('manage_options') || !check_admin_referer('acw_phpinfo')) {
        wp_die(__('Not allowed', 'ai-content-wizard'));
    }
    echo '<!DOCTYPE html><html><head><meta charset="utf-8"><title>PHP Info</title></head><body style="background:#fff">';
    ob_start();
    phpinfo();
    $phpinfo = ob_get_clean();
    echo $phpinfo;
    echo '</body></html>';
    exit;
}