<?php
/**
 * VMPFence Scan View
 *
 * @package VMPFence
 * @since 1.0.0
 * @since 2.0.0 Updated to reflect VMP WordPress Security branding.
 * @since 2.1.0 Added dynamic scan status and enable scans button.
 * @since 2.2.2 Updated to reflect VMP Security branding.
 * @since 2.2.4 Added malware signatures sync button and API key check.
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Get signature counts and sync info (same as vmpfence scanner.php)
$api_key = VMPFence_Config::get('central_api_key');
$license_tier = VMPFence_License::get_license_type();

// Enqueue scan-specific CSS
wp_enqueue_style('vmpfence-scan-css', plugins_url('assets/css/scan.css', dirname(__FILE__)), array(), '1.0.0');

// Enqueue toast notification system
wp_enqueue_style('vmpfence-toast-notifications', plugins_url('assets/css/toast-notifications.css', dirname(__FILE__)), array(), '1.0.3');
wp_enqueue_script('vmpfence-toast-notifications', plugins_url('assets/js/toast-notifications.js', dirname(__FILE__)), array('jquery'), '1.0.3', true);

// Enqueue Premium Upgrade Button Handler (required for "UPGRADE TO PREMIUM" buttons)
wp_enqueue_script('vmpfence-premium-upgrade', plugins_url('assets/js/premium-upgrade.js', dirname(__FILE__)), array('jquery'), VMPFENCE_VERSION, true);

// Enqueue scan-specific JavaScript
wp_enqueue_script('vmpfence-scan-js', plugins_url('assets/js/scan.js', dirname(__FILE__)), array('jquery'), '1.0.3', true);

// Check if signature sync is currently in progress (for page-load button state)
$sync_lock_key = 'vmpfence_signature_sync_lock';
$sync_lock_time = get_transient($sync_lock_key);
$is_sync_in_progress = false;
if ($sync_lock_time) {
    $sync_lock_age = time() - (int) $sync_lock_time;
    // Only consider it active if the lock is fresh (< 5 min — matches staleness threshold in class-signature-sync.php)
    $is_sync_in_progress = ($sync_lock_age < 300);
}

// Localize script for AJAX
wp_localize_script('vmpfence-scan-js', 'vmpfence_ajax', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'nonce' => wp_create_nonce('vmpfence_scan_nonce'),
    'is_sync_in_progress' => $is_sync_in_progress,
));

// Add inline script for enable scans button
wp_add_inline_script('vmpfence-scan-js', "
jQuery(document).ready(function($) {
    // Handle enable automatic scans button
    $('#vmpfence-enable-scans-btn').on('click', function() {
        var \$btn = $(this);
        var originalText = \$btn.text();
        
        // Disable button and show loading
        \$btn.text('ENABLING...').prop('disabled', true);
        
        // Make AJAX request to enable scans
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_enable_scans',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Reload the page to show updated status
                    window.location.reload();
                } else {
                    VMPFenceNotifications.showError('Error enabling scans: ' + (response.data.message || 'Unknown error'));
                    \$btn.text(originalText).prop('disabled', false);
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Error enabling scans. Please try again.');
                \$btn.text(originalText).prop('disabled', false);
            }
        });
    });
});
");

// Get current scan status for dynamic display
$scheduled_scans_enabled = VMPFence_Config::get('scheduledScansEnabled', 1);
$scan_status_text = $scheduled_scans_enabled ? 'VMP Security Scan Enabled' : 'Automatic Scan Deactivated';
?>

<div class="wrap">
    <!-- WordPress Notices -->
    <?php settings_errors(); ?>
</div>

<!-- VMPFence Header Banner -->
<div class="vmpfence-header-banner">
    <div class="vmpfence-logo-section">
        <div class="vmpfence-logo">
            <img src="<?php echo esc_url( VMPFENCE_PLUGIN_URL . 'admin/assets/images/VMP-logo.svg' ); ?>" alt="VMP Security" style="width: 24px; height: 24px; vertical-align: middle; margin-right: 8px;"> 
            <span class="brand-header">VMP Security Scan</span>
        </div>
    </div>
    <!-- <div class="vmpfence-header-right">
        <a href="#" class="vmpfence-learn-more">Learn more about this Dashboard ↗</a>
    </div> -->
</div>


<!-- Main Scan Grid (outside of .wrap to avoid notice interference) -->
<div class="vmpfence-scan-grid">
        <!-- Top Row: Scan Header + Premium Panel -->
        <div class="vmpfence-top-row">
            <!-- Scan Header -->
            <div class="vmpfence-scan-header" id="vmpfence-scan-status">
                <?php if ($scheduled_scans_enabled): ?>
                <div class="vmpfence-scan-enabled">
                    <svg width="120" height="120" viewBox="0 0 120 120">
                        <path d="M25 60 L50 85 L95 35" stroke="#191970" stroke-width="16" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                    <h2><?php echo esc_html($scan_status_text); ?></h2>
                </div>
                <?php else: ?>
                <div class="vmpfence-scan-disabled">
                    <h2><?php echo esc_html($scan_status_text); ?></h2>
                    <p>A VMP Security scan examines all files, posts, pages, and comments on your WordPress website looking for malware, known malicious URLs, and known patterns of infections. It also does several other reputation and server checks.</p>
                    <p>
                        <button id="vmpfence-enable-scans-btn" class="button button-primary">ENABLE AUTOMATIC SCANS</button>
                    </p>
                </div>
                <?php endif; ?>
            </div>

            <?php
            // Check premium status using the proper method
            $license_type = VMPFence_License::get_license_type();
            $is_premium = ($license_type === VMPFence_Constants::LICENSE_PREMIUM);
            ?>
            <div class="vmpfence-scan-premium-item" id="vmpfence-premium-progress">
                <?php if (!$is_premium): ?>
                    <div class="vmpfence-scan-premium-disabled">
                        <h3>Premium Protection Disabled</h3>
                        <p>As a free VMP Security user, you are currently using the Community version of the Threat Defense Feed. Premium users are protected by real-time malware signatures. Upgrade to Premium today to improve your protection.</p>
                        <div class="vmpfence-scan-premium-buttons">
                            <a href="#" class="vmpfence-scan-premium-upgrade-btn">UPGRADE TO PREMIUM</a>
                            <a href="#" target="_self" class="vmpfence-scan-premium-learn-btn">LEARN MORE</a>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="vmpfence-scan-premium-enabled">
                        <h3>Premium Protection Enabled</h3>
                        <p>Your site is protected by real-time malware signatures</p>
                    </div>
                    <div class="vmpfence-scan-premium-buttons">
                            <!-- <a href="#" class="vmpfence-scan-premium-upgrade-btn">UPGRADE TO PREMIUM</a>
                            <a href="#" target="_self" class="vmpfence-scan-premium-learn-btn">LEARN MORE</a> -->
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($scheduled_scans_enabled): ?>
        <!-- Bottom Row: Scan Progress Cards -->
        <div class="vmpfence-scan-row">
            <!-- Scan Type Card -->
            <div class="vmpfence-scan-card">
                <div class="vmpfence-scan-progress" data-status-type="scan_type_page">
                    <?php
                    // Calculate scan type percentage: 30% premium + 11% reputation + 59% options
                    require_once VMPFENCE_PLUGIN_DIR . 'status-modal/models/class-scanner-status.php';
                    $scan_status = VMPFence_Scanner_Status::get_scan_type_card_status();
                    $scan_percentage = round($scan_status['percentage'] * 100);
                    
                    // Set color based on percentage
                    if ($scan_percentage >= 80) {
                        $scan_color = '#28a745'; // Green
                    } elseif ($scan_percentage >= 60) {
                        $scan_color = '#17a2b8'; // Blue
                    } elseif ($scan_percentage >= 40) {
                        $scan_color = '#ffc107'; // Yellow
                    } else {
                        $scan_color = '#dc3545'; // Red
                    }
                    
                    // Get scan type for title
                    $scan_type = (string) VMPFence_Config::get('scanType');
                    $scan_type = ucwords(str_replace('_', ' ', strtolower($scan_type)));
                    ?>
                    <svg class="vmpfence-circle-chart" viewbox="0 0 33.83098862 33.83098862" width="100" height="100">
                        <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <circle id="scan-types-progress" class="vmpfence-circle-progress-bar" stroke="<?php echo esc_attr($scan_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($scan_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <text id="scan-types-text" x="16.91549431" y="20" text-anchor="middle"  transform="rotate(90 16.91549431 16.91549431)" font-size="6" font-weight="bold" class="vmpfence-circle-text"><?php echo esc_html($scan_percentage); ?>%</text>
                    </svg>
                </div>
                <div class="vmpfence-scan-info">
                    <h3 id="scan-types-title">Scan Type: <?php echo esc_html($scan_type); ?></h3>
                    <p id="scan-types-description"><?php echo esc_html($scan_type); ?> detection capability</p>
                    <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-scan-options') ); ?>" class="vmpfence-manage-link">Manage Scan</a>
                </div>
            </div>

            <!-- Malware Signatures Card -->
            <div class="vmpfence-scan-card">
                <div class="vmpfence-scan-progress" data-status-type="malware_signatures">
                    <?php
                    // Calculate malware signatures percentage: 70% free + 30% premium
                    $is_premium = ($license_type === VMPFence_Constants::LICENSE_PREMIUM);
                    $malware_percentage = 70; // Base 70% for free users
                    if ($is_premium) {
                        $malware_percentage = 100; // 70% + 30% = 100% for premium
                    }
                    
                    // Set color based on percentage
                    if ($malware_percentage >= 80) {
                        $malware_color = '#28a745'; // Green
                    } elseif ($malware_percentage >= 60) {
                        $malware_color = '#17a2b8'; // Blue
                    } elseif ($malware_percentage >= 40) {
                        $malware_color = '#ffc107'; // Yellow
                    } else {
                        $malware_color = '#dc3545'; // Red
                    }
                    ?>
                    <svg class="vmpfence-circle-chart" viewbox="0 0 33.83098862 33.83098862" width="100" height="100">
                        <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <circle id="malware-signatures-progress" class="vmpfence-circle-progress-bar" stroke="<?php echo esc_attr($malware_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($malware_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <text id="malware-signatures-text" x="16.91549431" y="20" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" font-size="6" font-weight="bold" class="vmpfence-circle-text"><?php echo esc_html($malware_percentage); ?>%</text>
                    </svg>
                </div>
                <div class="vmpfence-scan-info">
                    <h3 id="malware-signatures-title">Malware Signatures</h3>
                    <p id="malware-signatures-description"><?php echo $is_premium ? 'Premium malware detection signatures enabled' : 'Essential malware detection signatures included'; ?></p>
                    <?php if (!empty($api_key)): ?>
                        <button type="button" class="vmpfence-manage-link" id="vmpfence-sync-signatures" style="background: #191970; color: white; border: none; padding: 6px 12px; border-radius: 3px; cursor: pointer; font-size: 13px; margin: 5px auto 0; display: block;">
                            <span class="dashicons dashicons-update" style="font-size: 14px; margin-top: 2px;"></span>
                            Sync from API
                        </button>
                    <?php else: ?>
                        <span class="vmpfence-premium-notice" style="display: block; margin-top: 5px; font-style: italic; font-size: 12px; color: #666;">
                            ⭐ Complete setup wizard to enable API sync
                        </span>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Reputation Checks Card -->
            <div class="vmpfence-scan-card">
                <div class="vmpfence-scan-progress" data-status-type="reputation_checks">
                    <?php
                    // Calculate reputation checks percentage: Spamvertizing (33%) + Spam IP (33%) + GSB Blocklist (33%)
                    $spamvertize = (bool) VMPFence_Config::get('spamvertizeCheck', 0);
                    $spam_ip = (bool) VMPFence_Config::get('checkSpamIP', 0);
                    $gsb = (bool) VMPFence_Config::get('scansEnabled_checkGSB', 0);
                    
                    $reputation_percentage = 0;
                    if ($spamvertize) $reputation_percentage += 33;
                    if ($spam_ip) $reputation_percentage += 33;
                    if ($gsb) $reputation_percentage += 33;
                    
                    // Round 99 to 100 when all three checks are enabled
                    if ($reputation_percentage == 99) {
                        $reputation_percentage = 100;
                    }
                    
                    // Set color based on percentage
                    if ($reputation_percentage >= 80) {
                        $reputation_color = '#28a745'; // Green
                    } elseif ($reputation_percentage >= 60) {
                        $reputation_color = '#17a2b8'; // Blue
                    } elseif ($reputation_percentage >= 40) {
                        $reputation_color = '#ffc107'; // Yellow
                    } else {
                        $reputation_color = '#dc3545'; // Red
                    }
                    ?>
                    <svg class="vmpfence-circle-chart" viewbox="0 0 33.83098862 33.83098862" width="100" height="100">
                        <circle class="vmpfence-circle-bg" stroke="#e6e6e6" stroke-width="2" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <circle class="vmpfence-circle-progress-bar" stroke="<?php echo esc_attr($reputation_color); ?>" stroke-width="2" stroke-dasharray="<?php echo esc_attr($reputation_percentage); ?>,100" stroke-linecap="round" fill="none" cx="16.91549431" cy="16.91549431" r="15.91549431"></circle>
                        <text x="16.91549431" y="20" text-anchor="middle" transform="rotate(90 16.91549431 16.91549431)" font-size="6" font-weight="bold" class="vmpfence-circle-text"><?php echo esc_html($reputation_percentage); ?>%</text>
                    </svg>
                </div>
                <div class="vmpfence-scan-info">
                    <h3>Reputation Checks</h3>
                    <p>Check spam & spamvertising blocklists</p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=vmpfence-scan-options#general-content')); ?>" class="vmpfence-manage-link">Manage Options</a>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Scan Actions and Status Section -->
        <div class="vmpfence-scan-actions">
            <!-- Top Row: Start Scan + Help + Options -->
            <div class="vmpfence-scan-actions-top">
                <!-- Start New Scan Button -->
                <div class="vmpfence-start-scan" id="vmpfence-start-scan">
                    <button class="vmpfence-btn-start-scan">START NEW SCAN</button>
                    <!-- <button class="vmpfence-btn-debug-logs" style="margin-left: 10px; background: #666; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">VIEW DEBUG LOGS</button> -->
                </div>

                <!-- Help Section -->
                <a href="<?php echo esc_url( admin_url('admin.php?page=vmpfence-help') ); ?>" class="vmpfence-help-section" style="text-decoration: none; color: inherit; cursor: pointer;">
                    <div class="vmpfence-help-icon">
                        <svg viewBox="0 0 409.6 409.6" width="40" height="40" fill="#9E9E9E">
                            <title>support</title>
                            <path d="M204.8,0C91.69,0,0,91.69,0,204.8S91.69,409.6,204.8,409.6s204.8-91.7,204.8-204.8S317.91,0,204.8,0ZM128,204.8a76.8,76.8,0,1,1,76.8,76.8A76.8,76.8,0,0,1,128,204.8Zm242.39,68.59-71-29.4a102.71,102.71,0,0,0,0-78.39l48.85-20.23,22.12-9.16a179.65,179.65,0,0,1,0,137.18Zm-97-234.18-29.39,71a102.65,102.65,0,0,0-78.39,0L151.82,76.9,136.21,39.21a179.7,179.7,0,0,1,137.18,0Zm-234.18,97L76.9,151.82l33.28,13.78a102.65,102.65,0,0,0,0,78.39l-71,29.4a179.7,179.7,0,0,1,0-137.18Zm97,234.18,9.16-22.12,20.23-48.85a102.68,102.68,0,0,0,78.39,0l29.39,71a179.65,179.65,0,0,1-137.18,0Zm0,0"></path>
                        </svg>
                    </div>
                    <div class="vmpfence-help-content">
                        <h3>Help</h3>
                        <p>Find the documentation and help you need.</p>
                    </div>
                </a>

                <!-- Scan Options Section -->
                <div class="vmpfence-options-section" id="vmpfence-scan-options" style="cursor: pointer;" onclick="window.location.href='<?php echo esc_js( esc_url( admin_url('admin.php?page=vmpfence-scan-options') ) ); ?>';">
                    <div class="vmpfence-options-icon">
                        <svg viewBox="0 0 100.11 100.11" width="40" height="40" fill="#9E9E9E">
                            <title>options</title>
                            <path d="M99.59,41.42a2.06,2.06,0,0,0-1.37-.82L86.3,38.78a39.34,39.34,0,0,0-2.67-6.39q1.17-1.63,3.52-4.6t3.32-4.33A2.52,2.52,0,0,0,91,22a2.1,2.1,0,0,0-.46-1.43Q88.18,17.2,79.78,9.45a2.52,2.52,0,0,0-1.63-.65,2.12,2.12,0,0,0-1.57.59l-9.25,7a40.09,40.09,0,0,0-5.87-2.41L59.64,2a1.92,1.92,0,0,0-.75-1.4A2.46,2.46,0,0,0,57.29,0H42.82a2.19,2.19,0,0,0-2.34,1.82,106,106,0,0,0-1.89,12.12,37.62,37.62,0,0,0-5.93,2.48l-9-7A2.78,2.78,0,0,0,22,8.8q-1.44,0-6.16,4.66a64.88,64.88,0,0,0-6.42,7A2.75,2.75,0,0,0,8.8,22a2.44,2.44,0,0,0,.65,1.56q4.37,5.28,7,9a32.38,32.38,0,0,0-2.54,6L1.76,40.34a2,2,0,0,0-1.24.85A2.5,2.5,0,0,0,0,42.69V57.16a2.44,2.44,0,0,0,.52,1.53,2,2,0,0,0,1.37.82l11.93,1.76a31.91,31.91,0,0,0,2.67,6.45Q15.31,69.35,13,72.31T9.65,76.65a2.54,2.54,0,0,0-.07,3q2.54,3.52,10.75,11a2.25,2.25,0,0,0,1.63.71,2.35,2.35,0,0,0,1.63-.59l9.19-7a40.54,40.54,0,0,0,5.87,2.41l1.82,12a1.92,1.92,0,0,0,.75,1.4,2.45,2.45,0,0,0,1.6.55H57.29a2.2,2.2,0,0,0,2.35-1.82,107.41,107.41,0,0,0,1.89-12.12,37.19,37.19,0,0,0,5.93-2.48l9,7a3.18,3.18,0,0,0,1.69.59q1.43,0,6.13-4.62a65.86,65.86,0,0,0,6.45-7,2.16,2.16,0,0,0,.59-1.5,2.51,2.51,0,0,0-.65-1.63q-4.69-5.74-7-9a41.57,41.57,0,0,0,2.54-5.93l12.06-1.82a2,2,0,0,0,1.3-.85,2.52,2.52,0,0,0,.52-1.5V43a2.46,2.46,0,0,0-.52-1.53ZM61.85,61.86a16.08,16.08,0,0,1-11.8,4.89A16.69,16.69,0,0,1,33.37,50.06,16.69,16.69,0,0,1,50.06,33.37,16.69,16.69,0,0,1,66.74,50.06a16.08,16.08,0,0,1-4.89,11.8Zm0,0"></path>
                        </svg>
                    </div>
                    <div class="vmpfence-options-content">
                        <h3>Scan Options and Scheduling</h3>
                        <p>Manage scan options including scheduling</p>
                    </div>
                </div>
            </div>

            <!-- Bottom Row: Scan Status Items -->
            <div class="vmpfence-scan-status-row">
                <div class="vmpfence-status-item" data-scan-type="spamvertising_checks">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <rect x="8" y="12" width="14" height="10" rx="2" fill="#9E9E9E"/>
                            <path d="M12 12V10C12 8.895 12.895 8 14 8H16C17.105 8 18 8.895 18 10V12" stroke="#9E9E9E" stroke-width="2" fill="none"/>
                            <circle cx="15" cy="17" r="1.5" fill="white"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Spamvertising Checks</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="spam_check">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <rect x="8" y="12" width="14" height="10" rx="2" fill="#9E9E9E"/>
                            <path d="M12 12V10C12 8.895 12.895 8 14 8H16C17.105 8 18 8.895 18 10V12" stroke="#9E9E9E" stroke-width="2" fill="none"/>
                            <circle cx="15" cy="17" r="1.5" fill="white"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Spam Check</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="blocklist_check">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <rect x="8" y="12" width="14" height="10" rx="2" fill="#9E9E9E"/>
                            <path d="M12 12V10C12 8.895 12.895 8 14 8H16C17.105 8 18 8.895 18 10V12" stroke="#9E9E9E" stroke-width="2" fill="none"/>
                            <circle cx="15" cy="17" r="1.5" fill="white"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Blocklist Check</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="server_state">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Server State</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="file_changes">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>File Changes</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="malware_scan">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Malware Scan</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="content_safety">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Content Safety</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="public_files">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Public Files</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="user_security">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>User Security</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="vulnerability_scan">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>Vulnerability Scan</p>
                    </div>
                </div>

                <div class="vmpfence-status-item" data-scan-type="user_option_audit">
                    <div class="vmpfence-status-icon">
                        <svg width="30" height="30" viewBox="0 0 30 30">
                            <circle cx="15" cy="15" r="12" fill="#9E9E9E"/>
                            <path d="M9 15L13 19L21 11" stroke="white" stroke-width="2" fill="none"/>
                        </svg>
                    </div>
                    <div class="vmpfence-status-text">
                        <p>User & Option Audit</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Scan Results Section -->
        <div class="vmpfence-scan-results">
            <!-- Scan Status Header -->
            <div class="vmpfence-scan-status-header">
                <div class="vmpfence-scan-complete">
                    <span class="vmpfence-scan-timestamp" id="vmpfence-scan-timestamp"></span>
                    <span class="vmpfence-scan-message" id="vmpfence-scan-message"><b>Start Scanning</b></span>
                </div>
                <div class="vmpfence-scan-logs">
                    <a href="#" class="vmpfence-log-link" id="vmpfence-email-log-btn">EMAIL ACTIVITY LOG</a>
                    <a href="<?php echo esc_attr(home_url()); ?>?_vmpfence=viewActivityLog&amp;nonce=<?php echo esc_attr(wp_create_nonce('vmpfence_full_log_nonce')); ?>" class="vmpfence-log-link" target="_blank">VIEW FULL LOG</a>
                    <a href="#" class="vmpfence-log-link" id="vmpfence-show-log-btn">SHOW LOG</a>
                </div>
            </div>

            <!-- Inline Debug Log Container -->
            <div id="vmpfence-inline-debug-log" class="vmpfence-inline-debug-log" style="display: none;">
                <!-- <div class="vmpfence-debug-log-header">
                    <h3>Scan Activity Log</h3>
                    <button id="vmpfence-hide-log-btn" class="vmpfence-hide-log-btn">Hide Log</button>
                </div> -->
                <div id="vmpfence-inline-debug-content" class="vmpfence-debug-log-content">
                    <p>Loading debug logs...</p>
                </div>
            </div>

            <!-- Results Tabs and Actions -->
            <div class="vmpfence-results-tabs-section">
                <div class="vmpfence-results-tabs">
                    <div class="vmpfence-tab vmpfence-tab-active">
                        Results Found <span class="vmpfence-tab-count">(0)</span>
                    </div>
                    <div class="vmpfence-tab">
                        Ignored Results <span class="vmpfence-tab-count">(0)</span>
                    </div>
                </div>
                <div class="vmpfence-results-actions">
                    <button id="delete-all-deletable-files" class="vmpfence-btn-bulk-delete">DELETE ALL DELETABLE FILES</button>
                    <button class="vmpfence-btn-repair">REPAIR ALL REPAIRABLE FILES</button>
                </div>
            </div>

            <!-- Statistics Row -->
            <div class="vmpfence-stats-row">
                <div class="vmpfence-stat-item">
                    <div class="vmpfence-stat-label">Posts, Comments, & Files</div>
                    <div class="vmpfence-stat-count">0</div>
                </div>
                <div class="vmpfence-stat-item">
                    <div class="vmpfence-stat-label">Themes & Plugins</div>
                    <div class="vmpfence-stat-count">0</div>
                </div>
                <div class="vmpfence-stat-item">
                    <div class="vmpfence-stat-label">Users Checked</div>
                    <div class="vmpfence-stat-count">0</div>
                </div>
                <div class="vmpfence-stat-item">
                    <div class="vmpfence-stat-label">URLs Checked</div>
                    <div class="vmpfence-stat-count">0</div>
                </div>
                <div class="vmpfence-stat-item">
                    <div class="vmpfence-stat-label">Results Found</div>
                    <div class="vmpfence-stat-count">0</div>
                </div>
            </div>

            <!-- No Issues Message -->
            <div class="vmpfence-no-issues">
                <div class="vmpfence-no-issues-message">
                    No new issues have been found.
                </div>
            </div>

            <!-- About Us Section -->
            <div class="vmpfence-about-section">
                <h3>About VMP Security</h3>
                <p>VMP Security is a comprehensive security scanner designed specifically for WordPress websites. Our advanced scanning technology helps protect your website from malware, vulnerabilities, and security threats, ensuring your WordPress site remains secure and performs optimally.</p>
                <div class="vmpfence-about-features">
                    <div class="vmpfence-feature">
                        <strong>Advanced Malware Detection:</strong> Comprehensive scanning for known threats and suspicious patterns.
                    </div>
                    <!-- <div class="vmpfence-feature">
                        <strong>Real-time Protection:</strong> Continuous monitoring and automated security responses.
                    </div> -->
                    <div class="vmpfence-feature">
                        <strong>WordPress Optimized:</strong> Built specifically for WordPress security requirements.
                    </div>
                </div>
            </div>
    </div>
</div>

<!-- Toast Notification Container -->
<?php require_once plugin_dir_path(__FILE__) . 'partials/toast-notification-container.php'; ?>

<!-- Debug Log Modal -->
<div id="vmpfence-debug-modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 10000;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; width: 80%; max-width: 800px; max-height: 80%; border-radius: 8px; overflow: hidden;">
        <div style="padding: 20px; border-bottom: 1px solid #ddd; display: flex; justify-content: space-between; align-items: center;">
            <h3 style="margin: 0;">VMP Security Debug Logs - Server State, File Changes, User Security, Content Safety, Public Files & User Audit</h3>
            <button id="vmpfence-close-debug" style="background: none; border: none; font-size: 24px; cursor: pointer;">&times;</button>
        </div>
        <div id="vmpfence-debug-content" style="padding: 20px; max-height: 400px; overflow-y: auto; background: #f5f5f5; font-family: monospace; font-size: 12px; line-height: 1.4;">
            <p>No debug logs available. Run a scan first.</p>
        </div>
        <div style="padding: 15px; border-top: 1px solid #ddd; text-align: right;">
            <button id="vmpfence-refresh-debug" style="background: #0073aa; color: white; padding: 8px 16px; border: none; border-radius: 4px; margin-right: 10px; cursor: pointer;">Refresh Logs</button>
            <button id="vmpfence-close-debug-2" style="background: #666; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;">Close</button>
        </div>
    </div>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    // Handle enable automatic scans button
    $('#vmpfence-enable-scans-btn').on('click', function() {
        var $btn = $(this);
        var originalText = $btn.text();
        
        // Disable button and show loading
        $btn.text('ENABLING...').prop('disabled', true);
        
        // Make AJAX request to enable scans
        $.ajax({
            url: vmpfence_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'vmpfence_enable_scans',
                nonce: vmpfence_ajax.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Reload the page to show updated status
                    window.location.reload();
                } else {
                    VMPFenceNotifications.showError('Error enabling scans: ' + (response.data.message || 'Unknown error'));
                    $btn.text(originalText).prop('disabled', false);
                }
            },
            error: function() {
                VMPFenceNotifications.showError('Error enabling scans. Please try again.');
                $btn.text(originalText).prop('disabled', false);
            }
        });
    });

    // ── Sync button: set initial state from PHP lock check ─────────
    var syncButton = $('#vmpfence-sync-signatures');
    var syncOriginalHtml = syncButton.html();
    if (typeof vmpfence_ajax !== 'undefined' && vmpfence_ajax.is_sync_in_progress) {
        syncButton.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Syncing...');
        // Re-check after 10 seconds — just reload the page so PHP re-checks the transient.
        // Do NOT call the sync endpoint here (would trigger a new sync if the lock expired).
        setTimeout(function() {
            location.reload();
        }, 10000);
    }

    // Signature sync button handler
    $('#vmpfence-sync-signatures').on('click', function(e) {
        e.preventDefault();
        
        var button = $(this);
        var originalHtml = button.html();
        
        VMPFenceNotifications.showConfirmModal({
            title: 'Sync Malware Signatures',
            message: 'Sync malware signatures from the API server?\n\nThis will fetch the latest signature database (may take a few moments for large updates).',
            confirmText: 'Yes, Sync Now',
            cancelText: 'Cancel',
            type: 'info'
        }).then(function(confirmed) {
            if (!confirmed) {
                return;
            }
            
            // Disable button and show loading state
            button.prop('disabled', true).html('<span class="dashicons dashicons-update spin"></span> Syncing...');
            // Cross-disable: also disable scan button while sync is running
            var $scanBtn = $('.vmpfence-btn-start-scan');
            var scanBtnWasEnabled = !$scanBtn.prop('disabled');
            if (scanBtnWasEnabled) {
                $scanBtn.prop('disabled', true).data('disabled-by-sync', true);
            }
            var loadingToast = VMPFenceNotifications.showInfo('Syncing malware signatures from API...', 0, 'Please Wait');
            
            // Make AJAX request
            $.ajax({
                url: vmpfence_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'vmpfence_sync_signatures',
                    nonce: vmpfence_ajax.nonce
                },
                success: function(response) {
                    VMPFenceNotifications.removeToast(loadingToast);
                    
                    if (response.success) {
                        // Show detailed success message with signature count, version, and tier
                        var successMessage = response.data.message + ' Page will reload...';
                        VMPFenceNotifications.showSuccess(successMessage, 4000, 'Sync Complete');
                        
                        // Reload page after 3 seconds (gives user time to read the message)
                        setTimeout(function() {
                            location.reload();
                        }, 3000);
                    } else {
                        // Check if the error is specifically "already in progress"
                        var errorMsg = (response.data && response.data.message) ? response.data.message : 'Unknown error';
                        if (errorMsg.indexOf('already in progress') !== -1) {
                            // Keep button disabled with "in progress" indicator
                            VMPFenceNotifications.showInfo('Signature sync is running. The button will re-enable when it completes.', 5000, 'Sync In Progress');
                            button.html('<span class="dashicons dashicons-update spin"></span> Syncing...');
                            // Re-check after 10 seconds
                            setTimeout(function() {
                                location.reload();
                            }, 10000);
                        } else {
                            VMPFenceNotifications.showError('Signature sync failed: ' + errorMsg);
                            button.prop('disabled', false).html(originalHtml);
                            // Re-enable scan button if we disabled it
                            if (scanBtnWasEnabled && $scanBtn.data('disabled-by-sync')) {
                                $scanBtn.prop('disabled', false).removeData('disabled-by-sync');
                            }
                        }
                    }
                },
                error: function(xhr, status, error) {
                    VMPFenceNotifications.removeToast(loadingToast);
                    VMPFenceNotifications.showError('AJAX error: ' + error);
                    button.prop('disabled', false).html(originalHtml);
                    // Re-enable scan button if we disabled it
                    if (scanBtnWasEnabled && $scanBtn.data('disabled-by-sync')) {
                        $scanBtn.prop('disabled', false).removeData('disabled-by-sync');
                    }
                }
            });
        });
    });
});
</script>

<style>
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
.dashicons.spin {
    display: inline-block !important;
    animation: spin 1s linear infinite !important;
    vertical-align: middle !important;
}
</style>
