/**
 * Master Health Scanner — Fix Guidance Library
 * One entry per issue `type`. Each has:
 *   title      — short heading shown in the modal
 *   severity   — human label
 *   what       — plain-English explanation of the problem
 *   impact     — what goes wrong if left unfixed
 *   steps      — array of numbered fix steps (HTML allowed)
 *   links      — [{label, url}] reference links
 *   code       — optional before/after code snippet string
 */
window.PHS_FIX = {

    /* ── Runtime errors ─────────────────────────────────────── */
    runtime_error: {
        title: 'PHP Runtime Error',
        severity: 'Detected at runtime',
        what: 'This plugin triggered a PHP error, warning, or notice during a real page request. The error was captured by the Master Health Scanner\'s live interceptor while you browsed your site.',
        impact: 'PHP errors slow page loads, pollute your error log, break functionality, and in the case of Fatal errors can crash entire pages or the WordPress admin.',
        steps: [
            'Note the <strong>file path and line number</strong> shown in the error — open that file in a code editor.',
            'Read the full error message carefully — PHP errors usually describe exactly what is wrong (undefined variable, wrong argument type, etc.).',
            'If it is a <strong>PHP Fatal / Parse error</strong>: the plugin is likely incompatible with your PHP version. Check the plugin\'s page on WordPress.org for minimum PHP requirements.',
            'If it is a <strong>PHP Warning or Notice</strong> from a third-party plugin: update the plugin first (<em>Plugins → Updates</em>). The warning may already be fixed in a newer release.',
            'If updating does not help, check the plugin\'s support forum on WordPress.org and search for the error message.',
            'As a last resort, deactivate the plugin and find an alternative — a plugin throwing repeated Fatal errors should not stay active.',
        ],
        links: [
            { label: 'Understanding PHP Errors', url: 'https://www.php.net/manual/en/function.set-error-handler.php' },
            { label: 'WordPress Debug Logging', url: 'https://wordpress.org/documentation/article/debugging-in-wordpress/' },
        ],
    },

    /* ── Static analysis ────────────────────────────────────── */
    static_analysis: {
        title: 'Code Quality / Security Issue',
        severity: 'Detected by static analysis',
        what: 'The Master Health Scanner read the plugin\'s PHP source files and found a pattern that is dangerous, deprecated, or against WordPress coding standards.',
        impact: 'Static issues range from potential security vulnerabilities (XSS, SQL injection) to compatibility problems and future breakage.',
        steps: [
            'Identify the <strong>specific file</strong> shown in brackets in the issue message.',
            'Open the file and search for the flagged function or pattern.',
            'Apply the fix described in the individual issue — see the specific sub-entries below for exact replacement code.',
            'If this is a third-party plugin, <strong>update it</strong> — the developer may have already fixed it.',
            'If the plugin has not been updated in over a year and the vulnerability is serious, consider switching to an actively maintained alternative.',
        ],
        links: [
            { label: 'WordPress Plugin Security', url: 'https://developer.wordpress.org/plugins/security/' },
            { label: 'WordPress Coding Standards', url: 'https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/' },
        ],
    },

    eval_usage: {
        title: 'Dangerous: eval() Usage',
        severity: 'High risk',
        what: '<code>eval()</code> executes a string as PHP code. It is one of the most dangerous functions in PHP — if any user input reaches it, an attacker can run arbitrary code on your server.',
        impact: 'Complete server compromise, data theft, malware injection.',
        steps: [
            'Open the flagged file and find every <code>eval()</code> call.',
            'If the plugin is third-party, <strong>contact the developer</strong> or replace the plugin immediately.',
            'For your own code: refactor to use proper PHP — there is almost always a safer way to achieve the same result without <code>eval()</code>.',
        ],
        code: '// ❌ Dangerous\neval(\'$result = \' . $user_input . \';\');\n\n// ✅ Safe alternative: use a proper function or class',
        links: [{ label: 'OWASP Code Injection', url: 'https://owasp.org/www-community/attacks/Code_Injection' }],
    },

    xss_echo: {
        title: 'XSS: Unsanitised Superglobal Echo',
        severity: 'Critical — XSS vulnerability',
        what: 'The plugin directly echoes <code>$_GET</code>, <code>$_POST</code>, or another superglobal without sanitisation. Any value a visitor puts in the URL or form can be reflected back as HTML.',
        impact: 'Cross-site scripting (XSS) — attackers can inject JavaScript, steal session cookies, redirect users, or deface your site.',
        steps: [
            'Find every <code>echo $_GET[…]</code> / <code>echo $_POST[…]</code> in the file.',
            'Wrap it in the correct WordPress escape function before output.',
            'Choose the right function for the context:',
            '&nbsp;&nbsp;• In HTML: <code>echo esc_html($_GET[\'name\']);</code>',
            '&nbsp;&nbsp;• In HTML attributes: <code>echo esc_attr($_GET[\'name\']);</code>',
            '&nbsp;&nbsp;• In URLs: <code>echo esc_url($_GET[\'url\']);</code>',
            '&nbsp;&nbsp;• In JS: <code>echo esc_js($_GET[\'val\']);</code>',
        ],
        code: '// ❌ Dangerous\necho $_GET[\'search\'];\n\n// ✅ Safe\necho esc_html( $_GET[\'search\'] );',
        links: [{ label: 'WP Data Validation', url: 'https://developer.wordpress.org/apis/security/escaping/' }],
    },

    sql_injection: {
        title: 'SQL Injection Risk',
        severity: 'Critical — SQL injection',
        what: 'A variable is passed directly into a <code>$wpdb</code> database query without using <code>$wpdb->prepare()</code>. An attacker who controls that variable can manipulate your database queries.',
        impact: 'Data theft, data deletion, privilege escalation, full site compromise.',
        steps: [
            'Find the flagged <code>$wpdb->query()</code> / <code>get_results()</code> etc. call.',
            'Wrap any dynamic values using <code>$wpdb->prepare()</code> with placeholders.',
            'Use <code>%s</code> for strings, <code>%d</code> for integers, <code>%f</code> for floats.',
        ],
        code: '// ❌ Dangerous\n$wpdb->get_results("SELECT * FROM $wpdb->posts WHERE ID = $post_id");\n\n// ✅ Safe\n$wpdb->get_results(\n    $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id)\n);',
        links: [{ label: 'wpdb::prepare()', url: 'https://developer.wordpress.org/reference/classes/wpdb/prepare/' }],
    },

    shell_exec: {
        title: 'Shell Execution Function',
        severity: 'High risk',
        what: 'Functions like <code>exec()</code>, <code>shell_exec()</code>, <code>system()</code>, <code>passthru()</code> run operating system commands directly from PHP.',
        impact: 'If any user input reaches these functions, an attacker can execute any command on your server.',
        steps: [
            'Find the flagged shell function call in the plugin file.',
            'If the plugin is third-party, report it to the developer and consider switching plugins.',
            'If it is your own code, check whether user input ever reaches the argument — if so, sanitise with <code>escapeshellarg()</code> and <code>escapeshellcmd()</code>.',
            'Better yet, find a PHP-native alternative that does not call the shell at all.',
        ],
        code: '// ❌ Risky\n$output = shell_exec("convert " . $_POST[\'file\'] . " output.jpg");\n\n// ✅ Safer (if shell is truly necessary)\n$file = escapeshellarg($_POST[\'file\']);\n$output = shell_exec("convert $file output.jpg");',
        links: [],
    },

    base64_decode: {
        title: 'Suspicious base64_decode Usage',
        severity: 'Medium risk',
        what: '<code>base64_decode()</code> applied to a variable is a common technique used by malware to hide malicious code from simple string searches.',
        impact: 'May indicate obfuscated malicious code. At minimum it makes the plugin difficult to audit.',
        steps: [
            'Open the flagged file and find the <code>base64_decode($variable)</code> call.',
            'Trace where <code>$variable</code> comes from.',
            'If the decoded value is then passed to <code>eval()</code> or <code>create_function()</code>, the plugin is almost certainly malicious — deactivate and delete it immediately.',
            'If you are the developer: store the value in plain text or use a proper encryption library instead.',
        ],
        links: [{ label: 'WordPress Malware Signatures', url: 'https://wordpress.org/documentation/article/faq-my-site-was-hacked/' }],
    },

    /* ── Health / metadata issues ───────────────────────────── */
    update: {
        title: 'Plugin Update Available',
        severity: 'Warning',
        what: 'A newer version of this plugin is available in the WordPress plugin repository. You are running an outdated version.',
        impact: 'Outdated plugins are the #1 cause of WordPress hacks. Updates often include security patches, bug fixes, and compatibility improvements.',
        steps: [
            'Go to <strong>Dashboard → Updates</strong> or <strong>Plugins → Installed Plugins</strong>.',
            'Click <strong>Update Now</strong> next to this plugin.',
            'If you have a staging environment, test the update there first.',
            'After updating, visit your site\'s key pages to confirm nothing broke.',
            'Consider enabling <strong>automatic updates</strong> for trusted plugins: go to Plugins, click "Enable auto-updates" next to the plugin.',
        ],
        links: [{ label: 'WordPress Updates', url: 'https://wordpress.org/documentation/article/updating-wordpress/' }],
    },

    php_compat: {
        title: 'PHP Version Incompatibility',
        severity: 'Critical',
        what: 'This plugin requires a minimum PHP version that is higher than the PHP version currently running on your server.',
        impact: 'The plugin will fail or throw Fatal errors on your server. Features may be completely broken.',
        steps: [
            'Check what PHP version your server runs: go to <strong>Tools → Site Health → Info → Server</strong>.',
            'Check what PHP version the plugin requires (shown in the issue detail).',
            '<strong>Option A — Upgrade PHP</strong>: contact your host and ask them to upgrade your PHP version. PHP 8.1+ is recommended for all new WordPress sites.',
            '<strong>Option B — Use an older plugin version</strong>: download a previous release from the plugin\'s Advanced View on WordPress.org that supports your current PHP.',
            '<strong>Option C — Deactivate</strong>: if you cannot upgrade PHP or find a compatible version, deactivate the plugin to prevent errors.',
        ],
        links: [
            { label: 'WordPress PHP Requirements', url: 'https://wordpress.org/about/requirements/' },
            { label: 'Upgrading PHP', url: 'https://wordpress.org/documentation/article/how-to-install-php/' },
        ],
    },

    wp_compat: {
        title: 'WordPress Version Incompatibility',
        severity: 'Critical',
        what: 'This plugin requires a minimum WordPress version that is higher than the WordPress version currently installed.',
        impact: 'The plugin may malfunction, show errors, or fail to activate.',
        steps: [
            'Go to <strong>Dashboard → Updates</strong> and update WordPress to the latest version.',
            'Back up your site before updating WordPress.',
            'If you cannot update WordPress, use an older version of the plugin that supports your WP version.',
        ],
        links: [{ label: 'Updating WordPress', url: 'https://wordpress.org/documentation/article/updating-wordpress/' }],
    },

    missing_file: {
        title: 'Plugin File Missing',
        severity: 'Critical',
        what: 'WordPress knows about this plugin (it appears in the database) but its main PHP file does not exist on disk. The plugin folder or file was deleted without properly deactivating it first.',
        impact: 'WordPress may throw Fatal errors trying to load the plugin. The Plugins screen may show errors.',
        steps: [
            'Go to <strong>Plugins → Installed Plugins</strong> and deactivate this plugin if it shows as active.',
            'Delete the plugin entry via FTP/SFTP — remove any remaining folder under <code>wp-content/plugins/</code>.',
            'If you need the plugin: re-upload it via <strong>Plugins → Add New → Upload Plugin</strong>.',
            'Check your backups — you may have accidentally deleted it.',
        ],
        links: [],
    },

    permissions: {
        title: 'Loose File Permissions',
        severity: 'Warning',
        what: 'The plugin\'s main PHP file has permissions wider than the recommended <code>0644</code>. This means more users or processes on the server can read or write the file than necessary.',
        impact: 'On shared hosting, other users might be able to read or modify the plugin\'s files, potentially injecting malicious code.',
        steps: [
            'Connect to your server via FTP/SFTP or SSH.',
            'Navigate to <code>wp-content/plugins/[plugin-folder]/</code>.',
            'Set PHP files to <code>644</code> and directories to <code>755</code>.',
            'Via SSH: <code>find /path/to/plugin -type f -name "*.php" -exec chmod 644 {} \\;</code>',
            'Via SSH: <code>find /path/to/plugin -type d -exec chmod 755 {} \\;</code>',
        ],
        code: '# Fix permissions via SSH\ncd wp-content/plugins/your-plugin-folder\nfind . -type f -name "*.php" -exec chmod 644 {} \\;\nfind . -type d -exec chmod 755 {} \\;',
        links: [{ label: 'WordPress File Permissions', url: 'https://wordpress.org/documentation/article/changing-file-permissions/' }],
    },

    inactive: {
        title: 'Plugin Installed But Inactive',
        severity: 'Info',
        what: 'This plugin is installed on your server but not currently activated. Inactive plugins still take up disk space and can still be a security risk if they contain vulnerabilities.',
        impact: 'Inactive plugins with known security holes can still be exploited in some cases. They add clutter and can slow file system scans.',
        steps: [
            'If you no longer need this plugin: go to <strong>Plugins → Installed Plugins</strong>, make sure it is deactivated, then click <strong>Delete</strong>.',
            'If you need it temporarily inactive: that is fine, but keep it updated.',
            'If you are unsure what it does: check the plugin\'s description or WordPress.org page before deleting.',
        ],
        links: [],
    },

    no_version: {
        title: 'No Version Number Declared',
        severity: 'Error',
        what: 'The plugin\'s main file header does not include a <code>Version:</code> declaration. WordPress uses this to track updates and compatibility.',
        impact: 'WordPress cannot check for updates. Version history is impossible to track. Some themes and plugins that check for plugin versions may behave unexpectedly.',
        steps: [
            'Open the plugin\'s main PHP file.',
            'Find the file header comment block (the block at the top with <code>Plugin Name:</code>).',
            'Add a <code>Version:</code> line.',
        ],
        code: '<?php\n/**\n * Plugin Name: My Plugin\n * Version:     1.0.0    ← add this\n * ...\n */',
        links: [{ label: 'Plugin Headers', url: 'https://developer.wordpress.org/plugins/plugin-basics/header-requirements/' }],
    },

    no_author: {
        title: 'No Author Declared',
        severity: 'Info',
        what: 'The plugin header is missing an <code>Author:</code> field.',
        impact: 'Makes it harder to contact the developer for support or report security issues.',
        steps: [
            'Add <code>Author:</code> and optionally <code>Author URI:</code> to the plugin header.',
        ],
        code: '/**\n * Author:      Jane Developer\n * Author URI:  https://janedeveloper.com\n */',
        links: [],
    },

    no_textdomain: {
        title: 'No Text Domain Declared',
        severity: 'Info',
        what: 'The plugin header is missing a <code>Text Domain:</code> field. WordPress uses this to load translations.',
        impact: 'Translations (i18n / l10n) will not load correctly. The plugin cannot be properly translated.',
        steps: [
            'Add <code>Text Domain:</code> to the plugin header. It should match the plugin\'s folder slug.',
            'Also add <code>Domain Path: /languages</code> if you store translation files.',
        ],
        code: '/**\n * Text Domain: my-plugin-slug\n * Domain Path: /languages\n */',
        links: [{ label: 'Plugin Internationalisation', url: 'https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/' }],
    },

    no_readme: {
        title: 'No readme.txt Found',
        severity: 'Info',
        what: 'The plugin directory has no <code>readme.txt</code> or <code>README.md</code>. The readme is used by WordPress.org to display the plugin page and provides important metadata.',
        impact: 'Affects discoverability and documentation. Plugin validators and some tools may flag this.',
        steps: [
            'Create a <code>readme.txt</code> in the plugin root following the WordPress readme standard.',
            'Include at minimum: plugin name, description, installation instructions, changelog.',
        ],
        links: [{ label: 'WP readme.txt Standard', url: 'https://developer.wordpress.org/plugins/wordpress-org/how-your-readme-txt-works/' }],
    },

    deprecated_function: {
        title: 'Deprecated WordPress Function',
        severity: 'Warning',
        what: 'The plugin calls a WordPress function that has been deprecated and scheduled for removal in a future WordPress version.',
        impact: 'Will generate PHP Deprecated notices now. Will break completely when WordPress removes the function in a future major release.',
        steps: [
            'Find the deprecated function call in the flagged file.',
            'Replace it with the modern equivalent shown in the issue message.',
            'Test the plugin after making changes.',
            'If this is a third-party plugin, report it to the developer or check if an update is available.',
        ],
        links: [{ label: 'WP Deprecated Functions', url: 'https://developer.wordpress.org/reference/functions/' }],
    },

    short_tags: {
        title: 'PHP Short Tags Used',
        severity: 'Warning',
        what: 'The plugin uses <code><?</code> instead of <code><?php</code>. PHP short open tags are disabled by default on many servers.',
        impact: 'The plugin will display raw PHP code or Fatal Parse errors on servers with <code>short_open_tag = Off</code>.',
        steps: [
            'Search the plugin files for <code><?</code> (not followed by <code>php</code> or <code>=</code>).',
            'Replace every occurrence with <code><?php</code>.',
            'The short echo <code><?=</code> is safe since PHP 5.4 and does not need changing.',
        ],
        code: '// ❌ Unreliable\n<? echo $value; ?>\n\n// ✅ Always works\n<?php echo $value; ?>',
        links: [],
    },

    wp_debug_forced: {
        title: 'WP_DEBUG Forced On',
        severity: 'Warning',
        what: 'The plugin defines <code>WP_DEBUG</code> as <code>true</code> inside its own code. This is almost never intentional for a production plugin and overrides your site\'s own configuration.',
        impact: 'All PHP errors and notices will be displayed publicly to visitors, potentially leaking sensitive server paths and code.',
        steps: [
            'Find the <code>define(\'WP_DEBUG\', true)</code> line in the plugin.',
            'Remove it completely — debug settings belong in <code>wp-config.php</code>, not in plugins.',
            'If this is a third-party plugin, update it or report the issue to the developer.',
        ],
        code: '// ❌ Never do this in a plugin\ndefine(\'WP_DEBUG\', true);\n\n// ✅ WP_DEBUG belongs only in wp-config.php\n// define(\'WP_DEBUG\', true); // only in wp-config.php',
        links: [],
    },

    file_get_http: {
        title: 'file_get_contents() for HTTP Requests',
        severity: 'Info',
        what: 'The plugin uses PHP\'s <code>file_get_contents()</code> to make HTTP requests. WordPress provides its own HTTP API that is more reliable, respects proxy settings, and works on all hosting environments.',
        impact: '<code>file_get_contents()</code> for HTTP can fail when <code>allow_url_fopen</code> is disabled, does not respect WordPress proxy configuration, and provides no timeout or error handling.',
        steps: [
            'Replace <code>file_get_contents("http://...")</code> with <code>wp_remote_get()</code>.',
            'For POST requests, use <code>wp_remote_post()</code>.',
            'Check the response with <code>wp_remote_retrieve_body()</code>.',
        ],
        code: '// ❌ Unreliable\n$data = file_get_contents("https://api.example.com/data");\n\n// ✅ WordPress HTTP API\n$response = wp_remote_get("https://api.example.com/data");\nif ( is_wp_error($response) ) { /* handle error */ }\n$data = wp_remote_retrieve_body($response);',
        links: [{ label: 'WP HTTP API', url: 'https://developer.wordpress.org/plugins/http-api/' }],
    },

    curl_direct: {
        title: 'Direct cURL Usage',
        severity: 'Info',
        what: 'The plugin uses cURL directly instead of the WordPress HTTP API.',
        impact: 'Direct cURL bypasses WordPress proxy settings, SSL certificate handling, and error logging. Reduces portability across hosting environments.',
        steps: [
            'Replace <code>curl_init()</code> / <code>curl_exec()</code> with <code>wp_remote_get()</code> or <code>wp_remote_post()</code>.',
            'The WordPress HTTP API handles cURL, streams, and other transports automatically.',
        ],
        links: [{ label: 'WP HTTP API', url: 'https://developer.wordpress.org/plugins/http-api/' }],
    },

    get_currentuserinfo: {
        title: 'Deprecated: get_currentuserinfo()',
        severity: 'Warning',
        what: '<code>get_currentuserinfo()</code> was deprecated in WordPress 4.5.',
        impact: 'Generates PHP Deprecated notices. Will be removed in a future WordPress version.',
        steps: ['Replace with <code>wp_get_current_user()</code>.'],
        code: '// ❌ Deprecated\nget_currentuserinfo();\nglobal $current_user;\n\n// ✅ Modern\n$current_user = wp_get_current_user();\nif ( $current_user->exists() ) { /* logged in */ }',
        links: [{ label: 'wp_get_current_user()', url: 'https://developer.wordpress.org/reference/functions/wp_get_current_user/' }],
    },

    wpdb_escape: {
        title: 'Deprecated: $wpdb->escape()',
        severity: 'Warning',
        what: '<code>$wpdb->escape()</code> was deprecated in WordPress 3.6.',
        impact: 'Generates PHP Deprecated notices. SQL may not be properly sanitised.',
        steps: ['Use <code>$wpdb->prepare()</code> for full queries, or <code>esc_sql()</code> for individual values.'],
        code: '// ❌ Deprecated\n$value = $wpdb->escape($user_input);\n\n// ✅ Modern — use prepare()\n$results = $wpdb->get_results(\n    $wpdb->prepare("SELECT * FROM table WHERE col = %s", $user_input)\n);\n\n// ✅ Or for individual values\n$value = esc_sql($user_input);',
        links: [{ label: 'wpdb::prepare()', url: 'https://developer.wordpress.org/reference/classes/wpdb/prepare/' }],
    },

    /* ── Fallback for unknown types ──────────────────────────── */
    _default: {
        title: 'Plugin Issue Detected',
        severity: 'See details',
        what: 'An issue was detected with this plugin. Review the details in the issue message for more information.',
        impact: 'Varies depending on the specific issue type.',
        steps: [
            'Read the full issue message carefully.',
            'Update the plugin to its latest version.',
            'Check the plugin\'s support forum on WordPress.org.',
            'If the issue persists, consider deactivating the plugin and finding an alternative.',
        ],
        links: [{ label: 'WordPress Support Forums', url: 'https://wordpress.org/support/' }],
    },
};

