<?php
/**
 * Plugin Updater Class for Simple Appointment Booking
 * 
 * Handles automatic updates from the Mobile-Refuel license server
 * 
 * @package SimpleAppointmentBooking
 * @since 1.1.6
 */

// Sicherheitsmaßnahme: Direkten Zugriff verhindern
if (!defined('ABSPATH')) {
    exit;
}

class SIMPBOOK_Plugin_Updater {
    
    private $plugin_file;
    private $plugin_slug;
    private $version;
    private $api_url;
    private $api_token;
    private $license_key;
    private $cache_key;
    private $cache_duration;
    
    /**
     * Constructor
     */
    public function __construct($plugin_file, $plugin_slug, $version) {
        $this->plugin_file = $plugin_file;
        $this->plugin_slug = $plugin_slug;
        $this->version = $version;
        $this->api_url = 'https://mobile-refuel.de/wp-content/plugins/mobile-refuel-lizenzserver/lizenzen/get_update_info.php';
        $this->api_token = 'aP39F3kLc9x!mZ82';
        $this->license_key = get_option('simpbook_lizenz_key', '');
        $this->cache_key = 'simpbook_update_info_' . $this->plugin_slug;
        $this->cache_duration = 12 * HOUR_IN_SECONDS; // 12 Stunden
        
        // WordPress Update Hooks
        add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_updates'));
        add_filter('plugins_api', array($this, 'plugin_info'), 20, 3);
        add_action('upgrader_process_complete', array($this, 'clear_cache'), 10, 2);
        
        // Admin Hooks
        add_action('admin_init', array($this, 'manual_update_check'));
        add_action('admin_notices', array($this, 'admin_notices'));
    }
    
    /**
     * Check for plugin updates
     */
    public function check_for_updates($transient) {
        if (empty($transient->checked)) {
            return $transient;
        }
        
        // Cache prüfen
        $cached_info = get_transient($this->cache_key);
        if ($cached_info !== false) {
            $update_info = $cached_info;
        } else {
            $update_info = $this->get_update_info();
            if ($update_info) {
                set_transient($this->cache_key, $update_info, $this->cache_duration);
            }
        }

        // Veralteten Cache erkennen: wenn die installierte Version bereits >= der im Cache
        // gespeicherten "neuesten" Version ist, wurde der Cache vor dem Update befüllt.
        // Cache löschen und kein Update an WordPress melden.
        if ($update_info && isset($update_info->latest_version)) {
            if (version_compare($this->version, $update_info->latest_version, '>=')) {
                delete_transient($this->cache_key);
                return $transient;
            }
        }

        // Wenn Update verfügbar, WordPress benachrichtigen
        if ($update_info && isset($update_info->update_available) && $update_info->update_available === true) {
            $plugin_basename = plugin_basename($this->plugin_file);
            
            $update_data = array(
                'slug' => $this->plugin_slug,
                'plugin' => $plugin_basename,
                'new_version' => $update_info->latest_version,
                'url' => 'https://mobile-refuel.de',
                'package' => $update_info->download_url ?? '',
                'tested' => $update_info->tested_wp ?? '6.9',
                'requires_php' => $update_info->requires_php ?? '7.4',
                'icons' => array()
            );
            
            $transient->response[$plugin_basename] = (object) $update_data;
        }
        
        return $transient;
    }
    
    /**
     * Provide plugin information for the update screen
     */
    public function plugin_info($res, $action, $args) {
        if ($action !== 'plugin_information') {
            return $res;
        }
        
        if ($args->slug !== $this->plugin_slug) {
            return $res;
        }
        
        $update_info = get_transient($this->cache_key);
        if (!$update_info) {
            $update_info = $this->get_update_info();
        }
        
        if (!$update_info || !isset($update_info->latest_version)) {
            return $res;
        }
        
        $res = new stdClass();
        $res->name = 'PocketBooking Pro';
        $res->slug = $this->plugin_slug;
        $res->version = $update_info->latest_version;
        $res->tested = $update_info->tested_wp ?? '6.9';
        $res->requires = $update_info->requires_wp ?? '5.0';
        $res->requires_php = $update_info->requires_php ?? '7.4';
        $res->author = '<a href="https://mobile-refuel.de">Mobile-Refuel</a>';
        $res->homepage = 'https://mobile-refuel.de';
        $res->download_link = $update_info->download_url ?? '';
        $res->sections = array(
            'description' => 'Professionelles Terminbuchungs-Plugin mit Mitarbeiterverwaltung und E-Mail-Benachrichtigungen.',
            'changelog' => $update_info->changelog ?? ''
        );
        
        return $res;
    }
    
