<?php
/**
 * Scan Percentage AJAX Handler
 * 
 * Handles AJAX requests for scan percentage calculation
 * 
 * @package VMPFence
 * @since 1.0.0
 */

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

// Hook for logged-in users
add_action('wp_ajax_vmpfence_get_scan_percentage', 'vmpfence_handle_scan_percentage_ajax');

function vmpfence_handle_scan_percentage_ajax() {
    // Verify nonce
    if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), 'vmpfence_ajax_nonce')) {
        wp_send_json_error('Invalid nonce');
    }
    
    // Check permissions
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
    }
    
    try {
        // Include required classes
        require_once VMPFENCE_PLUGIN_DIR . 'includes/class-scan-percentage.php';
        
        // Get action
        $action = isset($_POST['scan_action']) ? sanitize_text_field(wp_unslash($_POST['scan_action'])) : 'get_status';
        
        switch ($action) {
            case 'get_status':
                $status = VMPFence_Scan_Percentage::getScanStatusDetails();
                
                // Add color for frontend
                $percentage = round($status['percentage'] * 100);
                if ($percentage >= 80) {
                    $status['color'] = '#28a745';
                } elseif ($percentage >= 60) {
                    $status['color'] = '#17a2b8';
                } elseif ($percentage >= 40) {
                    $status['color'] = '#ffc107';
                } else {
                    $status['color'] = '#dc3545';
                }
                
                wp_send_json_success($status);
                break;
                
            case 'get_recommendations':
                $recommendations = VMPFence_Scan_Percentage::getRecommendations();
                wp_send_json_success($recommendations);
                break;
                
            case 'calculate_for_type':
                $scan_type = isset($_POST['scan_type']) ? sanitize_text_field(wp_unslash($_POST['scan_type'])) : 'standard';
                
                // Temporarily calculate for specific scan type
                $original_type = VMPFence_Config::get('scanType');
                VMPFence_Config::set('scanType', $scan_type);
                
                $status = VMPFence_Scan_Percentage::getScanStatusDetails();
                
                // Restore original type
                VMPFence_Config::set('scanType', $original_type);
                
                wp_send_json_success(array(
                    'scan_type' => $scan_type,
                    'percentage' => round($status['percentage'] * 100),
                    'display_percentage' => $status['display_percentage'],
                    'status_message' => $status['status_message'],
                    'status_class' => $status['status_class']
                ));
                break;
                
            default:
                wp_send_json_error('Invalid action');
        }
        
    } catch (Exception $e) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Intentional for debugging
        // error_log('VMPFence Scan Percentage AJAX Error: ' . $e->getMessage());
        wp_send_json_error('Error calculating scan percentage: ' . $e->getMessage());
    }
}

// Add JavaScript for dynamic updates
add_action('admin_footer', 'vmpfence_scan_percentage_js');

function vmpfence_scan_percentage_js() {
    // Only load on VMPFence pages
    $screen = get_current_screen();
    if (!$screen || strpos($screen->id, 'vmpfence') === false) {
        return;
    }
    
    // Enqueue the scan percentage JavaScript file
    wp_enqueue_script(
        'vmpfence-scan-percentage',
        plugin_dir_url(dirname(__FILE__)) . 'assets/js/scan-percentage.js',
        array('jquery'),
        VMPFENCE_VERSION,
        true
    );
    
    // Localize script with nonce
    wp_localize_script('vmpfence-scan-percentage', 'vmpfence_scan_percentage', array(
        'nonce' => wp_create_nonce('vmpfence_ajax_nonce')
    ));
}