<?php

/**
 * Dyronics License Manager for MyParcel
 * 
 * This class handles license validation and updates for the MyParcel plugin.
 * It integrates with the Dyronics License Server to verify plugin licenses
 * and enable/disable features based on license status.
 */
class WCMP_License_Manager {
    
    private $license_server = 'https://dyronics.nl';
    private $plugin_slug = 'woocommerce-myparcel';
    private $plugin_version;
    private $option_key = 'wcmp_license_key';
    private $option_data = 'wcmp_license_data';
    
    public function __construct() {
        $this->plugin_version = $this->get_plugin_version();
        add_action('admin_init', array($this, 'init_admin'));
        add_action('admin_menu', array($this, 'add_license_menu'), 99);
        add_action('wp_ajax_wcmp_license_activate', array($this, 'ajax_activate_license'));
        add_action('wp_ajax_wcmp_license_deactivate', array($this, 'ajax_deactivate_license'));
        add_action('wp_ajax_wcmp_send_diagnostics', array($this, 'ajax_send_diagnostics'));
        add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_update'));
        add_filter('plugins_api', array($this, 'plugin_api_call'), 10, 3);
        
        // Report version after plugin update
        add_action('upgrader_process_complete', array($this, 'report_version_after_update'), 10, 2);
    }
    
    /**
     * Add license menu page
     */
    public function add_license_menu() {
        add_submenu_page(
            'woocommerce',
            'MyParcel Licentie & Diagnostics',
            'MyParcel Licentie',
            'manage_options',
            'wcmp-license',
            array($this, 'render_license_page')
        );
    }
    
