<?php
/**
 * NIBRA Auto-Updater for WordPress Plugins
 * Checks productes.nibra.cloud for updates and enables 1-click update from WP admin.
 * 
 * @version 1.0.0
 */
defined('ABSPATH') || exit;

class NIBRA_Updater {

    private string $plugin_slug;
    private string $plugin_file;
    private string $plugin_basename;
    private string $license_key;
    private string $api_url;
    private string $current_version;
    private ?object $update_cache = null;

    public function __construct(array $config) {
        $this->plugin_slug    = $config['plugin_slug']     ?? '';
        $this->plugin_file    = $config['plugin_file']     ?? '';
        $this->plugin_basename = plugin_basename($this->plugin_file);
        $this->license_key    = $config['license_key']     ?? '';
        $this->api_url        = rtrim($config['api_url'] ?? 'https://productes.nibra.cloud', '/');
        $this->current_version = $config['current_version'] ?? '1.0.0';

        if (!$this->plugin_slug || !$this->plugin_file) return;

        // Hook into WordPress update system
        add_filter('pre_set_site_transient_update_plugins', [$this, 'check_for_update']);
        add_filter('plugins_api', [$this, 'plugin_info'], 20, 3);
        add_action('in_plugin_update_message-' . $this->plugin_basename, [$this, 'update_message'], 10, 2);

        // Clear cache on activation/deactivation
        add_action('activate_' . $this->plugin_basename, [$this, 'clear_cache']);
        add_action('deactivate_' . $this->plugin_basename, [$this, 'clear_cache']);
    }

    /**
     * Check the NIBRA server for plugin updates
     */
    public function check_for_update($transient) {
        if (empty($transient->checked)) return $transient;

        $remote = $this->get_remote_version();
        if (!$remote || empty($remote['latest_version'])) return $transient;

        $latest = $remote['latest_version'];

        if (version_compare($this->current_version, $latest, '<')) {
            $plugin_data = [
                'slug'        => $this->plugin_slug,
                'plugin'      => $this->plugin_basename,
                'new_version' => $latest,
                'url'         => $this->api_url . '/product/' . $this->plugin_slug,
                'package'     => $remote['download_url'] ?? '',
                'tested'      => $remote['tested_wp'] ?? '',
                'requires'    => $remote['requires_wp'] ?? '6.0',
                'requires_php'=> $remote['requires_php'] ?? '8.0',
            ];

            // Icons & banners
            if (!empty($remote['icons'])) $plugin_data['icons'] = $remote['icons'];
            if (!empty($remote['banners'])) $plugin_data['banners'] = $remote['banners'];

            $transient->response[$this->plugin_basename] = (object) $plugin_data;
        } else {
            // No update — tell WP we checked
            $transient->no_update[$this->plugin_basename] = (object) [
                'slug'        => $this->plugin_slug,
                'plugin'      => $this->plugin_basename,
                'new_version' => $latest,
                'url'         => $this->api_url . '/product/' . $this->plugin_slug,
            ];
        }

        return $transient;
    }

    /**
     * Provide plugin info for the WordPress "View Details" popup
     */
    public function plugin_info($result, $action, $args) {
        if ($action !== 'plugin_information') return $result;
        if (!isset($args->slug) || $args->slug !== $this->plugin_slug) return $result;

        $remote = $this->get_remote_version();
        if (!$remote) return $result;

        $info = new \stdClass();
        $info->name          = 'DZQCOD — نظام إدارة طلبات COD';
        $info->slug          = $this->plugin_slug;
        $info->version       = $remote['latest_version'] ?? $this->current_version;
        $info->author        = '<a href="https://nibra.cloud">NIBRA Technology</a>';
        $info->author_profile = 'https://nibra.cloud';
        $info->homepage      = $this->api_url . '/product/' . $this->plugin_slug;
        $info->requires      = $remote['requires_wp'] ?? '6.0';
        $info->tested        = $remote['tested_wp'] ?? '';
        $info->requires_php  = $remote['requires_php'] ?? '8.0';
        $info->download_link = $remote['download_url'] ?? '';
        $info->trunk         = $remote['download_url'] ?? '';
        $info->last_updated  = $remote['released_at'] ?? '';

        // Sections
        $info->sections = [];
        if (!empty($remote['sections']['description'])) $info->sections['description'] = $remote['sections']['description'];
        if (!empty($remote['sections']['changelog']))    $info->sections['changelog'] = $remote['sections']['changelog'];
        $info->sections['installation'] = '<p>1. حمّل الملف من متجر NIBRA<br>2. ارفع من ووردبريس ← إضافات ← أضف جديد ← رفع إضافة<br>3. فعّل الإضافة وأكمل معالج الإعداد</p>';

        // Banners & icons
        if (!empty($remote['banners'])) $info->banners = $remote['banners'];
        if (!empty($remote['icons']))   $info->icons = $remote['icons'];

        // Upgrade notice
        if (!empty($remote['upgrade_notice'])) $info->upgrade_notice = $remote['upgrade_notice'];

        return $info;
    }

    /**
     * Show upgrade notice in the plugins list
     */
    public function update_message($plugin_data, $response): void {
        if (!empty($response->upgrade_notice)) {
            echo '<br><span style="display:inline-block;padding:4px 8px;background:#fff3cd;border-radius:4px;font-size:12px;margin-top:4px">⚠️ ' . esc_html($response->upgrade_notice) . '</span>';
        }
    }

    /**
     * Fetch remote version info from NIBRA server (cached 12h)
     */
    private function get_remote_version(): ?array {
        if ($this->update_cache !== null) return (array) $this->update_cache;

        $cache_key = 'nibra_update_' . $this->plugin_slug;
        $cached = get_transient($cache_key);
        if ($cached !== false) {
            $this->update_cache = (object) $cached;
            return $cached;
        }

        $domain = wp_parse_url(home_url(), PHP_URL_HOST) ?: '';
        $url = $this->api_url . '/api/v1/version-check?' . http_build_query([
            'product'         => $this->plugin_slug,
            'key'             => $this->license_key,
            'domain'          => $domain,
            'current_version' => $this->current_version,
        ]);

        $response = wp_remote_get($url, [
            'timeout'   => 15,
            'sslverify' => apply_filters('dzqcod_ssl_verify', true),
            'headers'   => [
                'Accept'         => 'application/json',
                'X-Nibra-Client' => 'DZQCOD/' . $this->current_version,
            ],
        ]);

        if (is_wp_error($response)) return null;

        $code = wp_remote_retrieve_response_code($response);
        if ($code !== 200) return null;

        $data = json_decode(wp_remote_retrieve_body($response), true);
        if (!$data || empty($data['latest_version'])) return null;

        // Cache for 12 hours
        set_transient($cache_key, $data, 12 * HOUR_IN_SECONDS);
        $this->update_cache = (object) $data;

        return $data;
    }

    /**
     * Clear the update cache
     */
    public function clear_cache(): void {
        delete_transient('nibra_update_' . $this->plugin_slug);
        delete_site_transient('update_plugins');
        $this->update_cache = null;
    }
}
