<?php
/**
 * Controlled AYSA plugin updater for private download.aysa.ai releases.
 *
 * This updater is intentionally excluded from the WordPress.org package.
 */

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

class Aysa_Updater {
    private static $metadata_cache = array();

    private $plugin_file;
    private $plugin_basename;
    private $plugin_slug;
    private $version;
    private $update_url;

    public function __construct($plugin_file, $update_url = '') {
        $this->plugin_file = $plugin_file;
        $this->plugin_basename = plugin_basename($plugin_file);
        $this->plugin_slug = dirname($this->plugin_basename);
        $this->version = defined('AYSA_VERSION') ? AYSA_VERSION : '0.0.0';
        $this->update_url = $update_url !== '' ? $update_url : $this->default_update_url();

        add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_update'));
        add_filter('site_transient_update_plugins', array($this, 'check_for_update'));
        add_filter('plugins_api', array($this, 'plugin_information'), 10, 3);
    }

    public function check_for_update($transient) {
        if (!is_object($transient) || empty($transient->checked) || !isset($transient->checked[$this->plugin_basename])) {
            return $transient;
        }

        $remote = $this->fetch_remote_metadata();
        if (!$remote || empty($remote->new_version) || empty($remote->package)) {
            return $transient;
        }

        if (version_compare($this->version, (string) $remote->new_version, '<')) {
            $transient->response[$this->plugin_basename] = (object) array(
                'id' => $this->plugin_basename,
                'slug' => $this->plugin_slug,
                'plugin' => $this->plugin_basename,
                'new_version' => (string) $remote->new_version,
                'url' => isset($remote->homepage) ? esc_url_raw((string) $remote->homepage) : 'https://aysa.ai',
                'package' => esc_url_raw((string) $remote->package),
                'tested' => isset($remote->tested) ? (string) $remote->tested : '',
                'requires' => isset($remote->requires) ? (string) $remote->requires : '',
                'requires_php' => isset($remote->requires_php) ? (string) $remote->requires_php : '',
                'icons' => array(),
                'banners' => array(),
            );
        }

        return $transient;
    }

    public function plugin_information($result, $action, $args) {
        if ($action !== 'plugin_information' || empty($args->slug) || (string) $args->slug !== $this->plugin_slug) {
            return $result;
        }

        $remote = $this->fetch_remote_metadata();
        if (!$remote) {
            return $result;
        }

        return (object) array(
            'name' => isset($remote->name) ? (string) $remote->name : 'AI SEO Automation - AYSA',
            'slug' => $this->plugin_slug,
            'version' => isset($remote->new_version) ? (string) $remote->new_version : $this->version,
            'author' => isset($remote->author) ? (string) $remote->author : 'Aysa.ai',
            'author_profile' => isset($remote->author_homepage) ? esc_url_raw((string) $remote->author_homepage) : 'https://aysa.ai',
            'homepage' => isset($remote->homepage) ? esc_url_raw((string) $remote->homepage) : 'https://aysa.ai',
            'requires' => isset($remote->requires) ? (string) $remote->requires : '',
            'requires_php' => isset($remote->requires_php) ? (string) $remote->requires_php : '',
            'tested' => isset($remote->tested) ? (string) $remote->tested : '',
            'last_updated' => isset($remote->last_updated) ? (string) $remote->last_updated : '',
            'download_link' => isset($remote->package) ? esc_url_raw((string) $remote->package) : '',
            'sections' => isset($remote->sections) && is_object($remote->sections) ? (array) $remote->sections : array(
                'description' => 'AYSA controlled release updates.',
                'changelog' => isset($remote->release_notes) ? wp_kses_post((string) $remote->release_notes) : '',
            ),
        );
    }

    private function fetch_remote_metadata() {
        global $wp_version;

        $cache_key = 'aysa_update_' . md5($this->update_url . '|' . $this->plugin_slug . '|' . $this->version);
        if (isset(self::$metadata_cache[$cache_key])) {
            return self::$metadata_cache[$cache_key];
        }

        $cached = get_site_transient($cache_key);
        if (is_object($cached)) {
            self::$metadata_cache[$cache_key] = $cached;
            return $cached;
        }

        $body = wp_json_encode(array(
            'slug' => $this->plugin_slug,
            'version' => $this->version,
            'site_url' => get_site_url(),
            'wp_version' => isset($wp_version) ? (string) $wp_version : '',
            'php_version' => PHP_VERSION,
        ));

        if (!is_string($body)) {
            return false;
        }

        $response = wp_remote_post($this->update_url, array(
            'timeout' => 15,
            'redirection' => 2,
            'headers' => array(
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ),
            'body' => $body,
        ));

        if (is_wp_error($response) || (int) wp_remote_retrieve_response_code($response) !== 200) {
            return false;
        }

        $decoded = json_decode((string) wp_remote_retrieve_body($response));
        if (!is_object($decoded) || empty($decoded->ok)) {
            return false;
        }

        self::$metadata_cache[$cache_key] = $decoded;
        set_site_transient($cache_key, $decoded, 5 * MINUTE_IN_SECONDS);

        return $decoded;
    }

    private function default_update_url() {
        if (defined('AYSA_UPDATE_CHECK_URL') && is_string(AYSA_UPDATE_CHECK_URL) && trim(AYSA_UPDATE_CHECK_URL) !== '') {
            return esc_url_raw((string) AYSA_UPDATE_CHECK_URL);
        }

        return 'https://download.aysa.ai/wp-update/check.php';
    }
}