    /**
     * Render license page
     */
    public function render_license_page() {
        $license_key = get_option($this->option_key, '');
        $license_data = get_option($this->option_data, array());
        $is_valid = !empty($license_data['status']) && $license_data['status'] === 'active';
        
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <div class="wcmp-license-container" style="max-width: 800px;">
                <!-- License Activation Section -->
                <div class="card" style="margin-top: 20px;">
                    <h2>Licentie Activatie</h2>
                    
                    <?php if ($is_valid): ?>
                        <div class="notice notice-success inline">
                            <p><strong>✓ Licentie Actief</strong></p>
                            <p>Domein: <?php echo esc_html($license_data['domain'] ?? get_site_url()); ?></p>
                            <?php if (!empty($license_data['expires'])): ?>
                                <p>Vervalt op: <?php echo esc_html($license_data['expires']); ?></p>
                            <?php endif; ?>
                        </div>
                        
                        <p>
                            <button type="button" class="button button-secondary" id="wcmp-deactivate-license">
                                Licentie Deactiveren
                            </button>
                        </p>
                    <?php else: ?>
                        <div class="notice notice-warning inline">
                            <p>Voer een geldige licentie sleutel in om alle premium functies te gebruiken.</p>
                        </div>
                        
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="wcmp_license_key">Licentie Sleutel</label>
                                </th>
                                <td>
                                    <input type="text" 
                                           id="wcmp_license_key" 
                                           value="<?php echo esc_attr($license_key); ?>" 
                                           class="regular-text"
                                           placeholder="DYR-XXXX-XXXX-XXXX">
                                    <p class="description">
                                        Voer hier je MyParcel premium licentie sleutel in.
                                    </p>
                                </td>
                            </tr>
                        </table>
                        
                        <p>
                            <button type="button" class="button button-primary" id="wcmp-activate-license">
                                Licentie Activeren
                            </button>
                        </p>
                    <?php endif; ?>
                    
                    <div id="wcmp-license-message" style="margin-top: 15px;"></div>
                </div>
                
                <!-- Diagnostics Section -->
                <div class="card" style="margin-top: 20px;">
                    <h2>Diagnostics & Support</h2>
                    
                    <p>Verstuur diagnostische gegevens naar Dyronics support voor troubleshooting.</p>
                    
                    <h3>Systeem Informatie</h3>
                    <table class="widefat">
                        <tbody>
                            <tr>
                                <td><strong>WordPress Versie:</strong></td>
                                <td><?php echo esc_html(get_bloginfo('version')); ?></td>
                            </tr>
                            <tr>
                                <td><strong>WooCommerce Versie:</strong></td>
                                <td><?php echo esc_html(defined('WC_VERSION') ? WC_VERSION : 'Niet geïnstalleerd'); ?></td>
                            </tr>
                            <tr>
                                <td><strong>MyParcel Plugin Versie:</strong></td>
                                <td><?php echo esc_html($this->plugin_version); ?></td>
                            </tr>
                            <tr>
                                <td><strong>PHP Versie:</strong></td>
                                <td><?php echo esc_html(PHP_VERSION); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Site URL:</strong></td>
                                <td><?php echo esc_html(get_site_url()); ?></td>
                            </tr>
                            <tr>
                                <td><strong>Licentie Status:</strong></td>
                                <td><?php echo $is_valid ? '<span style="color: green;">✓ Actief</span>' : '<span style="color: orange;">⚠ Inactief</span>'; ?></td>
                            </tr>
                        </tbody>
                    </table>
                    
                    <p style="margin-top: 20px;">
                        <button type="button" class="button button-secondary" id="wcmp-send-diagnostics">
                            Verstuur Diagnostics naar Support
                        </button>
                    </p>
                    
                    <div id="wcmp-diagnostics-message" style="margin-top: 15px;"></div>
                </div>
            </div>
        </div>
        
        <script type="text/javascript">
        jQuery(document).ready(function($) {
            // Activate License
            $('#wcmp-activate-license').on('click', function() {
                var button = $(this);
                var licenseKey = $('#wcmp_license_key').val();
                var messageDiv = $('#wcmp-license-message');
                
                if (!licenseKey) {
                    messageDiv.html('<div class="notice notice-error inline"><p>Voer een licentie sleutel in.</p></div>');
                    return;
                }
                
                button.prop('disabled', true).text('Bezig met activeren...');
                messageDiv.html('');
                
                $.post(ajaxurl, {
                    action: 'wcmp_license_activate',
                    license_key: licenseKey,
                    nonce: '<?php echo wp_create_nonce('wcmp_license_nonce'); ?>'
                }, function(response) {
                    if (response.success) {
                        messageDiv.html('<div class="notice notice-success inline"><p>' + response.data.message + '</p></div>');
                        setTimeout(function() { location.reload(); }, 1500);
                    } else {
                        messageDiv.html('<div class="notice notice-error inline"><p>' + (response.data.message || 'Activatie mislukt') + '</p></div>');
                        button.prop('disabled', false).text('Licentie Activeren');
                    }
                });
            });
            
            // Deactivate License
            $('#wcmp-deactivate-license').on('click', function() {
                if (!confirm('Weet je zeker dat je de licentie wilt deactiveren?')) {
                    return;
                }
                
                var button = $(this);
                var messageDiv = $('#wcmp-license-message');
                
                button.prop('disabled', true).text('Bezig met deactiveren...');
                
                $.post(ajaxurl, {
                    action: 'wcmp_license_deactivate',
                    nonce: '<?php echo wp_create_nonce('wcmp_license_nonce'); ?>'
                }, function(response) {
                    if (response.success) {
                        messageDiv.html('<div class="notice notice-success inline"><p>' + response.data.message + '</p></div>');
                        setTimeout(function() { location.reload(); }, 1500);
                    } else {
                        messageDiv.html('<div class="notice notice-error inline"><p>' + (response.data.message || 'Deactivatie mislukt') + '</p></div>');
                        button.prop('disabled', false).text('Licentie Deactiveren');
                    }
                });
            });
            
            // Send Diagnostics
            $('#wcmp-send-diagnostics').on('click', function() {
                var button = $(this);
                var messageDiv = $('#wcmp-diagnostics-message');
                
                button.prop('disabled', true).text('Bezig met versturen...');
                messageDiv.html('');
                
                $.post(ajaxurl, {
                    action: 'wcmp_send_diagnostics',
                    nonce: '<?php echo wp_create_nonce('wcmp_diagnostics_nonce'); ?>'
                }, function(response) {
                    if (response.success) {
                        messageDiv.html('<div class="notice notice-success inline"><p>✓ Diagnostische gegevens succesvol verzonden naar Dyronics support.</p></div>');
                    } else {
                        messageDiv.html('<div class="notice notice-error inline"><p>Fout bij het verzenden van diagnostics.</p></div>');
                    }
                    button.prop('disabled', false).text('Verstuur Diagnostics naar Support');
                });
            });
        });
        </script>
        <?php
    }
    
