<?php
/**
 * WP Multi – Modul: Admin-Dashboard Update-Anzeige
 *
 * Automatisch aus wp-multi.php ausgelagert. Wird über den Loader in
 * wp-multi.php eingebunden (nur wenn das WP Multi Toolkit aktiv ist).
 */

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

/*
 * Admin Dashboard Update-Anzeige
 */

define('WP_MULTI_UPDATE_REPO', 'wp-multi');
define('WP_MULTI_UPDATE_CACHE_KEY', 'wp_multi_latest_release');
define('WP_MULTI_UPDATE_HOST', 'git.viper.ipv64.net');

// Fragt den Gitea-Server nach dem neuesten Release ab (gecached via Transient)
function wp_multi_get_latest_release() {
    $cached = get_transient(WP_MULTI_UPDATE_CACHE_KEY);
    if ($cached !== false) {
        return $cached;
    }

    $api_url = 'https://' . WP_MULTI_UPDATE_HOST . '/api/v1/repos/M_Viper/' . WP_MULTI_UPDATE_REPO . '/releases';
    $response = wp_remote_get($api_url, array(
        'timeout' => 10,
        'headers' => array('Accept' => 'application/json'),
    ));

    if (is_wp_error($response)) {
        // Kurz erneut versuchen statt für 12 Stunden zu sperren
        set_transient(WP_MULTI_UPDATE_CACHE_KEY, false, HOUR_IN_SECONDS);
        return false;
    }

    $body = wp_remote_retrieve_body($response);
    $releases = json_decode($body, true);

    if (empty($releases) || !is_array($releases)) {
        set_transient(WP_MULTI_UPDATE_CACHE_KEY, false, HOUR_IN_SECONDS);
        return false;
    }

    usort($releases, function ($a, $b) {
        $a_date = !empty($a['created_at']) ? $a['created_at'] : '';
        $b_date = !empty($b['created_at']) ? $b['created_at'] : '';
        return strtotime($b_date) - strtotime($a_date);
    });

    $latest = false;
    foreach ($releases as $release) {
        if (!empty($release['prerelease'])) {
            continue;
        }
        if (!empty($release['tag_name'])) {
            // Nur Download-URLs auf dem erwarteten Host akzeptieren
            $html_url = !empty($release['html_url']) ? $release['html_url'] : '';
            $release_host = $html_url ? wp_parse_url($html_url, PHP_URL_HOST) : '';
            $latest = array(
                'version' => ltrim($release['tag_name'], 'v'),
                'url'     => ($release_host === WP_MULTI_UPDATE_HOST)
                    ? esc_url_raw($html_url)
                    : 'https://' . WP_MULTI_UPDATE_HOST . '/M_Viper/' . WP_MULTI_UPDATE_REPO . '/releases',
            );
            break;
        }
    }

    set_transient(WP_MULTI_UPDATE_CACHE_KEY, $latest, 12 * HOUR_IN_SECONDS);
    return $latest;
}

// Liest die installierte Version aus dem Plugin-Header
function wp_multi_get_installed_version() {
    if (!function_exists('get_plugin_data')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }
    $data = get_plugin_data(WP_MULTI_FILE, false, false);
    return !empty($data['Version']) ? $data['Version'] : '0';
}

// Dashboard-Widget registrieren
function wp_multi_add_update_dashboard_widget() {
    wp_add_dashboard_widget(
        'wp_multi_update_widget',
        __('WP Multi - Update-Status', 'wp-multi'),
        'wp_multi_update_dashboard_widget_content'
    );
}
add_action('wp_dashboard_setup', 'wp_multi_add_update_dashboard_widget');

// Zeigt im Dashboard-Widget an, ob WP Multi aktuell ist oder ein Update verfügbar ist
function wp_multi_update_dashboard_widget_content() {
    $installed_version = wp_multi_get_installed_version();
    $latest = wp_multi_get_latest_release();

    echo '<p><strong>' . esc_html__('Installierte Version:', 'wp-multi') . '</strong> ' . esc_html($installed_version) . '</p>';

    if (!$latest || empty($latest['version'])) {
        echo '<p>' . esc_html__('Der Update-Server konnte nicht erreicht werden.', 'wp-multi') . '</p>';
        return;
    }

    if (version_compare($latest['version'], $installed_version, '>')) {
        echo '<p style="color:#dc3545;"><strong>' . esc_html__('Update verfügbar:', 'wp-multi') . '</strong> ' . esc_html($latest['version']) . '</p>';
        echo '<p><a href="' . esc_url($latest['url']) . '" target="_blank" class="button button-primary">' . esc_html__('Update herunterladen', 'wp-multi') . '</a></p>';
    } else {
        echo '<p style="color:#28a745;"><strong>' . esc_html__('WP Multi ist aktuell.', 'wp-multi') . '</strong></p>';
    }
}

// Admin-Hinweis anzeigen, wenn ein Update verfügbar ist
function wp_multi_update_admin_notice() {
    if (!current_user_can('manage_options') || !is_admin()) {
        return;
    }

    $installed_version = wp_multi_get_installed_version();
    $latest = wp_multi_get_latest_release();

    if (!$latest || empty($latest['version'])) {
        return;
    }

    if (version_compare($latest['version'], $installed_version, '>')) {
        printf(
            '<div class="notice notice-warning is-dismissible"><p>%1$s <a href="%2$s" target="_blank">%3$s</a></p></div>',
            sprintf(
                esc_html__('Für "WP Multi" ist ein Update verfügbar: Version %1$s (installiert: %2$s).', 'wp-multi'),
                esc_html($latest['version']),
                esc_html($installed_version)
            ),
            esc_url($latest['url']),
            esc_html__('Jetzt herunterladen', 'wp-multi')
        );
    }
}
add_action('admin_notices', 'wp_multi_update_admin_notice');


