<?php
/**
 * Plugin Auto-Updater
 * Checks for updates from remote server and enables one-click updates
 */

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

class USCDN_Updater {
    
    private $plugin_slug;
    private $plugin_file;
    private $version;
    private $update_url;
    private $cache_key;
    private $cache_allowed;
    
    public function __construct($plugin_file, $update_url) {
        $this->plugin_file = $plugin_file;
        $this->plugin_slug = plugin_basename($plugin_file);
        $this->version = USCDN_VERSION;
        $this->update_url = $update_url;
        $this->cache_key = 'uscdn_update_check';
        $this->cache_allowed = true;
        
        add_filter('pre_set_site_transient_update_plugins', [$this, 'check_for_update']);
        add_filter('plugins_api', [$this, 'plugin_info'], 20, 3);
        add_filter('upgrader_pre_download', [$this, 'maybe_deactivate_plugin'], 10, 3);
        add_filter('upgrader_post_install', [$this, 'after_install'], 10, 3);
    }
    
    /**
     * Check for plugin updates
     */
    public function check_for_update($transient) {
        if (empty($transient->checked)) {
            return $transient;
        }
        
        // Get update info
        $remote = $this->request();
        
        if ($remote && version_compare($this->version, $remote->version, '<') && version_compare($remote->requires, get_bloginfo('version'), '<=')) {
            $res = new stdClass();
            $res->slug = dirname($this->plugin_slug);
            $res->plugin = $this->plugin_slug;
            $res->new_version = $remote->version;
            $res->tested = $remote->tested;
            $res->package = $remote->download_url;
            $res->url = $remote->homepage;
            $res->icons = $remote->icons ?? [];
            $res->banners = $remote->banners ?? [];
            
            $transient->response[$this->plugin_slug] = $res;
        }
        
        return $transient;
    }
    
    /**
     * Get plugin info for update screen
     */
    public function plugin_info($response, $action, $args) {
        // Only for our plugin
        if ($action !== 'plugin_information' || $args->slug !== dirname($this->plugin_slug)) {
            return $response;
        }
        
        $remote = $this->request();
        
        if (!$remote) {
            return $response;
        }
        
        $res = new stdClass();
        $res->name = $remote->name;
        $res->slug = dirname($this->plugin_slug);
        $res->version = $remote->version;
        $res->tested = $remote->tested;
        $res->requires = $remote->requires;
        $res->author = $remote->author;
        $res->author_profile = $remote->author_profile ?? '';
        $res->download_link = $remote->download_url;
        $res->trunk = $remote->download_url;
        $res->requires_php = $remote->requires_php ?? '7.4';
        $res->last_updated = $remote->last_updated ?? date('Y-m-d H:i:s');
        $res->sections = [
            'description' => $remote->sections->description ?? '',
            'installation' => $remote->sections->installation ?? '',
            'changelog' => $remote->sections->changelog ?? ''
        ];
        
        if (!empty($remote->banners)) {
            $res->banners = $remote->banners;
        }
        
        if (!empty($remote->icons)) {
            $res->icons = $remote->icons;
        }
        
        return $res;
    }
    
    /**
     * Request update information from remote server
     */
    private function request() {
        // Check cache first
        $remote = get_transient($this->cache_key);
        
        if ($remote !== false && $this->cache_allowed) {
            return $remote;
        }
        
        // Fetch from remote
        $response = wp_remote_get(
            $this->update_url,
            [
                'timeout' => 10,
                'headers' => [
                    'Accept' => 'application/json'
                ]
            ]
        );
        
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) != 200) {
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $remote = json_decode($body);
        
        if (!$remote || !isset($remote->version)) {
            return false;
        }
        
        // Cache for 12 hours
        set_transient($this->cache_key, $remote, 12 * HOUR_IN_SECONDS);
        
        return $remote;
    }
    
    /**
     * Clear update cache
     */
    public function clear_cache() {
        delete_transient($this->cache_key);
    }
    
    /**
     * Force check for updates (for manual button)
     */
    public function force_check() {
        $this->cache_allowed = false;
        $this->clear_cache();
        delete_site_transient('update_plugins');
        
        // Trigger WordPress to check for updates
        wp_update_plugins();
        
        return $this->request();
    }
    
    /**
     * Deactivate plugin before update
     */
    public function maybe_deactivate_plugin($return, $package, $upgrader) {
        if (isset($upgrader->skin->plugin) && $upgrader->skin->plugin === $this->plugin_slug) {
            deactivate_plugins($this->plugin_slug);
        }
        return $return;
    }
    
    /**
     * After update installation
     */
    public function after_install($response, $hook_extra, $result) {
        global $wp_filesystem;
        
        // Get plugin directory
        $plugin_folder = WP_PLUGIN_DIR . '/' . dirname($this->plugin_slug);
        $wp_filesystem->move($result['destination'], $plugin_folder);
        $result['destination'] = $plugin_folder;
        
        // Reactivate plugin
        activate_plugin($this->plugin_slug);
        
        return $result;
    }
}