    /**
     * AJAX handler for sending diagnostics
     */
    public function ajax_send_diagnostics() {
        check_ajax_referer('wcmp_diagnostics_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Onvoldoende rechten'));
        }
        
        $result = $this->send_diagnostic_data();
        
        if ($result) {
            wp_send_json_success(array('message' => 'Diagnostics verzonden'));
        } else {
            wp_send_json_error(array('message' => 'Fout bij verzenden'));
        }
    }
    
    /**
     * Get plugin version from main plugin file
     */
    private function get_plugin_version() {
        $plugin_file = dirname(dirname(__FILE__)) . '/woocommerce-myparcel.php';
        
        if (!function_exists('get_plugin_data')) {
            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }
        
        $plugin_data = get_plugin_data($plugin_file);
        return $plugin_data['Version'];
    }
    
    /**
     * Initialize admin functionality
     */
    public function init_admin() {
        if (current_user_can('manage_options')) {
            add_action('admin_notices', array($this, 'show_admin_notices'));
        }
    }
    
    /**
     * Show admin notices for license status
     */
    public function show_admin_notices() {
        if (!$this->is_license_valid()) {
            $license_key = get_option($this->option_key);
            if (empty($license_key)) {
                echo '<div class="notice notice-warning is-dismissible">';
                echo '<p><strong>MyParcel:</strong> Voer een geldige licentie sleutel in om alle functies te gebruiken.</p>';
                echo '</div>';
            } else {
                echo '<div class="notice notice-error is-dismissible">';
                echo '<p><strong>MyParcel:</strong> Uw licentie is niet geldig of verlopen. Neem contact op met support.</p>';
                echo '</div>';
            }
        }
    }
    
    /**
     * Check if license is valid
     */
    public function is_license_valid() {
        $license_data = get_option($this->option_data);
        
        if (empty($license_data) || !isset($license_data['status'])) {
            return false;
        }
        
        // Accept both 'valid' and 'active' as valid status
        return in_array($license_data['status'], array('valid', 'active'));
    }
    
    /**
     * Get license features
     */
    public function get_license_features() {
        $license_data = get_option($this->option_data);
        
        if (empty($license_data) || !isset($license_data['features'])) {
            return array();
        }
        
        return $license_data['features'];
    }
    
    /**
     * Check if feature is enabled
     */
    public function is_feature_enabled($feature) {
        $features = $this->get_license_features();
        return in_array($feature, $features);
    }
    
    /**
     * Activate license via AJAX
     */
    public function ajax_activate_license() {
        check_ajax_referer('wcmp_license_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die('Onvoldoende rechten');
        }
        
        $license_key = sanitize_text_field($_POST['license_key']);
        
        if (empty($license_key)) {
            wp_send_json_error('Licentie sleutel mag niet leeg zijn');
        }
        
        // Activate license on the server
        $domain = $this->sanitize_domain(home_url());
        
        $response = wp_remote_post($this->license_server . '/wp-json/dyronics/v1/license/activate', array(
            'body' => json_encode(array(
                'license_key' => $license_key,
                'domain' => $domain,
                'plugin_slug' => $this->plugin_slug,
                'wp_version' => get_bloginfo('version'),
                'php_version' => PHP_VERSION,
                'plugin_version' => $this->plugin_version
            )),
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'timeout' => 15,
            'sslverify' => false
        ));
        
        if (is_wp_error($response)) {
            wp_send_json_error('Kon geen verbinding maken met licentieserver: ' . $response->get_error_message());
            return;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($response_code !== 200 || !$data || !$data['success']) {
            $error_message = isset($data['message']) ? $data['message'] : 'Activatie mislukt';
            wp_send_json_error($error_message);
            return;
        }
        
        // Store license key and data
        update_option($this->option_key, $license_key);
        update_option($this->option_data, array(
            'status' => 'active',
            'domain' => isset($data['data']['domain']) ? $data['data']['domain'] : $domain,
            'expires' => isset($data['data']['expires_at']) ? $data['data']['expires_at'] : '',
            'customer_name' => isset($data['data']['customer_name']) ? $data['data']['customer_name'] : ''
        ));
        set_transient('wcmp_license_checked', true, DAY_IN_SECONDS);
        
        wp_send_json_success('Licentie succesvol geactiveerd');
    }
    
    /**
     * Deactivate license via AJAX  
     */
    public function ajax_deactivate_license() {
        check_ajax_referer('wcmp_license_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_die('Onvoldoende rechten');
        }
        
        $license_key = get_option($this->option_key);
        if (!empty($license_key)) {
            // Deactivate on server
            $domain = $this->sanitize_domain(home_url());
            
            wp_remote_post($this->license_server . '/wp-json/dyronics/v1/license/deactivate', array(
                'body' => json_encode(array(
                    'license_key' => $license_key,
                    'domain' => $domain,
                    'plugin_slug' => $this->plugin_slug
                )),
                'headers' => array(
                    'Content-Type' => 'application/json'
                ),
                'timeout' => 15,
                'sslverify' => false
            ));
        }
        
        // Clear local data
        delete_option($this->option_key);
        delete_option($this->option_data);
        delete_transient('wcmp_license_checked');
        
        wp_send_json_success('Licentie gedeactiveerd');
    }
    
    /**
     * Verify license with server
     */
    private function verify_license() {
        $license_key = get_option($this->option_key);
        
        if (empty($license_key)) {
            update_option($this->option_data, array());
            return false;
        }
        
        $domain = $this->sanitize_domain(home_url());
        
        $response = wp_remote_post($this->license_server . '/wp-json/dyronics/v1/license/check', array(
            'body' => json_encode(array(
                'license_key' => $license_key,
                'domain' => $domain,
                'plugin_slug' => $this->plugin_slug,
                'version' => $this->plugin_version,
                'signature' => $this->generate_signature($license_key . $domain . $this->plugin_slug)
            )),
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'timeout' => 15,
            'httpversion' => '1.1',
            'sslverify' => false
        ));
        
        if (is_wp_error($response)) {
            // License server unavailable - assume valid for existing users
            $license_data = get_option($this->option_data);
            if (!empty($license_data) && isset($license_data['status']) && in_array($license_data['status'], array('valid', 'active'))) {
                set_transient('wcmp_license_checked', true, DAY_IN_SECONDS);
                return true;
            }
            return false;
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        
        if ($response_code !== 200) {
            update_option($this->option_data, array('status' => 'invalid'));
            return false;
        }
        
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['status'])) {
            update_option($this->option_data, array('status' => 'invalid'));
            return false;
        }
        
        // Store license data
        update_option($this->option_data, $data);
        set_transient('wcmp_license_checked', true, DAY_IN_SECONDS);
        
        return ($data['status'] === 'valid');
    }
    
    /**
     * Check for plugin updates
     */
    public function check_for_update($transient) {
        if (empty($transient->checked)) {
            return $transient;
        }
        
        // Only check if license is valid
        if (!$this->is_license_valid()) {
            return $transient;
        }
        
        $plugin_file = $this->plugin_slug . '/' . $this->plugin_slug . '.php';
        
        if (!isset($transient->checked[$plugin_file])) {
            return $transient;
        }
        
        $current_version = $transient->checked[$plugin_file];
        
        // Check with license server for updates
        $response = wp_remote_post($this->license_server . '/wp-json/dyronics/v1/license/check-update', array(
            'body' => json_encode(array(
                'license_key' => get_option($this->option_key),
                'plugin_slug' => $this->plugin_slug,
                'current_version' => $current_version,
                'domain' => $this->sanitize_domain(home_url())
            )),
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'timeout' => 15,
            'sslverify' => false
        ));
        
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            return $transient;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['new_version'])) {
            return $transient;
        }
        
        // Version comparison
        if (version_compare($current_version, $data['new_version'], '<')) {
            // Get package URL - try multiple fields for compatibility
            $package_url = '';
            if (isset($data['download_url'])) {
                $package_url = $data['download_url'];
            } elseif (isset($data['package'])) {
                $package_url = $data['package'];
            } elseif (isset($data['data']['download_url'])) {
                $package_url = $data['data']['download_url'];
            }
            
            $transient->response[$plugin_file] = (object) array(
                'slug' => $this->plugin_slug,
                'new_version' => $data['new_version'],
                'url' => isset($data['url']) ? $data['url'] : '',
                'package' => $package_url,
                'tested' => isset($data['tested']) ? $data['tested'] : '',
                'requires_php' => isset($data['requires_php']) ? $data['requires_php'] : '',
                'compatibility' => isset($data['compatibility']) ? $data['compatibility'] : array()
            );
        }
        
        return $transient;
    }
    
    /**
     * Plugin API call for update information
     */
    public function plugin_api_call($result, $action, $args) {
        if ($action !== 'plugin_information') {
            return $result;
        }
        
        if (!isset($args->slug) || $args->slug !== $this->plugin_slug) {
            return $result;
        }
        
        if (!$this->is_license_valid()) {
            return $result;
        }
        
        // Get plugin information from license server
        $response = wp_remote_post($this->license_server . '/wp-json/dyronics/v1/plugin/info', array(
            'body' => json_encode(array(
                'license_key' => get_option($this->option_key),
                'plugin_slug' => $this->plugin_slug,
                'domain' => $this->sanitize_domain(home_url())
            )),
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'timeout' => 15,
            'sslverify' => false
        ));
        
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            return $result;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data) {
            return $result;
        }
        
        return (object) $data;
    }
    
    /**
     * Sanitize domain for comparison
     */
    private function sanitize_domain($url) {
        $parsed = parse_url($url);
        $domain = isset($parsed['host']) ? $parsed['host'] : '';
        
        // Remove www prefix
        $domain = preg_replace('/^www\./', '', $domain);
        
        return strtolower($domain);
    }
    
    /**
     * Generate signature for API requests
     */
    private function generate_signature($data) {
        return hash_hmac('sha256', $data, 'DYR0N1C5_L1C3N53_53CR3T_K3Y_2026');
    }
    
    /**
     * Get license key
     */
    public function get_license_key() {
        return get_option($this->option_key);
    }
    
    /**
     * Get license data
     */
    public function get_license_data() {
        return get_option($this->option_data);
    }
    
    /**
     * Send diagnostic data to license server
     */
    public function send_diagnostic_data() {
        if (!$this->is_license_valid()) {
            return false;
        }
        
        global $wp_version;
        
        $diagnostic_data = array(
            'domain' => $this->sanitize_domain(home_url()),
            'license_key' => get_option($this->option_key),
            'plugin_version' => $this->plugin_version,
            'wp_version' => $wp_version,
            'php_version' => phpversion(),
            'server_info' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'active_plugins' => get_option('active_plugins'),
            'theme' => wp_get_theme()->get('Name'),
            'timestamp' => current_time('mysql'),
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'upload_max_filesize' => ini_get('upload_max_filesize'),
            'post_max_size' => ini_get('post_max_size')
        );
        
        // Add plugin specific data
        if (class_exists('WCMYPA')) {
            $wcmypa = WCMYPA::$plugin;
            if ($wcmypa) {
                $diagnostic_data['myparcel_settings'] = array(
                    'api_key_set' => !empty($wcmypa->setting_collection->getByName(WCMYPA_Settings::SETTING_API_KEY)),
                    'checkout_display' => $wcmypa->setting_collection->getByName(WCMYPA_Settings::SETTING_DELIVERY_OPTIONS_DISPLAY),
                    'default_options' => $wcmypa->setting_collection->getByName(WCMYPA_Settings::SETTING_SHIPPING_METHODS_PACKAGE_TYPES)
                );
            }
        }
        
        $response = wp_remote_post($this->license_server . '/wp-json/dyronics/v1/license/diagnostics', array(
            'body' => json_encode($diagnostic_data),
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'timeout' => 30,
            'sslverify' => false
        ));
        
        return !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200;
    }
    
    /**
     * Schedule diagnostic data sending
     */
    public function schedule_diagnostics() {
        if (!wp_next_scheduled('wcmp_send_diagnostics')) {
            wp_schedule_event(time(), 'daily', 'wcmp_send_diagnostics');
        }
        
        add_action('wcmp_send_diagnostics', array($this, 'send_diagnostic_data'));
    }
    
    /**
     * Render license section in MyParcel settings
     */
    public function render_license_section($active_tab) {
        // Only show on general tab
        if ($active_tab !== 'general') {
            return;
        }
        
        $license_key = get_option($this->option_key);
        $license_data = get_option($this->option_data);
        $is_valid = $this->is_license_valid();
        ?>
        <div class="wcmp-license-settings" style="margin-top: 20px; padding: 15px; border: 1px solid #ddd; background: #f9f9f9;">
            <h3><?php _e('Dyronics Licentie', 'woocommerce-myparcel'); ?></h3>
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="wcmp_license_key"><?php _e('Licentie Sleutel', 'woocommerce-myparcel'); ?></label>
                    </th>
                    <td>
                        <input type="password" 
                               id="wcmp_license_key" 
                               name="wcmp_license_key" 
                               value="<?php echo esc_attr($license_key); ?>" 
                               class="regular-text" 
                               placeholder="XXXX-XXXX-XXXX-XXXX" />
                        
                        <?php if ($is_valid): ?>
                            <span class="wcmp-license-status valid" style="color: #46b450; font-weight: bold; margin-left: 10px;">✓ Geldig</span>
                            <button type="button" class="button" id="wcmp-deactivate-license">
                                <?php _e('Deactiveren', 'woocommerce-myparcel'); ?>
                            </button>
                        <?php else: ?>
                            <span class="wcmp-license-status invalid" style="color: #dc3232; font-weight: bold; margin-left: 10px;">✗ Ongeldig</span>
                            <button type="button" class="button-primary" id="wcmp-activate-license">
                                <?php _e('Activeren', 'woocommerce-myparcel'); ?>
                            </button>
                        <?php endif; ?>
                    </td>
                </tr>
                
                <?php if ($is_valid && !empty($license_data)): ?>
                <tr>
                    <th scope="row"><?php _e('Licentie Informatie', 'woocommerce-myparcel'); ?></th>
                    <td>
                        <p><strong><?php _e('Type:', 'woocommerce-myparcel'); ?></strong> 
                           <?php echo esc_html($license_data['license_type'] ?? 'Onbekend'); ?></p>
                        
                        <?php if (isset($license_data['expires'])): ?>
                        <p><strong><?php _e('Verloopt:', 'woocommerce-myparcel'); ?></strong> 
                           <?php echo esc_html($license_data['expires']); ?></p>
                        <?php endif; ?>
                        
                        <?php if (isset($license_data['features']) && !empty($license_data['features'])): ?>
                        <p><strong><?php _e('Functies:', 'woocommerce-myparcel'); ?></strong> 
                           <?php echo esc_html(implode(', ', $license_data['features'])); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endif; ?>
            </table>
            
            <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('#wcmp-activate-license').on('click', function() {
                    var licenseKey = $('#wcmp_license_key').val();
                    
                    if (!licenseKey) {
                        alert('Voer een licentie sleutel in');
                        return;
                    }
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'wcmp_license_activate',
                            license_key: licenseKey,
                            nonce: '<?php echo wp_create_nonce('wcmp_license_nonce'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                location.reload();
                            } else {
                                alert('Fout: ' + response.data);
                            }
                        },
                        error: function() {
                            alert('Er is een fout opgetreden');
                        }
                    });
                });
                
                $('#wcmp-deactivate-license').on('click', function() {
                    if (!confirm('Weet je zeker dat je de licentie wilt deactiveren?')) {
                        return;
                    }
                    
                    $.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'wcmp_license_deactivate',
                            nonce: '<?php echo wp_create_nonce('wcmp_license_nonce'); ?>'
                        },
                        success: function(response) {
                            if (response.success) {
                                location.reload();
                            } else {
                                alert('Fout: ' + response.data);
                            }
                        },
                        error: function() {
                            alert('Er is een fout opgetreden');
                        }
                    });
                });
            });
            </script>
        </div>
        <?php
    }

    /**
     * Get admin settings HTML
     */
    public function get_admin_settings_html() {
        $license_key = get_option($this->option_key);
        $license_data = get_option($this->option_data);
        $is_valid = $this->is_license_valid();
        
        ob_start();
        ?>
        <div class="wcmp-license-settings">
            <h3><?php _e('Dyronics Licentie', 'woocommerce-myparcel'); ?></h3>
            
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="wcmp_license_key"><?php _e('Licentie Sleutel', 'woocommerce-myparcel'); ?></label>
                    </th>
                    <td>
                        <input type="password" 
                               id="wcmp_license_key" 
                               name="wcmp_license_key" 
                               value="<?php echo esc_attr($license_key); ?>" 
                               class="regular-text" 
                               placeholder="XXXX-XXXX-XXXX-XXXX" />
                        
                        <?php if ($is_valid): ?>
                            <span class="wcmp-license-status valid">✓ Geldig</span>
                            <button type="button" class="button" id="wcmp-deactivate-license">
                                <?php _e('Deactiveren', 'woocommerce-myparcel'); ?>
                            </button>
                        <?php else: ?>
                            <span class="wcmp-license-status invalid">✗ Ongeldig</span>
                            <button type="button" class="button-primary" id="wcmp-activate-license">
                                <?php _e('Activeren', 'woocommerce-myparcel'); ?>
                            </button>
                        <?php endif; ?>
                    </td>
                </tr>
                
                <?php if ($is_valid && !empty($license_data)): ?>
                <tr>
                    <th scope="row"><?php _e('Licentie Informatie', 'woocommerce-myparcel'); ?></th>
                    <td>
                        <p><strong><?php _e('Type:', 'woocommerce-myparcel'); ?></strong> 
                           <?php echo esc_html($license_data['license_type'] ?? 'Onbekend'); ?></p>
                        
                        <?php if (isset($license_data['expires'])): ?>
                        <p><strong><?php _e('Verloopt:', 'woocommerce-myparcel'); ?></strong> 
                           <?php echo esc_html($license_data['expires']); ?></p>
                        <?php endif; ?>
                        
                        <?php if (isset($license_data['features']) && !empty($license_data['features'])): ?>
                        <p><strong><?php _e('Functies:', 'woocommerce-myparcel'); ?></strong> 
                           <?php echo esc_html(implode(', ', $license_data['features'])); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endif; ?>
            </table>
        </div>
        <?php
        
        return ob_get_clean();
    }
    
    /**
     * Report version to license server after plugin update
     */
    public function report_version_after_update($upgrader_object, $options) {
        // Check if this is a plugin update
        if ($options['type'] !== 'plugin' || $options['action'] !== 'update') {
            return;
        }
        
        // Check if our plugin was updated
        $our_plugin = $this->plugin_slug . '/' . $this->plugin_slug . '.php';
        
        if (isset($options['plugins'])) {
            foreach ($options['plugins'] as $plugin) {
                if ($plugin === $our_plugin) {
                    // Our plugin was updated - report new version to license server
                    $this->report_current_version();
                    break;
                }
            }
        } elseif (isset($options['plugin']) && $options['plugin'] === $our_plugin) {
            // Single plugin update
            $this->report_current_version();
        }
    }
    
    /**
     * Report current plugin version to license server
     */
    private function report_current_version() {
        $license_key = get_option($this->option_key);
        
        if (empty($license_key)) {
            return; // No license configured
        }
        
        // Get fresh version number
        $current_version = $this->get_plugin_version();
        
        // Send version report to license server
        wp_remote_post($this->license_server . '/wp-json/dyronics/v1/license/report-version', array(
            'body' => json_encode(array(
                'license_key' => $license_key,
                'plugin_slug' => $this->plugin_slug,
                'version' => $current_version,
                'domain' => $this->sanitize_domain(home_url()),
                'wp_version' => get_bloginfo('version'),
                'php_version' => phpversion()
            )),
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'timeout' => 5,
            'sslverify' => false,
            'blocking' => false // Non-blocking so it doesn't slow down the update
        ));
    }
}
