<?php
/**
 * AJAX Handler for Manual Update Checks
 */

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

class USCDN_Update_Ajax {
    
    public static function init() {
        add_action('wp_ajax_uscdn_check_updates', [__CLASS__, 'check_updates']);
    }
    
    /**
     * AJAX handler for checking updates
     */
    public static function check_updates() {
        // Verify nonce
        check_ajax_referer('uscdn_check_updates', 'nonce');
        
        // Check permissions
        if (!current_user_can('update_plugins')) {
            wp_send_json_error([
                'message' => 'You do not have permission to check for updates.'
            ]);
        }
        
        // Get updater instance
        if (!isset($GLOBALS['uscdn_updater'])) {
            wp_send_json_error([
                'message' => 'Update system not initialized.'
            ]);
        }
        
        // Force check for updates
        $remote = $GLOBALS['uscdn_updater']->force_check();
        
        if (!$remote) {
            wp_send_json_error([
                'message' => 'Could not check for updates. Please verify the update URL is accessible.',
                'url' => 'https://awsmarketplace-public-personal.s3.us-east-1.amazonaws.com/UtilS-Wordpress-RHINO-MARLIN-Plugin/update-info.json'
            ]);
        }
        
        // Compare versions
        if (version_compare(USCDN_VERSION, $remote->version, '<')) {
            wp_send_json_success([
                'update_available' => true,
                'current_version' => USCDN_VERSION,
                'new_version' => $remote->version,
                'message' => 'Update available! Version ' . $remote->version . ' is ready to install.',
                'plugins_url' => admin_url('plugins.php')
            ]);
        } else {
            wp_send_json_success([
                'update_available' => false,
                'current_version' => USCDN_VERSION,
                'message' => 'You are using the latest version (v' . USCDN_VERSION . ')'
            ]);
        }
    }
}

// Initialize
USCDN_Update_Ajax::init();
