<?php

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// === THEME VERSION AUTOMATISCH AUS style.css LADEN (PARENT THEME PRIORITÄT) ===
function minecraft_modern_get_theme_version() {
    // Holt das aktuell aktive Theme (child oder parent)
    $theme = wp_get_theme();

    // Wenn ein Child-Theme aktiv ist und ein Parent vorhanden ist, nutze die Parent-Version
    $parent = $theme->parent();
    if ( $parent && $parent->exists() ) {
        $parent_version = $parent->get( 'Version' );
        if ( ! empty( $parent_version ) ) {
            return $parent_version;
        }
    }

    // Fallback: Version des aktuell aktiven Themes (wenn kein Parent existiert oder Parent keine Version hat)
    return $theme->get( 'Version' );
}

// === THEME UPDATE NOTIFICATION SYSTEM ===

// Funktion zum Leeren des Caches (wenn man auf "Update prüfen" klickt)
function minecraft_modern_clear_cache() {
    if ( isset( $_GET['mm_clear_cache'] ) && current_user_can( 'manage_options' ) ) {
        check_admin_referer( 'mm_clear_cache_action' );
        delete_transient( 'minecraft_modern_latest_release' );
        wp_redirect( admin_url( 'index.php' ) );
        exit;
    }
}
add_action( 'admin_init', 'minecraft_modern_clear_cache' );

// Funktion zum Abrufen der neuesten Release-Informationen
function minecraft_modern_get_latest_release_info( $force_refresh = false ) {
    $transient_key = 'minecraft_modern_latest_release';
    
    // Wenn erzwungen wird (oder Cache leer), frische Daten holen
    if ( $force_refresh ) {
        delete_transient( $transient_key );
    }
    
    $release_info = get_transient( $transient_key );
    
    if ( false === $release_info ) {
        // Timeout auf 10 Sekunden erhöht für langsame Verbindungen
        $response = wp_remote_get(
            'https://git.viper.ipv64.net/api/v1/repos/M_Viper/Minecraft-Modern-Theme/releases/latest',
            array( 'timeout' => 10 )
        );
        
        if ( ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response ) ) {
            $body = wp_remote_retrieve_body( $response );
            $release_data = json_decode( $body, true );
            
            if ( $release_data && isset( $release_data['tag_name'] ) ) {
                // Tag bereinigen (falls 'v' davor steht, z.B. v1.6 -> 1.6)
                $tag_name = $release_data['tag_name'];
                if ( strpos( $tag_name, 'v' ) === 0 ) {
                    $tag_name = ltrim( $tag_name, 'v' );
                }

                $release_info = array(
                    'version'       => $tag_name,
                    'download_url'  => $release_data['zipball_url'],
                    'release_notes' => isset( $release_data['body'] ) ? $release_data['body'] : '',
                    'published_at'  => isset( $release_data['published_at'] ) ? $release_data['published_at'] : ''
                );
                
                // Cache für 6 Stunden
                set_transient( $transient_key, $release_info, 6 * HOUR_IN_SECONDS );
            } else {
                // Fehlerhafte Daten leer cachen
                set_transient( $transient_key, array(), HOUR_IN_SECONDS );
            }
        } else {
            // Fehler beim Abrufen
            set_transient( $transient_key, array(), HOUR_IN_SECONDS );
        }
    }
    
    return $release_info;
}

// === BENACHRICHTIGUNG IM ADMIN-BEREICH ===
function minecraft_modern_show_update_notification() {
    if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
        return;
    }
    
    $current_version = minecraft_modern_get_theme_version();
    $latest_release  = minecraft_modern_get_latest_release_info();
    
    if ( ! empty( $latest_release ) && isset( $latest_release['version'] ) && version_compare( $current_version, $latest_release['version'], '<' ) ) {
        ?>
        <div class="notice notice-warning is-dismissible">
            <h3><?php _e( 'Minecraft Modern Theme Update Available', 'minecraft-modern-theme' ); ?></h3>
            <p>
                <?php 
                printf(
                    __( 'You are using version %1$s of the Minecraft Modern Theme. Version %2$s is now available.', 'minecraft-modern-theme' ),
                    '<strong>' . esc_html( $current_version ) . '</strong>',
                    '<strong>' . esc_html( $latest_release['version'] ) . '</strong>'
                );
                ?>
            </p>
            <p>
                <a href="<?php echo esc_url( $latest_release['download_url'] ); ?>" class="button button-primary" target="_blank">
                    <?php _e( 'Download Latest Version', 'minecraft-modern-theme' ); ?>
                </a>
                <a href="https://git.viper.ipv64.net/M_Viper/Minecraft-Modern-Theme/releases" class="button" target="_blank">
                    <?php _e( 'View Release Notes', 'minecraft-modern-theme' ); ?>
                </a>
            </p>
        </div>
        <?php
    }
}
add_action( 'admin_notices', 'minecraft_modern_show_update_notification' );

// === DASHBOARD WIDGET ===
function minecraft_modern_add_dashboard_widget() {
    wp_add_dashboard_widget(
        'minecraft_modern_update_widget',
        'Minecraft Modern Theme Status',
        'minecraft_modern_update_widget_function'
    );
}
add_action( 'wp_dashboard_setup', 'minecraft_modern_add_dashboard_widget' );

function minecraft_modern_update_widget_function() {
    $current_version = minecraft_modern_get_theme_version();
    $latest_release  = minecraft_modern_get_latest_release_info();
    
    echo '<p><strong>' . __( 'Current Version:', 'minecraft-modern-theme' ) . '</strong> ' . esc_html( $current_version ) . '</p>';
    
    if ( ! empty( $latest_release ) && isset( $latest_release['version'] ) ) {
        echo '<p><strong>' . __( 'Latest Version:', 'minecraft-modern-theme' ) . '</strong> ' . esc_html( $latest_release['version'] ) . '</p>';
        
        if ( version_compare( $current_version, $latest_release['version'], '<' ) ) {
            echo '<p><strong>' . __( 'Status:', 'minecraft-modern-theme' ) . '</strong> <span style="color:#d63638;">' . __( 'Update Available', 'minecraft-modern-theme' ) . '</span></p>';
            echo '<p><a href="' . esc_url( $latest_release['download_url'] ) . '" class="button button-primary" target="_blank">' . __( 'Download Update', 'minecraft-modern-theme' ) . '</a></p>';
        } else {
            echo '<p><strong>' . __( 'Status:', 'minecraft-modern-theme' ) . '</strong> <span style="color:#46b450;">' . __( 'Up to Date', 'minecraft-modern-theme' ) . '</span></p>';
        }
    } else {
        echo '<p><strong>' . __( 'Status:', 'minecraft-modern-theme' ) . '</strong> ' . __( 'Unable to check for updates', 'minecraft-modern-theme' ) . '</p>';
    }
    
    // Link für "Jetzt prüfen"
    $refresh_url = wp_nonce_url( admin_url( 'index.php?mm_clear_cache=1' ), 'mm_clear_cache_action' );
    echo '<p><a href="' . esc_url( $refresh_url ) . '" onclick="return confirm(\'Cache leeren und neu prüfen?\');">' . __( 'Check for Updates Now', 'minecraft-modern-theme' ) . '</a></p>';
    
    echo '<p><a href="https://git.viper.ipv64.net/M_Viper/Minecraft-Modern-Theme/releases" target="_blank">' . __( 'View All Releases', 'minecraft-modern-theme' ) . '</a></p>';
}
