<?php
if (!defined('ABSPATH')) { exit; }

class WAE_Updater {
    const CACHE_KEY = 'wae_update_info_cache';

    public static function init() {
        add_filter('pre_set_site_transient_update_plugins', array(__CLASS__, 'check_for_update'));
        add_filter('plugins_api', array(__CLASS__, 'plugins_api'), 10, 3);
        add_filter('auto_update_plugin', array(__CLASS__, 'allow_auto_update'), 10, 2);
        add_action('wae_daily_update_check', array(__CLASS__, 'scheduled_update_check'));
        if (!wp_next_scheduled('wae_daily_update_check')) { wp_schedule_event(time() + HOUR_IN_SECONDS, 'daily', 'wae_daily_update_check'); }
    }

    private static function options() {
        $defaults = array(
            'core_api_base' => 'https://rent-a-pastor.com/wp-json/rentapastor/v1',
            'auto_updates_enabled' => '0',
            'update_channel' => 'stable'
        );
        $o = get_option('wae_options', array());
        return wp_parse_args(is_array($o) ? $o : array(), $defaults);
    }

    private static function update_info($force = false) {
        if (!$force) {
            $cached = get_transient(self::CACHE_KEY);
            if (is_array($cached)) { return $cached; }
        }
        $o = self::options();
        $base = !empty($o['core_api_base']) ? untrailingslashit($o['core_api_base']) : 'https://rent-a-pastor.com/wp-json/rentapastor/v1';
        $url = add_query_arg(array(
            'plugin' => 'wedding-ai-engine-event-locations',
            'version' => WAE_VERSION,
            'site' => rawurlencode(home_url('/')),
            'channel' => isset($o['update_channel']) ? sanitize_key($o['update_channel']) : 'stable'
        ), $base . '/partner-plugin/update-check');
        $res = wp_remote_get($url, array('timeout'=>8));
        if (is_wp_error($res)) { return array(); }
        $body = json_decode((string) wp_remote_retrieve_body($res), true);
        if (!is_array($body) || empty($body['success'])) { return array(); }
        set_transient(self::CACHE_KEY, $body, DAY_IN_SECONDS);
        return $body;
    }

    public static function check_for_update($transient) {
        if (!is_object($transient)) { return $transient; }
        $plugin_file = plugin_basename(WAE_PLUGIN_FILE);
        $info = self::update_info(false);
        if (empty($info['latest_version']) || empty($info['download_url'])) { return $transient; }
        if (!version_compare($info['latest_version'], WAE_VERSION, '>')) { return $transient; }
        $obj = new stdClass();
        $obj->slug = 'wedding-ai-engine';
        $obj->plugin = $plugin_file;
        $obj->new_version = sanitize_text_field($info['latest_version']);
        $obj->url = 'https://rent-a-pastor.com/';
        $obj->package = esc_url_raw($info['download_url']);
        $obj->tested = isset($info['tested']) ? sanitize_text_field($info['tested']) : '';
        $obj->requires = isset($info['requires_wp']) ? sanitize_text_field($info['requires_wp']) : '6.0';
        $obj->requires_php = isset($info['requires_php']) ? sanitize_text_field($info['requires_php']) : '7.4';
        $transient->response[$plugin_file] = $obj;
        return $transient;
    }

    public static function plugins_api($result, $action, $args) {
        if ($action !== 'plugin_information' || empty($args->slug) || $args->slug !== 'wedding-ai-engine') { return $result; }
        $info = self::update_info(true);
        $obj = new stdClass();
        $obj->name = 'Wedding AI Engine';
        $obj->slug = 'wedding-ai-engine';
        $obj->version = isset($info['latest_version']) ? sanitize_text_field($info['latest_version']) : WAE_VERSION;
        $obj->author = 'Wedding AI Engine / Rent-a-Pastor';
        $obj->homepage = 'https://rent-a-pastor.com/';
        $obj->requires = isset($info['requires_wp']) ? sanitize_text_field($info['requires_wp']) : '6.0';
        $obj->requires_php = isset($info['requires_php']) ? sanitize_text_field($info['requires_php']) : '7.4';
        $obj->sections = array(
            'description' => 'Wedding AI Engine optimiert Eventlocation-Websites für strukturierte Daten, KI-Lesbarkeit und optionale Trauredner-Services.',
            'changelog' => isset($info['changelog']) ? wp_kses_post($info['changelog']) : 'Keine Änderungsinformationen verfügbar.'
        );
        if (!empty($info['download_url'])) { $obj->download_link = esc_url_raw($info['download_url']); }
        return $obj;
    }

    public static function scheduled_update_check() {
        self::update_info(true);
    }

    public static function allow_auto_update($update, $item) {
        if (empty($item->plugin) || $item->plugin !== plugin_basename(WAE_PLUGIN_FILE)) { return $update; }
        $o = self::options();
        return !empty($o['auto_updates_enabled']) && $o['auto_updates_enabled'] === '1';
    }
}
