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

/**
 * Helper functions for handling plugin and theme updates
 */

/**
 * Track update progress and send webhooks
 * 
 * @param string $update_id The update operation ID
 * @param array $items Item slugs and their current status
 * @param string $type The webhook type: 'progress' or 'completed'
 * @return bool Success status
 */
function wpsec_track_update_progress($update_id, $items, $type = 'progress') {
    if (empty($update_id)) {
        wpsec_debug_log('❌ Update progress tracking: Missing update_id', 'error');
        return false;
    }
    
    if (empty($items)) {
        wpsec_debug_log('❌ Update progress tracking: No items to track', 'error');
        return false;
    }
    
    // Format items for webhook
    $formatted_items = [];
    foreach ($items as $slug => $status) {
        $item = [
            'slug' => $slug,
            'status' => $status['status'] ?? 'initializing',
            'error' => $status['error'] ?? null
        ];
        $formatted_items[] = $item;
    }
    
    // Include webhooks file if needed
    if (!function_exists('wpsec_send_webhook')) {
        require_once(WPSEC_PLUGIN_DIR . 'includes/webhooks.php');
    }
    
    // Send appropriate webhook based on type
    if ($type === 'completed') {
        if (function_exists('wpsec_send_update_completed_webhook')) {
            return wpsec_send_update_completed_webhook($update_id, $formatted_items);
        }
    } else {
        if (function_exists('wpsec_send_update_progress_webhook')) {
            return wpsec_send_update_progress_webhook($update_id, $formatted_items);
        }
    }
    
    return false;
}

/**
 * Generate a unique update ID
 * 
 * @return string Unique update ID
 */
function wpsec_generate_update_id() {
    return 'upd_' . time() . '_' . substr(md5(uniqid(wp_rand(), true)), 0, 8);
}
