<?php
/**
 * Vulnerabilities tab — settings + cached findings + run-now action.
 *
 * @package Brainwerk Security Suite
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if ( ! empty( $_POST['shieldforge_vulnscan_action'] ) && check_admin_referer( 'shieldforge_vulnscan' ) && current_user_can( Shieldforge_Admin::CAP ) ) {
    $a = sanitize_key( wp_unslash( $_POST['shieldforge_vulnscan_action'] ) );
    if ( 'scan_now' === $a ) {
        $r = Shieldforge_VulnScanner::scan_all();
        add_settings_error( 'brainwerk-security-suite', 'sf_vulnscan_done', sprintf(
            /* translators: 1: queries, 2: errors, 3: plugins-affected, 4: themes-affected, 5: core-affected */
            esc_html__( 'Vulnerability scan complete: %1$d queries, %2$d errors, %3$d plugins / %4$d themes / %5$d core hits.', 'brainwerk-security-suite' ),
            (int) ( $r['queries'] ?? 0 ),
            (int) ( $r['errors'] ?? 0 ),
            (int) ( count( $r['plugins'] ?? array() ) ),
            (int) ( count( $r['themes'] ?? array() ) ),
            (int) ( count( $r['core'] ?? array() ) )
        ), 'updated' );
    } elseif ( 'reset_cache' === $a ) {
        Shieldforge_VulnScanner::reset_cache();
        add_settings_error( 'brainwerk-security-suite', 'sf_vulnscan_reset', esc_html__( 'Vulnerability cache cleared.', 'brainwerk-security-suite' ), 'updated' );
    }
}

$status   = Shieldforge_VulnScanner::status();
$cached   = Shieldforge_VulnScanner::get_cached_results();
$enabled  = (bool) Shieldforge_Settings::get( 'vulnscan_enabled', false );
$themes   = (bool) Shieldforge_Settings::get( 'vulnscan_check_themes', true );
$core_chk = (bool) Shieldforge_Settings::get( 'vulnscan_check_core', true );
$endpoint = (string) Shieldforge_Settings::get( 'vulnscan_endpoint', '' );

$last_run_human = $status['last_run']
    ? human_time_diff( $status['last_run'], time() ) . ' ' . esc_html__( 'ago', 'brainwerk-security-suite' )
    : esc_html__( 'never', 'brainwerk-security-suite' );
$next_run_human = $status['next_run']
    ? human_time_diff( time(), $status['next_run'] )
    : esc_html__( 'not scheduled', 'brainwerk-security-suite' );