    /**
     * Get update information from API
     */
    private function get_update_info() {
        $is_trial = (function_exists('simpbook_has_full_access') && simpbook_has_full_access()) ? '1' : '0';
        $request_url = add_query_arg(array(
            'action' => 'get_update_info',
            'plugin_slug' => $this->plugin_slug,
            'current_version' => $this->version,
            'license_key' => $this->license_key,
            'domain' => get_site_url(),
            'token' => $this->api_token,
            'is_trial' => $is_trial
        ), $this->api_url);
        
        $response = wp_remote_get($request_url, array(
            'timeout' => 15,
            'sslverify' => true
        ));
        
        if (is_wp_error($response)) {
            return false;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body);
        
        if (!$data || !isset($data->status) || $data->status !== 'success') {
            return false;
        }
        
        return $data;
    }
    
    /**
     * Clear update cache
     */
    public function clear_cache($upgrader, $options) {
        if ($options['action'] === 'update' && $options['type'] === 'plugin') {
            delete_transient($this->cache_key);
            delete_site_transient('update_plugins');
        }
    }
    
    /**
     * Manual update check handler
     */
    public function manual_update_check() {
        if (isset($_GET['simpbook_check_updates']) && current_user_can('manage_options')) {
            delete_transient($this->cache_key);
            delete_site_transient('update_plugins');
            // No redirect — the settings page renders on the current URL with fresh data.
            // wp_redirect() can fail on some hosts when headers are already sent,
            // which would produce a white page. Rendering inline is more reliable.
        }
    }
    
    /**
     * Show admin notices
     */
    public function admin_notices() {
        if (isset($_GET['simpbook_update_checked']) && current_user_can('manage_options')) {
            echo '<div class="notice notice-success is-dismissible"><p>' . 
                 esc_html__('Update check completed.', 'simple-appointment-booking') . 
                 '</p></div>';
        }
    }
    
    /**
     * Get cached update info (for display purposes).
     * Reads from transient cache; if empty fetches from API and stores result.
     */
    public static function get_cached_update_info() {
        $cache_key = 'simpbook_update_info_' . SIMPBOOK_PLUGIN_SLUG;
        $cached_info = get_transient($cache_key);
        if ($cached_info !== false) {
            return $cached_info;
        }

        if (!is_admin() || !current_user_can('manage_options')) {
            return false;
        }

        $api_url   = 'https://mobile-refuel.de/wp-content/plugins/mobile-refuel-lizenzserver/lizenzen/get_update_info.php';
        $api_token = 'aP39F3kLc9x!mZ82';
        $license_key     = get_option('simpbook_lizenz_key', '');
        $current_version = defined('SIMPBOOK_VERSION') ? SIMPBOOK_VERSION : '1.1.5';
        $is_trial = (function_exists('simpbook_has_full_access') && simpbook_has_full_access()) ? '1' : '0';

        $request_url = add_query_arg(array(
            'action'          => 'get_update_info',
            'plugin_slug'     => SIMPBOOK_PLUGIN_SLUG,
            'current_version' => $current_version,
            'license_key'     => $license_key,
            'domain'          => get_site_url(),
            'token'           => $api_token,
            'is_trial'        => $is_trial,
        ), $api_url);

        $response = wp_remote_get($request_url, array('timeout' => 8, 'sslverify' => true));

        if (!is_wp_error($response)) {
            $data = json_decode(wp_remote_retrieve_body($response));
            if ($data && isset($data->status) && $data->status === 'success') {
                set_transient($cache_key, $data, 12 * HOUR_IN_SECONDS);
                return $data;
            }
        }

        return false;
    }
}
