<?php 

class Updater {

    public static function init(): void {
        add_filter('pre_set_site_transient_update_plugins', [self::class, 'checkUpdates']);
        add_filter('plugins_api', [self::class, 'pluginsApi'], 10, 3);
    }

    public static function checkUpdates($transient) {
        if (empty($transient->checked)) return $transient;

        $plugin_file = ZODDAK_PLUGIN_BASENAME;
        $current_version = $transient->checked[$plugin_file] ?? null;
        if (!$current_version) return $transient;

        $host = parse_url(home_url(), PHP_URL_HOST);
        $is_local =
            in_array($host, ['localhost', '127.0.0.1', 'wordpress.local'], true) ||
            (function_exists('str_ends_with') && (str_ends_with($host, '.test') || str_ends_with($host, '.local')));

        $base_url = $is_local ? ZODDAK_UPDATES_URL_DEV_ENV : ZODDAK_UPDATES_URL_PROD_ENV;

        $request_url = add_query_arg([
            'slug' => ZODDAK_PLUGIN_SLUG,
            'current' => $current_version,
            'domain' => $host,
        ], $base_url);

        $response = wp_remote_get($request_url, ['timeout' => 10, 'headers' => ['Accept' => 'application/json']]);
        $code = wp_remote_retrieve_response_code($response);
        if (is_wp_error($response) || $code !== 200) return $transient;

        $data = json_decode(wp_remote_retrieve_body($response));
        $release = $data->data ?? null;
        if (empty($release->version) || empty($release->zip_path)) return $transient;

        if (version_compare($release->version, $current_version, '>')) {
            $transient->response[$plugin_file] = (object) [
                'slug'        => ZODDAK_PLUGIN_SLUG,
                'plugin'      => $plugin_file,
                'new_version' => $release->version,
                'url'         => $release->plugin_uri ?? '',
                'package'     => $release->zip_path,
            ];
        }

        return $transient;
    }

    public static function pluginsApi($result, $action, $args) {
        if ($action !== 'plugin_information') return $result;
        if (empty($args->slug) || $args->slug !== ZODDAK_PLUGIN_SLUG) return $result;

        $host = parse_url(home_url(), PHP_URL_HOST);
        $is_local =
            in_array($host, ['localhost', '127.0.0.1', 'wordpress.local'], true) ||
            (function_exists('str_ends_with') && str_ends_with($host, '.local'));

        $base_url = $is_local ? ZODDAK_UPDATES_URL_DEV_ENV : ZODDAK_UPDATES_URL_PROD_ENV;

        $request_url = add_query_arg(['slug' => ZODDAK_PLUGIN_SLUG], $base_url);

        $response = wp_remote_get($request_url, ['timeout' => 10, 'headers' => ['Accept' => 'application/json']]);
        $code = wp_remote_retrieve_response_code($response);
        if (is_wp_error($response) || $code !== 200) return $result;

        $data = json_decode(wp_remote_retrieve_body($response));
        if (!$data || empty($data->success) || empty($data->data)) return $result;

        $release = $data->data;

        $desc = $release->description ?? 'Actualización privada.';
        $items = array_map('esc_html', (array) ($release->changelog ?? []));
        $changelog_html = $items
            ? '<ul><li>' . implode('</li><li>', $items) . '</li></ul>'
            : '<p>No hay changelog.</p>';

        return (object) [
            'name'          => $release->name ?? 'Zoddak Resales',
            'slug'          => ZODDAK_PLUGIN_SLUG,
            'version'       => (string) ($release->version ?? ''),
            'author'        => $release->author ?? 'Zoddak',
            'author_profile'=> $release->author_uri ?? '',
            'homepage'      => $release->plugin_uri ?? '',
            'sections'      => [
                'description' => wp_kses_post('<p>' . esc_html($desc) . '</p>'),
                'changelog'   => wp_kses_post($changelog_html),
            ],
        ];
    }
}