<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
function moesec_external_scan_tab() {
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'moesec'));
    }

    $site_url = esc_url(get_site_url());
    $scan_url = esc_url_raw("https://scan.moesec.com/scan?site=" . urlencode($site_url) . "&plugin");
    $scan_url2 = esc_url_raw("https://scan.moesec.com/scan?site=" . urlencode($site_url) . "&plugin2");    
    if (isset($_POST['moesec_external_scan']) && check_admin_referer('moesec_external_scan', 'moesec_external_scan_nonce')) {
        $response = wp_safe_remote_get($scan_url);
        
        if (is_wp_error($response)) {
            echo '<div class="error"><p>' . esc_html__('Note: Busy External Scan Queue. *Still Running..DO NOT refresh, Please recheck in 10 minutes.*', 'moesec') . '</p></div>';
        } else {
            $scan_result = wp_remote_retrieve_body($response);
            if (!empty($scan_result)) {
                echo '<h3>' . esc_html__('Scan Results for', 'moesec') . ' ' . esc_html($site_url) . '</h3>';
                echo '<ul>';
                echo '<li>' . esc_html__('Malware Status:', 'moesec') . ' ' . esc_html(strpos($scan_result, "ID#") !== false ? __('Infected', 'moesec') : __('Clean', 'moesec')) . '</li>';
                echo '<li>' . esc_html__('Blacklist Status:', 'moesec') . ' ' . esc_html(strpos($scan_result, "is BLACKLISTED by") !== false ? __('Blacklisted', 'moesec') : __('Not Blacklisted', 'moesec')) . '</li>';
                echo '<li>' . esc_html__('WordPress Version:', 'moesec') . ' ' . esc_html(strpos($scan_result, "Outdated WordPress version detected") !== false ? __('Outdated', 'moesec') : __('Up to date', 'moesec')) . '</li>';
                echo '<li>' . esc_html__('SSL Status:', 'moesec') . ' ' . esc_html(strpos($scan_result, "*Valid*") !== false ? __('Valid', 'moesec') : __('Invalid', 'moesec')) . '</li>';
                echo '<li>' . esc_html__('Security Headers:', 'moesec') . ' ' . esc_html(strpos($scan_result, "*Missing") !== false ? __('Missing Headers', 'moesec') : __('Good', 'moesec')) . '</li>';
                echo '</ul>';
            } else {
                echo '<div class="error"><p>' . esc_html__('Error: Scan Failed. Try again later', 'moesec') . '</p></div>';
            }
        }
    }
    
    ?>
    <form method="post" action="">
        <?php wp_nonce_field('moesec_external_scan', 'moesec_external_scan_nonce'); ?>
        <input type="submit" name="moesec_external_scan" class="button button-primary" value="<?php esc_attr_e('Run External Scan', 'moesec'); ?>">
        <a href="<?php echo esc_url($scan_url2); ?>" class="button button-secondary" target="_blank"><?php esc_html_e('Detailed External Scan', 'moesec'); ?></a>
    </form>
    <?php
}
