<?php
/**
 * AJAX Handler for Signature Sync
 *
 * @package VMPFence
 * @since 2.1.0
 */

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

/**
 * Handle signature sync from API (matches firewall sync pattern)
 * @since 2.1.0
 * @since 2.2.4 - Added memory limit increase for large syncs
 */
add_action('wp_ajax_vmpfence_sync_signatures', 'vmpfence_ajax_sync_signatures');

function vmpfence_ajax_sync_signatures() {
    // Safety net: bump memory limit for signature sync
    // The streamed writer keeps peak usage under ~10 MB, but this guards against
    // edge cases (e.g., very large individual signatures, WordPress overhead)
    @ini_set('memory_limit', '512M');
    
    // Verify nonce
    check_ajax_referer('vmpfence_scan_nonce', 'nonce');
    
    // Check user capabilities
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array(
            'message' => 'Insufficient permissions'
        ));
        return;
    }
    
    try {
        // Use the VMPFence_Signature_Sync class (matches firewall pattern)
        $result = VMPFence_Signature_Sync::sync_from_api();
        
        if ($result['success']) {
            // Success response (matches firewall format)
            wp_send_json_success(array(
                'message' => sprintf(
                    'Successfully synced %d signatures (Version: %s, Tier: %s)',
                    $result['imported'],
                    $result['version'],
                    strtoupper($result['license_tier'])
                ),
                'signature_count' => $result['imported'],
                'version' => $result['version'],
                'tier' => $result['license_tier']
            ));
        } else {
            // Error response
            $error_msg = !empty($result['errors']) ? implode(', ', $result['errors']) : 'Unknown error';
            wp_send_json_error(array(
                'message' => $error_msg
            ));
        }
        
    } catch (Exception $e) {
        wp_send_json_error(array(
            'message' => 'Error: ' . $e->getMessage()
        ));
    }
}
