<?php
/**
 * FajaedeSEO Auto Updater
 * Handles automatic plugin updates via a custom endpoint.
 */

defined('ABSPATH') or exit;

class FajaedeSEO_Updater {
    /**
     * @var string
     */
    private $plugin_slug;
    
    /**
     * @var string
     */
    private $version;
    
    /**
     * @var string
     */
    private $update_api_url;

    public function __construct(string $plugin_slug, string $version, string $update_api_url) {
        $this->plugin_slug = $plugin_slug;
        $this->version = $version;
        $this->update_api_url = $update_api_url;

        // Haak in op de WordPress update checks
        // phpcs:ignore -- Premium plugins outside of WordPress.org require custom updaters.
        add_filter('pre_set_site_transient_update_plugins', [$this, 'check_update']);
        add_filter('plugins_api', [$this, 'plugin_info'], 10, 3);
    }

    /**
     * @param object|false $transient
     * @return object|false
     */
    public function check_update($transient) {
        if (empty($transient->checked)) {
            return $transient;
        }

        // Vraag onze eigen server om update data
        $remote = $this->request_api('update_check');

        // Als er een nieuwere versie is, vertel dit aan WordPress
        if ($remote && version_compare($this->version, $remote->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; // De .zip link
            $res->url = $remote->homepage ?? 'https://www.fajaede.nl';

            $transient->response[$this->plugin_slug] = $res;
        } else {
            // Als de plugin up-to-date is, verwijder dan de spook-melding uit de WordPress cache
            if (isset($transient->response[$this->plugin_slug])) {
                unset($transient->response[$this->plugin_slug]);
            }
        }

        return $transient;
    }

    /**
     * @param false|object|array $false
     * @param string $action
     * @param object|array $args
     * @return false|object
     */
    public function plugin_info($false, string $action, $args) {
        $plugin_slug_only = dirname($this->plugin_slug);
        if ($action !== 'plugin_information' || !isset($args->slug) || $args->slug !== $plugin_slug_only) {
            return $false;
        }

        // Haal plugin changelog / details op voor de 'Bekijk details' popup
        $remote = $this->request_api('plugin_info');
        if (!$remote) {
            return $false;
        }

        $res = new stdClass();
        $res->name = $remote->name ?? 'FajaedeSEO AI';
        $res->slug = $plugin_slug_only;
        $res->version = $remote->version;
        $res->tested = $remote->tested ?? '';
        $res->requires = $remote->requires ?? '';
        $res->requires_php = $remote->requires_php ?? '';
        $res->author = 'fajaede';
        $res->author_profile = 'https://www.fajaede.nl';
        $res->download_link = $remote->download_url;
        $res->trunk = $remote->download_url;
        $res->last_updated = $remote->last_updated ?? '';
        
        $res->sections = [
            'description' => $remote->sections->description ?? 'The Privacy-first AI SEO Automation Platform.',
            'changelog' => $remote->sections->changelog ?? 'No changelog provided.'
        ];

        return $res;
    }

    /**
     * @param string $action
     * @return object|false
     */
    private function request_api(string $action) {
        // We sturen de licentie mee, zodat je API kan bepalen of ze de .zip mogen downloaden!
        $license_key = get_option('fajaedeseo_pro_license_key', '');
        
        $url = add_query_arg([
            'action' => $action,
            'license' => urlencode($license_key),
            'domain' => urlencode(home_url())
        ], $this->update_api_url);

        $request = wp_remote_get($url, ['timeout' => 10, 'sslverify' => true]);
        if (is_wp_error($request) || wp_remote_retrieve_response_code($request) !== 200) {
            return false;
        }

        $response = json_decode(wp_remote_retrieve_body($request));
        return $response ?: false;
    }
}