?>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Plugin / Theme / Core vulnerabilities', 'brainwerk-security-suite' ); ?></h2>
    <p class="muted">
        <?php esc_html_e( 'Daily check against an EU-hosted vulnerability API (default: shieldforge-intel.brainwerk.at — no API key, self-hostable). Each scan sends only the slug + version of installed components. No site URL, no admin email, no IPs.', 'brainwerk-security-suite' ); ?>
    </p>

    <?php if ( ! $enabled ) : ?>
        <div class="notice notice-info inline" style="margin:0 0 12px">
            <p>
                <strong><?php esc_html_e( 'The vulnerability scanner is off by default.', 'brainwerk-security-suite' ); ?></strong>
                <?php esc_html_e( 'It is the only feature that automatically contacts an external service. Enable it below to consent to the daily lookup (slug + version only). You can also run a one-off check with “Scan now” without turning on the daily schedule.', 'brainwerk-security-suite' ); ?>
            </p>
        </div>
    <?php endif; ?>

    <table class="widefat striped" style="max-width:680px">
        <tbody>
            <tr><th scope="row" style="width:40%"><?php esc_html_e( 'Last scan', 'brainwerk-security-suite' ); ?></th><td><?php echo esc_html( $last_run_human ); ?></td></tr>
            <tr><th scope="row"><?php esc_html_e( 'Queries last run', 'brainwerk-security-suite' ); ?></th><td><?php echo (int) $status['queries']; ?> <span class="muted">(<?php echo (int) $status['errors']; ?> errors)</span></td></tr>
            <tr><th scope="row"><?php esc_html_e( 'Findings (cached)', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <?php
                    printf(
                        /* translators: 1: plugins-affected, 2: themes-affected, 3: core-affected */
                        esc_html__( '%1$d plugins, %2$d themes, %3$d core', 'brainwerk-security-suite' ),
                        (int) $status['plugins'],
                        (int) $status['themes'],
                        (int) $status['core']
                    );
                    ?>
                </td>
            </tr>
            <tr><th scope="row"><?php esc_html_e( 'Next scheduled run', 'brainwerk-security-suite' ); ?></th><td><?php echo esc_html( $next_run_human ); ?></td></tr>
        </tbody>
    </table>

    <form method="post" action="" style="margin-top:14px; display:flex; gap:8px; flex-wrap:wrap">
        <?php wp_nonce_field( 'shieldforge_vulnscan' ); ?>
        <button type="submit" name="shieldforge_vulnscan_action" value="scan_now" class="button button-primary"><?php esc_html_e( 'Scan now', 'brainwerk-security-suite' ); ?></button>
        <button type="submit" name="shieldforge_vulnscan_action" value="reset_cache" class="button" onclick="return confirm('<?php echo esc_js( __( 'Clear cached vulnerability data and dedup state?', 'brainwerk-security-suite' ) ); ?>');"><?php esc_html_e( 'Clear cache', 'brainwerk-security-suite' ); ?></button>
    </form>
    <p class="description" style="margin-top:6px">
        <?php esc_html_e( 'Manual scans hit the API in real time and may take ~10–60s depending on how many plugins are installed.', 'brainwerk-security-suite' ); ?>
    </p>
</div>

<?php
$render_bucket = function( $title, $rows ) {
    if ( empty( $rows ) ) {
        return;
    }
    ?>
    <div class="shieldforge-card">
        <h2><?php echo esc_html( $title ); ?> <span class="sf-badge"><?php echo (int) count( $rows ); ?></span></h2>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th><?php esc_html_e( 'Component', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Version', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Active', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Vulnerability', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Fixed in', 'brainwerk-security-suite' ); ?></th>
                    <th><?php esc_html_e( 'Sources', 'brainwerk-security-suite' ); ?></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ( $rows as $entry ) :
                $vulns = (array) ( $entry['vulns'] ?? array() );
                $rowspan = max( 1, count( $vulns ) );
            ?>
                <?php $first = true; foreach ( $vulns as $v ) : ?>
                    <tr>
                        <?php if ( $first ) : ?>
                            <td rowspan="<?php echo (int) $rowspan; ?>">
                                <strong><?php echo esc_html( $entry['name'] ); ?></strong>
                                <br><code style="font-size:11px"><?php echo esc_html( $entry['slug'] ); ?></code>
                            </td>
                            <td rowspan="<?php echo (int) $rowspan; ?>"><code><?php echo esc_html( $entry['version'] ); ?></code></td>
                            <td rowspan="<?php echo (int) $rowspan; ?>">
                                <?php if ( ! empty( $entry['active'] ) ) : ?>
                                    <span style="color:#b32d2e; font-weight:600">&#x25CF; <?php esc_html_e( 'active', 'brainwerk-security-suite' ); ?></span>
                                <?php else : ?>
                                    <span class="muted">&#x25CB; <?php esc_html_e( 'inactive', 'brainwerk-security-suite' ); ?></span>
                                <?php endif; ?>
                            </td>
                        <?php endif; ?>
                        <td>
                            <?php echo esc_html( $v['name'] ); ?>
                            <?php if ( ! empty( $v['cvss'] ) ) : ?>
                                <span class="sf-badge" title="CVSS"><?php echo esc_html( $v['cvss'] ); ?></span>
                            <?php endif; ?>
                            <?php if ( ! empty( $v['unfixed'] ) ) : ?>
                                <br><span style="color:#b32d2e; font-size:11px"><?php esc_html_e( 'No patch available', 'brainwerk-security-suite' ); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ( ! empty( $v['fixed_in'] ) ) : ?>
                                <code><?php echo esc_html( $v['fixed_in'] ); ?></code>
                            <?php else : ?>
                                <span class="muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            $source_links = array();
                            foreach ( (array) ( $v['sources'] ?? array() ) as $s ) {
                                if ( ! empty( $s['link'] ) && ! empty( $s['id'] ) ) {
                                    $source_links[] = '<a href="' . esc_url( $s['link'] ) . '" target="_blank" rel="noopener">' . esc_html( $s['id'] ) . '</a>';
                                } elseif ( ! empty( $s['id'] ) ) {
                                    $source_links[] = esc_html( $s['id'] );
                                }
                            }
                            echo wp_kses(
                                implode( ' · ', $source_links ),
                                array( 'a' => array( 'href' => true, 'target' => true, 'rel' => true ) )
                            );
                            ?>
                        </td>
                    </tr>
                <?php $first = false; endforeach; ?>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
};

if ( null === $cached ) {
    ?>
    <div class="sf-empty-state">
        <div class="sf-empty-icon dashicons dashicons-shield"></div>
        <h3><?php esc_html_e( 'No vulnerability scan has run yet.', 'brainwerk-security-suite' ); ?></h3>
        <p><?php esc_html_e( 'The scanner queries a public CVE database for every plugin/theme/core component on your site. The next scheduled run is at 04:30, but you can run it on demand.', 'brainwerk-security-suite' ); ?></p>
        <form method="post" action="" style="display:inline">
            <?php wp_nonce_field( 'shieldforge_vulnscan' ); ?>
            <button type="submit" name="shieldforge_vulnscan_action" value="scan_now" class="button button-primary"><?php esc_html_e( 'Scan now', 'brainwerk-security-suite' ); ?></button>
        </form>
    </div>
    <?php
} else {
    $render_bucket( __( 'Vulnerable plugins', 'brainwerk-security-suite' ),  $cached['plugins'] );
    $render_bucket( __( 'Vulnerable themes', 'brainwerk-security-suite' ),   $cached['themes'] );
    $render_bucket( __( 'Vulnerable WordPress core', 'brainwerk-security-suite' ), $cached['core'] );

    if ( empty( $cached['plugins'] ) && empty( $cached['themes'] ) && empty( $cached['core'] ) ) {
        echo '<div class="shieldforge-card"><p style="color:#2d6a2d"><strong>' . esc_html__( 'No known vulnerabilities found in the installed components. ✓', 'brainwerk-security-suite' ) . '</strong></p></div>';
    }
}
?>

<div class="shieldforge-card">
    <h2><?php esc_html_e( 'Settings', 'brainwerk-security-suite' ); ?></h2>
    <form method="post" action="">
        <?php wp_nonce_field( Shieldforge_Admin::NONCE ); ?>
        <input type="hidden" name="shieldforge_action" value="save_settings">
        <input type="hidden" name="shieldforge_tab_keys[]" value="vulnscan_enabled">
        <input type="hidden" name="shieldforge_tab_keys[]" value="vulnscan_check_themes">
        <input type="hidden" name="shieldforge_tab_keys[]" value="vulnscan_check_core">

        <table class="form-table" role="presentation">
            <tr>
                <th scope="row"><?php esc_html_e( 'Enable scanner', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[vulnscan_enabled]" value="1" <?php checked( $enabled ); ?>>
                        <?php esc_html_e( 'Run the daily vulnerability check.', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Check themes', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[vulnscan_check_themes]" value="1" <?php checked( $themes ); ?>>
                        <?php esc_html_e( 'Also query the API for installed themes.', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'Check WordPress core', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <label class="sf-toggle">
                        <input type="checkbox" name="shieldforge[vulnscan_check_core]" value="1" <?php checked( $core_chk ); ?>>
                        <?php esc_html_e( 'Also check the running WordPress core version.', 'brainwerk-security-suite' ); ?>
                    </label>
                </td>
            </tr>
            <tr>
                <th scope="row"><?php esc_html_e( 'API endpoint', 'brainwerk-security-suite' ); ?></th>
                <td>
                    <input type="url" name="shieldforge[vulnscan_endpoint]" value="<?php echo esc_attr( $endpoint ); ?>" class="regular-text" placeholder="<?php echo esc_attr( Shieldforge_VulnScanner::ENDPOINT_BASE ); ?>">
                    <p class="description"><?php esc_html_e( 'Override only if you mirror the API privately. Empty uses wpvulnerability.net.', 'brainwerk-security-suite' ); ?></p>
                </td>
            </tr>
        </table>

        <p>
            <button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'brainwerk-security-suite' ); ?></button>
        </p>
    </form>
</div>