/**
 * Look up fix guidance for an issue.
 * Tries to match on type, then falls back to _default.
 */
window.PHS_FIX.get = function(issue) {
    // Map static_analysis message patterns to specific entries
    if (issue.type === 'static_analysis') {
        const msg = issue.message || '';
        if (/eval\s*\(/.test(msg))                      return this.eval_usage;
        if (/echo.*superglobal|XSS/.test(msg))          return this.xss_echo;
        if (/SQL injection|wpdb.*query/.test(msg))      return this.sql_injection;
        if (/shell_exec|exec\(\)|system\(|passthru/.test(msg)) return this.shell_exec;
        if (/base64_decode/.test(msg))                  return this.base64_decode;
        if (/get_currentuserinfo/.test(msg))            return this.get_currentuserinfo;
        if (/wpdb.*escape/.test(msg))                   return this.wpdb_escape;
        if (/short tags/.test(msg))                     return this.short_tags;
        if (/WP_DEBUG/.test(msg))                       return this.wp_debug_forced;
        if (/file_get_contents.*HTTP|wp_remote_get/.test(msg)) return this.file_get_http;
        if (/cURL|curl_exec/.test(msg))                 return this.curl_direct;
        if (/Deprecated/.test(msg))                     return this.deprecated_function;
        return this.static_analysis;
    }
    return this[issue.type] || this._default;
};
