<?php
defined( 'ABSPATH' ) || exit;

/**
 * Plugin vulnerability checker.
 *
 * Free tier: flags plugins that are outdated or abandoned (no update in 2+ years)
 * using only the WordPress.org Plugins API — no external API key required.
 *
 * Full CVE scanning via Patchstack is reserved for the Security Essentials add-on.
 */
class SITECL_Plugin_CVE {

    public static function scan(): array {
        if ( ! function_exists( 'get_plugins' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = self::get_active_plugins_data();

        if ( empty( $active ) ) {
            return [];
        }

        $issues = [];

        foreach ( $active as $plugin ) {
            $wp_org = self::fetch_wp_org_data( $plugin['slug'] );

            if ( empty( $wp_org ) ) {
                continue;
            }

            $last_updated = $wp_org['last_updated'] ?? '';
            $tested_up_to = $wp_org['tested_up_to'] ?? '';
            $plugin_name  = esc_html( $wp_org['name'] ?? $plugin['slug'] );

            // Flag: not updated in 2+ years.
            if ( $last_updated ) {
                $days_since = ( time() - strtotime( $last_updated ) ) / DAY_IN_SECONDS;
                if ( $days_since > 730 ) {
                    $issues[] = [
                        'type'        => 'plugin_cve',
                        'severity'    => 'warning',
                        'title'       => sprintf(
                            /* translators: %1$s plugin name, %2$s number of years */
                            __( '%1$s has not been updated in over %2$s years', 'site-cliniq' ),
                            $plugin_name,
                            round( $days_since / 365, 1 )
                        ),
                        'detail'      => __( 'Abandoned plugins are a security risk. Consider finding an actively maintained alternative.', 'site-cliniq' ),
                        'plugin_slug' => $plugin['slug'],
                    ];
                }
            }

            // Flag: not tested with current WP version.
            global $wp_version;
            if ( $tested_up_to && version_compare( $tested_up_to, $wp_version, '<' ) ) {
                $major_installed = (int) $wp_version;
                $major_tested    = (int) $tested_up_to;

                if ( $major_installed > $major_tested ) {
                    $issues[] = [
                        'type'        => 'plugin_cve',
                        'severity'    => 'info',
                        'title'       => sprintf(
                            /* translators: %1$s plugin name, %2$s WP version, %3$s tested-up-to version */
                            __( '%1$s is not tested with WordPress %2$s (tested up to %3$s)', 'site-cliniq' ),
                            $plugin_name,
                            esc_html( $wp_version ),
                            esc_html( $tested_up_to )
                        ),
                        'detail'      => __( 'The plugin author has not confirmed compatibility with your current WordPress version. Test carefully before relying on this plugin.', 'site-cliniq' ),
                        'plugin_slug' => $plugin['slug'],
                    ];
                }
            }
        }

        return $issues;
    }

    // -------------------------------------------------------------------------

    private static function fetch_wp_org_data( string $slug ): array {
        $cache_key = 'sitecl_wporg_plugin_' . $slug;
        $cached    = get_transient( $cache_key );
        if ( false !== $cached ) {
            return is_array( $cached ) ? $cached : [];
        }

        $response = wp_remote_get(
            "https://api.wordpress.org/plugins/info/1.0/{$slug}.json",
            [ 'timeout' => 10 ]
        );

        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
            set_transient( $cache_key, [], HOUR_IN_SECONDS * 6 );
            return [];
        }

        $data = json_decode( wp_remote_retrieve_body( $response ), true );
        $data = is_array( $data ) ? $data : [];

        set_transient( $cache_key, $data, HOUR_IN_SECONDS * 12 );

        return $data;
    }

    private static function get_active_plugins_data(): array {
        if ( ! function_exists( 'get_plugins' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $all_plugins = get_plugins();
        $active      = (array) get_option( 'active_plugins', [] );
        $result      = [];

        foreach ( $active as $plugin_file ) {
            if ( ! isset( $all_plugins[ $plugin_file ] ) ) {
                continue;
            }
            $result[] = [
                'slug'    => explode( '/', $plugin_file )[0],
                'version' => $all_plugins[ $plugin_file ]['Version'] ?? '0.0.0',
            ];
        }

        return $result;
    }
}
