<?php
/**
 * Maintenance GENIUS - Admin
 * Gestion du menu et de l'interface d'administration
 * Version 2.9.126
 */

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

class MG_Admin {

    /**
     * Enregistre les hooks admin
     */
    public static function init() {
        add_action('admin_menu', [__CLASS__, 'add_menu']);
        add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_assets']);
        add_action('admin_bar_menu', [__CLASS__, 'add_admin_bar_menu'], 999);
        
        add_action('admin_head', [__CLASS__, 'admin_bar_toggle_assets']);
        add_action('wp_head', [__CLASS__, 'admin_bar_toggle_assets']);
        add_action('admin_footer', [__CLASS__, 'sidebar_submenu_js']);
        
        add_filter('upload_mimes', [__CLASS__, 'allow_json_upload']);
        add_filter('wp_check_filetype_and_ext', [__CLASS__, 'fix_json_mime_type'], 10, 5);
        
        // Badge PRO dans la liste des extensions (v2.9.43)
        add_filter('all_plugins', [__CLASS__, 'add_pro_badge_to_name']);
        add_filter('plugin_row_meta', [__CLASS__, 'add_pro_row_meta'], 10, 2);

        // Toujours actif → widget MG Core (status maintenance + stats + quick actions).
        // Si monitoring UI activé → widget legacy avec données monitoring (rétro-compat).
        add_action( 'wp_dashboard_setup', [ __CLASS__, 'add_dashboard_widget' ] );

        // - Contraint l'icône menu sidebar à 20×20 (sinon le PNG s'affiche en taille réelle)
        // - Cache le logo header sur la page MG (orange sur orange = invisible)
        add_action( 'admin_head', [ __CLASS__, 'inject_admin_css_fix' ] );
    }

    /**
     * v2.9.69 — Injection CSS minimale pour contraindre l'icône menu sidebar et masquer
     * le logo header sur fond orange (anti-bug v2.9.69).
     */
    public static function inject_admin_css_fix() {
        ?>
        <style>
            #toplevel_page_maintenance-genius .wp-menu-image img,
            #toplevel_page_maintenance-genius .wp-menu-image.svg img {
                width: 20px !important;
                height: 20px !important;
                max-width: 20px !important;
                max-height: 20px !important;
                padding: 6px 0 0 !important;
                opacity: 0.9;
            }
            #toplevel_page_maintenance-genius:hover .wp-menu-image img,
            #toplevel_page_maintenance-genius.current .wp-menu-image img,
            #toplevel_page_maintenance-genius.wp-has-current-submenu .wp-menu-image img {
                opacity: 1;
            }
            /* Cache le logo header (orange sur fond orange = invisible) */
            .mg-header-logo { display: none !important; }
        </style>
        <?php
    }

    /**
     * Initialisation frontend uniquement: admin bar + toggle (v2.6.64)
     */
    public static function init_admin_bar() {
        add_action('admin_bar_menu', [__CLASS__, 'add_admin_bar_menu'], 999);
        add_action('wp_head', [__CLASS__, 'admin_bar_toggle_assets']);
    }

    /**
     * Autoriser l'upload de fichiers JSON et Lottie (v2.6.19)
     */
    public static function allow_json_upload($mimes) {
        $mimes['json'] = 'application/json';
        $mimes['lottie'] = 'application/json';
        return $mimes;
    }

    /**
     * Corriger le type MIME pour les fichiers JSON et Lottie (v2.6.19)
     */
    public static function fix_json_mime_type($data, $file, $filename, $mimes, $real_mime = '') {
        if (!empty($data['ext']) && !empty($data['type'])) {
            return $data;
        }

        $filetype = wp_check_filetype($filename, $mimes);

        if ($filetype['ext'] === 'json') {
            $data['ext'] = 'json';
            $data['type'] = 'application/json';
        }
        
        if ($filetype['ext'] === 'lottie') {
            $data['ext'] = 'lottie';
            $data['type'] = 'application/json';
        }

        return $data;
    }

    /**
     * Ajoute le menu et sous-menus dans l'admin WordPress (v2.9.69)
     */
    public static function add_menu() {
        // Fallback SVG monochrome v2.9.52 si PNG manquant. WordPress affiche l'URL directement.
        $icon_url = MG_PLUGIN_URL . 'assets/images/mg-icon-256.png';
        $icon_path = MG_PLUGIN_DIR . 'assets/images/mg-icon-256.png';
        if ( ! file_exists( $icon_path ) ) {
            $icon_url = MG_PLUGIN_URL . 'assets/images/mg-icon.svg';
        }

        add_menu_page(
            'Maintenance GENIUS',
            'Maintenance GENIUS',
            'manage_options',
            'maintenance-genius',
            [__CLASS__, 'render_page'],
            $icon_url,
            100
        );

        // Sous-menu "Paramètres" — remplace le doublon WP auto
        add_submenu_page(
            'maintenance-genius',
            __('Settings', 'maintenance-genius'),
            '⚙️ ' . __('Settings', 'maintenance-genius'),
            'manage_options',
            'maintenance-genius'
        );

        // Sous-menu "Aperçu" — JS intercepte pour ouvrir en nouvel onglet
        add_submenu_page(
            'maintenance-genius',
            __('Preview', 'maintenance-genius'),
            '👁 ' . __('Preview', 'maintenance-genius'),
            'manage_options',
            'mg-preview-redirect',
            '__return_null'
        );

        // Sous-menu "Activer/Désactiver" — JS intercepte pour AJAX toggle
        $settings = MG_Settings::load();
        $is_active = ! empty( $settings['maintenance_enabled'] );
        $toggle_label = $is_active
            ? '❌ ' . __('Disable', 'maintenance-genius')
            : '✅ ' . __('Enable', 'maintenance-genius');

        add_submenu_page(
            'maintenance-genius',
            __('Toggle maintenance', 'maintenance-genius'),
            '<span id="mg-sidebar-toggle-label">' . $toggle_label . '</span>',
            'manage_options',
            'mg-toggle-redirect',
            '__return_null'
        );
    }

    /**
     * JS pour sous-menus sidebar : Aperçu (nouvel onglet) + Toggle (AJAX) (v2.9.52)
     */
    public static function sidebar_submenu_js() {
        if ( ! current_user_can('manage_options') ) {
            return;
        }
        $preview_url = home_url( '/?mg_preview=1&_wpnonce=' . wp_create_nonce('mg_preview') );
        $settings    = MG_Settings::load();
        $is_active   = ! empty( $settings['maintenance_enabled'] ) ? 1 : 0;
        ?>
        <script>
        (function(){
            document.addEventListener('DOMContentLoaded', function(){
                // Aperçu → nouvel onglet
                var previewLinks = document.querySelectorAll('a[href*="mg-preview-redirect"]');
                previewLinks.forEach(function(link){
                    link.addEventListener('click', function(e){
                        e.preventDefault();
                        window.open('<?php echo esc_js( $preview_url ); ?>', '_blank');
                    });
                });

                // Toggle → AJAX
                var toggleLinks = document.querySelectorAll('a[href*="mg-toggle-redirect"]');
                var mgSidebarEnabled = <?php echo $is_active ? 'true' : 'false'; ?>;
                toggleLinks.forEach(function(link){
                    link.addEventListener('click', function(e){
                        e.preventDefault();
                        if (link.classList.contains('mg-loading')) return;
                        link.classList.add('mg-loading');
                        var newState = !mgSidebarEnabled;
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', '<?php echo esc_js( admin_url('admin-ajax.php') ); ?>');
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        xhr.onload = function(){
                            link.classList.remove('mg-loading');
                            try {
                                var resp = JSON.parse(xhr.responseText);
                                if (resp && resp.success) {
                                    mgSidebarEnabled = resp.data.enabled;
                                    var label = document.getElementById('mg-sidebar-toggle-label');
                                    if (label) {
                                        label.textContent = mgSidebarEnabled
                                            ? '❌ <?php echo esc_js( __('Disable', 'maintenance-genius') ); ?>'
                                            : '✅ <?php echo esc_js( __('Enable', 'maintenance-genius') ); ?>';
                                    }
                                    // Sync admin bar toggle if present
                                    var abToggle = document.getElementById('mg-adminbar-toggle');
                                    if (abToggle) {
                                        abToggle.setAttribute('data-enabled', mgSidebarEnabled ? '1' : '0');
                                        abToggle.classList.toggle('mg-active', mgSidebarEnabled);
                                        var abLabel = abToggle.querySelector('.mg-toggle-label');
                                        if (abLabel) abLabel.textContent = mgSidebarEnabled ? 'ON' : 'OFF';
                                    }
                                    // Sync page toggle if present
                                    var pageToggle = document.getElementById('mg-toggle');
                                    if (pageToggle && pageToggle.type === 'checkbox') {
                                        pageToggle.checked = mgSidebarEnabled;
                                        pageToggle.dispatchEvent(new Event('change'));
                                    }
                                    // Sync floating button if present
                                    var floatToggle = document.getElementById('mg-float-toggle');
                                    if (floatToggle) {
                                        floatToggle.classList.toggle('is-on', mgSidebarEnabled);
                                        floatToggle.classList.toggle('is-off', !mgSidebarEnabled);
                                        var floatLabel = document.getElementById('mg-float-status');
                                        if (floatLabel) floatLabel.textContent = mgSidebarEnabled ? 'ON' : 'OFF';
                                    }
                                    var widgetDot = document.querySelector('#mg_dashboard_widget .mg-dwc-dot');
                                    if (widgetDot) {
                                        widgetDot.classList.toggle('maintenance', mgSidebarEnabled);
                                        widgetDot.classList.toggle('live', !mgSidebarEnabled);
                                        var widgetText = document.querySelector('#mg_dashboard_widget .mg-dwc-status-text');
                                        var widgetSub  = document.querySelector('#mg_dashboard_widget .mg-dwc-status-sub');
                                        if (widgetText) widgetText.textContent = mgSidebarEnabled ? 'Maintenance Active' : 'Site Live';
                                        if (widgetSub)  widgetSub.textContent  = mgSidebarEnabled ? 'Visitors see your maintenance page' : 'Maintenance mode is OFF';
                                    }
                                }
                            } catch(ex){}
                        };
                        xhr.onerror = function(){ link.classList.remove('mg-loading'); };
                        xhr.send('action=mg_toggle&nonce=<?php echo esc_js( wp_create_nonce('mg_nonce') ); ?>&enabled=' + (newState ? 'true' : 'false'));
                    });
                });
            });
        })();
        </script>
        <?php
    }

    /**
     * Charge les assets CSS/JS pour l'admin
     */
    public static function enqueue_assets($hook) {
        if ($hook !== 'toplevel_page_maintenance-genius') {
            return;
        }

        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');

        wp_enqueue_media();

        wp_enqueue_script('jquery');

        // le CSS admin fantôme après update sans changement de version.
        $mg_css_path = MG_PLUGIN_DIR . 'assets/css/admin.css';
        $mg_css_ver  = file_exists( $mg_css_path ) ? MG_VERSION . '.' . filemtime( $mg_css_path ) : MG_VERSION;
        wp_enqueue_style(
            'mg-admin-css',
            MG_PLUGIN_URL . 'assets/css/admin.css',
            [],
            $mg_css_ver
        );

        $mg_js_path = MG_PLUGIN_DIR . 'assets/js/admin.js';
        $mg_js_ver  = file_exists( $mg_js_path ) ? MG_VERSION . '.' . filemtime( $mg_js_path ) : MG_VERSION;
        wp_enqueue_script(
            'mg-admin-js',
            MG_PLUGIN_URL . 'assets/js/admin.js',
            ['jquery', 'wp-color-picker'],
            $mg_js_ver,
            true
        );

        wp_localize_script('mg-admin-js', 'mgAdmin', [
            'ajaxurl'     => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('mg_nonce'),
            'preview_url' => home_url('/?mg_preview=1&_wpnonce=' . wp_create_nonce('mg_preview')),
            'version'     => MG_VERSION,
            'lottie_player_url' => MG_PLUGIN_URL . 'assets/js/vendor/dotlottie/dotlottie-player.mjs?ver=' . MG_VERSION,
            'i18n'        => [
                'unsaved'                => __('Unsaved', 'maintenance-genius'),
                'saving'                 => __('Saving...', 'maintenance-genius'),
                'saved'                  => __('Saved', 'maintenance-genius'),
                'retry'                  => __('Retry', 'maintenance-genius'),
                'h1h2_reset'             => __('H1/H2 sizes reset to default values', 'maintenance-genius'),
                'csv_exported'           => __('CSV export downloaded', 'maintenance-genius'),
                'no_email_export'        => __('No emails to export', 'maintenance-genius'),
                'emails_deleted'         => __('Emails deleted', 'maintenance-genius'),
                'connection_error'       => __('Connection error', 'maintenance-genius'),
                'error_prefix'           => __('Error:', 'maintenance-genius'),
                'unknown'                => __('Unknown', 'maintenance-genius'),
                'whitelist_saved'        => __('Whitelist saved!', 'maintenance-genius'),
                'blacklist_saved'        => __('Blacklist saved!', 'maintenance-genius'),
                'logs_cleared'           => __('Logs cleared!', 'maintenance-genius'),
                'no_logs_export'         => __('No logs to export', 'maintenance-genius'),
                'enter_license_key'      => __('Please enter a license key', 'maintenance-genius'),
                'config_exported'        => __('Configuration exported successfully!', 'maintenance-genius'),
                'export_error'           => __('Error during export', 'maintenance-genius'),
                'select_json_file'       => __('Please select a JSON file', 'maintenance-genius'),
                'import_error'           => __('Error during import', 'maintenance-genius'),
                'error_generic'          => __('Error', 'maintenance-genius'),
                'chat_connection_error'  => __('Connection error. Please try again later.', 'maintenance-genius'),
                'confirm_delete_emails'     => __('Are you sure you want to delete all collected emails?', 'maintenance-genius'),
                'confirm_disconnect_all'    => __('Do you really want to disconnect all visitors?', 'maintenance-genius'),
                'confirm_reset_design'      => __('Do you really want to reset the design?', 'maintenance-genius'),
                'confirm_clear_logs'        => __('Do you really want to clear all logs?', 'maintenance-genius'),
                /* translators: %s: name or value */
                'confirm_delete_access'     => __('Delete access for "%s"?', 'maintenance-genius'),
                'confirm_clear_access_logs' => __('Clear access logs?', 'maintenance-genius'),
                'confirm_deactivate_license'=> __('Are you sure you want to deactivate your PRO license?', 'maintenance-genius'),
                'confirm_delete_animation'  => __('Delete this animation?', 'maintenance-genius'),
                // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText -- Multi-line confirm dialog
                /* translators: %s: preset name */
                'confirm_apply_preset'      => __( "Apply preset \"%s\"?\n\nThis will replace your current design settings.", 'maintenance-genius' ),
                /* translators: %s: name or value */
                'confirm_delete_preset'     => __('Permanently delete preset "%s"?', 'maintenance-genius'),
                'confirm_reset_stats'       => // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
                __( "Do you really want to reset all statistics?\n\nThis action is irreversible.", 'maintenance-genius' ),
                'confirm_import_settings'   => // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
                __( "⚠️ This will replace your current settings.\n\nDo you want to continue?", 'maintenance-genius' ),
                'preview_url_error'      => __('Error: Preview URL not defined', 'maintenance-genius'),
                'format_not_supported'   => // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
                __( "Format not supported.\n\nUse a .json or .lottie file downloaded from LottieFiles.com", 'maintenance-genius' ),
                'file_too_large'         => __('File too large (max 5 MB)', 'maintenance-genius'),
                'upload_failed'          => __('Upload failed', 'maintenance-genius'),
                'connection_error_retry' => __('Connection error. Please try again.', 'maintenance-genius'),
                'save_error'             => __('Error saving', 'maintenance-genius'),
                'select_json_file_alert' => __('Please select a .json file', 'maintenance-genius'),
                'checking'               => __('Checking...', 'maintenance-genius'),
                'checking_in_progress'   => __('⏳ Checking in progress...', 'maintenance-genius'),
                'check_error'            => __('❌ Check error', 'maintenance-genius'),
                'resetting'              => __('Resetting...', 'maintenance-genius'),
                'saving'                 => __('Saving...', 'maintenance-genius'),
                'loading'                => __('Loading...', 'maintenance-genius'),
                'deleting'               => __('Deleting...', 'maintenance-genius'),
                'creating'               => __('Creating...', 'maintenance-genius'),
                'save'                   => __('Save', 'maintenance-genius'),
                'load_logs'              => __('Load logs', 'maintenance-genius'),
                'activating'             => __('Activating...', 'maintenance-genius'),
                'activate'               => __('Activate', 'maintenance-genius'),
                'deactivating'           => __('Deactivating...', 'maintenance-genius'),
                'saving_preset'          => __('Saving...', 'maintenance-genius'),
                'save_preset_btn'        => __('💾 Save', 'maintenance-genius'),
                'importing'              => __('Importing...', 'maintenance-genius'),
                'import_preset_btn'      => __('📥 Import a preset', 'maintenance-genius'),
                'resetting_stats'        => __('⏳ Resetting...', 'maintenance-genius'),
                'reset_stats_btn'        => __('🗑️ Reset statistics', 'maintenance-genius'),
                'exporting'              => __('⏳ Exporting...', 'maintenance-genius'),
                'download_backup_btn'    => __('📥 Download Backup', 'maintenance-genius'),
                'download'               => __('Download', 'maintenance-genius'),
                'choose_bg_image'        => __('Choose a background image', 'maintenance-genius'),
                'use_this_image'         => __('Use this image', 'maintenance-genius'),
                'choose_logo'            => __('Choose a logo', 'maintenance-genius'),
                'use'                    => __('Use', 'maintenance-genius'),
                'no_custom_presets'      => __('No custom presets saved.', 'maintenance-genius'),
                'configure_design_hint'  => __('Configure your perfect design, then save it here!', 'maintenance-genius'),
                'new_version_available'  => __('New version available!', 'maintenance-genius'),
                'is_available'           => __('is available.', 'maintenance-genius'),
                'check_updates'          => __('Check for updates', 'maintenance-genius'),
                'up_to_date'             => __('You are up to date!', 'maintenance-genius'),
                'is_latest_version'      => __('is the latest version.', 'maintenance-genius'),
                'no_image_selected'      => __('No image selected', 'maintenance-genius'),
                'drag_drop'              => __('Drag and drop', 'maintenance-genius'),
                'your_file_here'         => __('your .json or .lottie file here', 'maintenance-genius'),
                'or_click_select'        => __('or click to select', 'maintenance-genius'),
                'password_generated'     => __('Password generated!', 'maintenance-genius'),
                'password_copied'        => __('Password copied!', 'maintenance-genius'),
                'copied'                 => __('Copied!', 'maintenance-genius'),
                'background_saved'       => __('Background saved!', 'maintenance-genius'),
                'unsaved_changes'        => __('Unsaved changes', 'maintenance-genius'),
                'unsaved_warning'        => __('You have unsaved changes. Leave the page anyway?', 'maintenance-genius'),
                'text_colors_saved'      => __('Text colors saved!', 'maintenance-genius'),
                'button_colors_saved'    => __('Button colors saved!', 'maintenance-genius'),
                'container_saved'        => __('Container saved!', 'maintenance-genius'),
                'typography_saved'       => __('Typography saved!', 'maintenance-genius'),
                'dimensions_saved'       => __('Dimensions saved!', 'maintenance-genius'),
                'animations_saved'       => __('Animations saved!', 'maintenance-genius'),
                'design_saved'           => __('Design saved!', 'maintenance-genius'),
                'all_saved'              => __('All saved!', 'maintenance-genius'),
                'disable_maintenance'    => __('Disable maintenance', 'maintenance-genius'),
                'enable_maintenance'     => __('Enable maintenance', 'maintenance-genius'),
                'go_pro'                 => __('Upgrade to PRO →', 'maintenance-genius'),
                'schedule_configured'    => __('Schedule configured:', 'maintenance-genius'),
                'start_label'            => __('Start:', 'maintenance-genius'),
                'end_label'              => __('End:', 'maintenance-genius'),
                'at'                     => __('at', 'maintenance-genius'),
                'apply'                  => __('Apply', 'maintenance-genius'),
                'upload_backup_btn'      => __('📤 Upload Backup', 'maintenance-genius'),
                'confirm_clear_monitoring'   => __('Do you really want to clear the monitoring history?', 'maintenance-genius'),
                'no_monitoring_events'       => __('No events recorded yet.', 'maintenance-genius'),
                'resend_email'               => __('Resend email', 'maintenance-genius'),
                'regenerate_token'           => __('🔑 Regenerate token', 'maintenance-genius'),
                'confirm_regenerate_token'   => __('⚠️ Generating a new token will invalidate the old one. Continue?', 'maintenance-genius'),
                'send'                       => __('📧 Send', 'maintenance-genius'),
                'logs_cleared'               => __('Logs cleared', 'maintenance-genius'),
                'unblocked'                  => __('✅ Unblocked!', 'maintenance-genius'),
                'session_expired_reload'     => __('🔒 Session expired — reload the page', 'maintenance-genius'),
                'session_expired'            => __('🔒 Session expired', 'maintenance-genius'),
                // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText -- Confirm dialog with placeholder
                /* translators: %s: theme label */
                'theme_confirm'              => __("Apply theme \"%s\"?\n\nYour current visual settings will be saved for undo.", 'maintenance-genius'),
                'theme_applied_badge'        => __('applied', 'maintenance-genius'),
                'revert_theme'               => __('Revert Theme', 'maintenance-genius'),
                'coming_soon_label'          => __('COMING SOON', 'maintenance-genius'),
                'coming_soon_mode'           => __('COMING SOON MODE', 'maintenance-genius'),
                'maintenance_mode'           => __('MAINTENANCE MODE', 'maintenance-genius'),
            ],
        ]);
    }

    /**
     * Affiche la page d'administration
     */
    public static function render_page() {
        if (!current_user_can('manage_options')) {
            return;
        }

        $settings = MG_Settings::load();
        $fonts = MG_Settings::get_fonts();
        $animations = MG_Settings::get_animations();

        include MG_PLUGIN_DIR . 'templates/admin-page.php';
    }

    /**
     * Ajoute le menu dans la barre d'administration avec toggle ON/OFF (v2.6.64)
     */
    public static function add_admin_bar_menu($wp_admin_bar) {
        if (!current_user_can('manage_options')) {
            return;
        }

        $preview_url = home_url('/?mg_preview=1&_wpnonce=' . wp_create_nonce('mg_preview'));
        $settings_url = admin_url('admin.php?page=maintenance-genius');
        $settings = MG_Settings::load();
        $is_active = !empty($settings['maintenance_enabled']);

        $icon_style = 'font-family:dashicons;font-size:16px;vertical-align:middle;margin-right:5px;';

        $toggle_html = '<span class="mg-toggle-switch' . ($is_active ? ' mg-active' : '') . '" id="mg-adminbar-toggle" data-enabled="' . ($is_active ? '1' : '0') . '">';
        $toggle_html .= '<span class="mg-toggle-track">';
        $toggle_html .= '<span class="mg-toggle-thumb"></span>';
        $toggle_html .= '</span>';
        $toggle_html .= '<span class="mg-toggle-label">' . ($is_active ? 'ON' : 'OFF') . '</span>';
        $toggle_html .= '</span>';

        $title = '<span class="ab-icon dashicons-before dashicons-admin-tools"></span>';
        $title .= '<span class="ab-label">Maintenance</span>';
        $title .= $toggle_html;

        $wp_admin_bar->add_node([
            'id'    => 'maintenance-genius',
            'title' => $title,
            'href'  => $settings_url,
            'meta'  => [
                'title' => 'Maintenance GENIUS v' . MG_VERSION
            ]
        ]);

        $wp_admin_bar->add_node([
            'id'     => 'mg-settings',
            'parent' => 'maintenance-genius',
            'title'  => '<span style="' . $icon_style . '" class="dashicons-admin-generic"></span>' . __('Settings', 'maintenance-genius'),
            'href'   => $settings_url,
        ]);

        $wp_admin_bar->add_node([
            'id'     => 'mg-preview',
            'parent' => 'maintenance-genius',
            'title'  => '<span style="' . $icon_style . '" class="dashicons-visibility"></span>' . __('Preview', 'maintenance-genius'),
            'href'   => $preview_url,
            'meta'   => [
                'target' => '_blank',
            ]
        ]);

        $toggle_icon = $is_active ? 'dashicons-no' : 'dashicons-yes';
        $toggle_color = $is_active ? 'color:#dc3545;' : 'color:#4CAF50;';
        $toggle_text = $is_active ? __('Disable', 'maintenance-genius') : __('Enable', 'maintenance-genius');
        
        $wp_admin_bar->add_node([
            'id'     => 'mg-toggle',
            'parent' => 'maintenance-genius',
            'title'  => '<span style="' . $icon_style . $toggle_color . '" class="' . $toggle_icon . '"></span>' . $toggle_text,
            'href'   => '#',
            'meta'   => [
                'class' => 'mg-admin-bar-toggle',
            ]
        ]);
    }

    /**
     * CSS/JS inline pour le toggle admin bar (chargé globalement) (v2.6.64)
     */
    public static function admin_bar_toggle_assets() {
        if (!current_user_can('manage_options') || !is_admin_bar_showing()) {
            return;
        }
        ?>
        <style>
        /* ===== Maintenance GENIUS - Admin Bar Toggle v2.6.64 ===== */
        #wpadminbar .mg-toggle-switch {
            display:inline-flex !important;align-items:center !important;cursor:pointer !important;
            margin-left:8px !important;vertical-align:middle !important;position:relative !important;z-index:10 !important;
            line-height:1 !important;height:auto !important;
        }
        #wpadminbar .mg-toggle-track {
            width:40px !important;height:22px !important;
            background:rgba(255,255,255,0.2) !important;
            border-radius:22px !important;
            position:relative !important;transition:all .4s ease !important;
            display:inline-block !important;box-sizing:border-box !important;
            padding:0 !important;margin:0 !important;
        }
        #wpadminbar .mg-active .mg-toggle-track {
            background:#4CAF50 !important;
            box-shadow:0 0 8px rgba(76,175,80,0.6),0 0 16px rgba(76,175,80,0.25) !important;
        }
        #wpadminbar .mg-toggle-thumb {
            width:16px !important;height:16px !important;background:#fff !important;border-radius:50% !important;
            position:absolute !important;top:3px !important;left:3px !important;
            transition:transform .4s ease !important;
            box-shadow:0 2px 4px rgba(0,0,0,0.2) !important;
            display:block !important;content:none !important;
            padding:0 !important;margin:0 !important;
        }
        #wpadminbar .mg-active .mg-toggle-thumb {
            transform:translateX(18px) !important;
        }
        #wpadminbar .mg-toggle-label {
            font-size:10px !important;font-weight:700 !important;margin-left:6px !important;
            min-width:22px !important;text-align:center !important;letter-spacing:0.5px !important;
            transition:color .4s ease !important;display:inline !important;
            line-height:22px !important;padding:0 !important;
        }
        #wpadminbar .mg-active .mg-toggle-label { color:#4CAF50 !important; }
        #wpadminbar .mg-toggle-switch:not(.mg-active) .mg-toggle-label { color:rgba(255,255,255,0.5) !important; }
        /* Hover */
        #wpadminbar .mg-toggle-switch:hover .mg-toggle-track { background:rgba(255,255,255,0.35) !important; }
        #wpadminbar .mg-toggle-switch.mg-active:hover .mg-toggle-track { background:#43a047 !important;box-shadow:0 0 12px rgba(76,175,80,0.8),0 0 24px rgba(76,175,80,0.35) !important; }
        /* Loading */
        #wpadminbar .mg-toggle-switch.mg-loading .mg-toggle-track { opacity:.5 !important; }
        #wpadminbar .mg-toggle-switch.mg-loading { pointer-events:none !important; }
        </style>
        <script>
        (function(){
            if (typeof jQuery === 'undefined') return;
            jQuery(function($){
                var $toggle = $('#mg-adminbar-toggle');
                if (!$toggle.length) return;

                $toggle.on('click', function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    e.stopImmediatePropagation();
                    doToggle();
                    return false;
                });

                $(document).on('click', '#wp-admin-bar-mg-toggle a', function(e){
                    e.preventDefault();
                    doToggle();
                    return false;
                });

                function doToggle(){
                    if ($toggle.hasClass('mg-loading')) return;
                    
                    var isEnabled = $toggle.attr('data-enabled') === '1';
                    var newState = !isEnabled;

                    $toggle.addClass('mg-loading');

                    $.post(
                        '<?php echo esc_js(admin_url('admin-ajax.php')); ?>',
                        {
                            action: 'mg_toggle',
                            nonce: '<?php echo esc_js( wp_create_nonce('mg_nonce') ); ?>',
                            enabled: newState ? 'true' : 'false'
                        },
                        function(resp){
                            $toggle.removeClass('mg-loading');
                            if (resp && resp.success) {
                                var on = resp.data.enabled;
                                $toggle.attr('data-enabled', on ? '1' : '0');
                                $toggle.toggleClass('mg-active', on);
                                $toggle.find('.mg-toggle-label').text(on ? 'ON' : 'OFF');

                                var $sub = $('#wp-admin-bar-mg-toggle a');
                                if (on) {
                                    $sub.html('<span style="font-family:dashicons;font-size:16px;vertical-align:middle;margin-right:5px;color:#dc3545;" class="dashicons-no"></span><?php echo esc_js(__('Disable', 'maintenance-genius')); ?>');
                                } else {
                                    $sub.html('<span style="font-family:dashicons;font-size:16px;vertical-align:middle;margin-right:5px;color:#4CAF50;" class="dashicons-yes"></span><?php echo esc_js(__('Enable', 'maintenance-genius')); ?>');
                                }

                                var $pageToggle = $('#mg-toggle');
                                if ($pageToggle.length && $pageToggle.is(':checkbox')) {
                                    $pageToggle.prop('checked', on).trigger('change');
                                }

                                var $widgetDot = $('#mg_dashboard_widget .mg-dwc-dot');
                                if ($widgetDot.length) {
                                    $widgetDot.toggleClass('maintenance', on).toggleClass('live', !on);
                                    $('#mg_dashboard_widget .mg-dwc-status-text').text(on ? 'Maintenance Active' : 'Site Live');
                                    $('#mg_dashboard_widget .mg-dwc-status-sub').text(on ? 'Visitors see your maintenance page' : 'Maintenance mode is OFF');
                                }
                            }
                        }
                    ).fail(function(){
                        $toggle.removeClass('mg-loading');
                    });
                }
            });
        })();
        </script>
        <?php
    }

    /**
     * Ajouter le badge PRO au nom du plugin dans la liste des extensions (v2.9.43)
     * @param array $plugins
     * @return array
     */
    public static function add_pro_badge_to_name($plugins) {
        $plugin_file = plugin_basename(MG_PLUGIN_FILE);
        if (isset($plugins[$plugin_file]) && MG_License::is_valid()) {
            $plugins[$plugin_file]['Name'] .= ' <span style="background:#F97316;color:#fff;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700;margin-left:6px;vertical-align:middle;">PRO</span>';
        }
        return $plugins;
    }

    /**
     * Ajouter un lien PRO dans les meta du plugin (v2.9.43)
     * @param array  $links
     * @param string $file
     * @return array
     */
    public static function add_pro_row_meta($links, $file) {
        $plugin_file = plugin_basename(MG_PLUGIN_FILE);
        if ($file === $plugin_file && MG_License::is_valid()) {
            $links[] = '<span style="color:#F97316;font-weight:700;">✓ PRO</span>';
        }
        return $links;
    }

    // ============================================
    // DASHBOARD WIDGET — Monitoring Overview (v2.9.44)
    // ============================================

    /**
     * Enregistre le widget dans le tableau de bord WordPress
     */
    public static function add_dashboard_widget() {
        // Titre avec logo brand inline (img 16px) au lieu de l'emoji 🔧.
        // (sinon WordPress centre le titre seul et crée un gap visuel à côté du logo).
        $logo_img = '<img src="' . esc_url( MG_PLUGIN_URL . 'assets/images/mg-icon-256.png' ) . '" alt="" style="width:18px;height:18px;flex-shrink:0;">';
        $title_html = '<span style="display:inline-flex;align-items:center;gap:8px;">' . $logo_img . '<span>Maintenance GENIUS — ' . esc_html__( 'Site Status', 'maintenance-genius' ) . '</span></span>';
        wp_add_dashboard_widget(
            'mg_dashboard_widget',
            $title_html,
            [ __CLASS__, 'render_dashboard_widget' ]
        );
    }

    /**
     * Dispatcher v2.9.69 — bascule entre widget Core (par défaut) et widget Legacy monitoring.
     * Le widget Core est l'expérience standard WP.org-ready (sans dépendance monitoring).
     * Le widget Legacy reste accessible pour rétro-compat si MG_DISABLE_MONITORING_UI = false.
     */
    public static function render_dashboard_widget() {
        if ( defined( 'MG_DISABLE_MONITORING_UI' ) && ! MG_DISABLE_MONITORING_UI && class_exists( 'MG_Monitoring' ) ) {
            self::render_dashboard_widget_legacy();
            return;
        }
        self::render_dashboard_widget_core();
    }

    /**
     * v2.9.69 — Nouveau widget dashboard MG Core (pas de monitoring).
     * Affiche : status maintenance ON/OFF, stats visiteurs, maintenance planifiée,
     *           inscriptions notification, quick actions.
     * Branding chakra Racine #F97316.
     */
    public static function render_dashboard_widget_core() {
        $settings              = MG_Settings::load();
        $maintenance_active    = ! empty( $settings['maintenance_enabled'] );
        $scheduled_enabled     = ! empty( $settings['scheduled_enabled'] );
        $scheduled_start       = ! empty( $settings['scheduled_start'] ) ? $settings['scheduled_start'] : '';
        $stats_enabled         = ! empty( $settings['stats_enabled'] );
        $notification_enabled  = ! empty( $settings['notification_enabled'] );

        // Stats lecture (option safe, pas de query DB)
        $stats           = get_option( 'mg_visit_stats', [] );
        $blocked_count   = is_array( $stats ) && isset( $stats['blocked_count'] ) ? (int) $stats['blocked_count'] : 0;
        $notifications   = get_option( 'mg_notifications', [] );
        $notif_count     = is_array( $notifications ) ? count( $notifications ) : 0;

        $admin_url       = admin_url( 'admin.php?page=maintenance-genius' );
        $preview_url     = wp_nonce_url( add_query_arg( 'mg_preview', '1', home_url( '/' ) ), 'mg_preview' );

        // Dot status + label
        if ( $maintenance_active ) {
            $dot_class    = 'maintenance';
            $status_text  = __( 'Maintenance Active', 'maintenance-genius' );
            $status_sub   = __( 'Visitors see your maintenance page', 'maintenance-genius' );
        } else {
            $dot_class    = 'live';
            $status_text  = __( 'Site Live', 'maintenance-genius' );
            $status_sub   = __( 'Maintenance mode is OFF', 'maintenance-genius' );
        }
        ?>
        <style>
            #mg_dashboard_widget { border: 1px solid #F97316 !important; }
            #mg_dashboard_widget .inside { padding: 0 !important; margin: 0 !important; }
            .mg-dwc { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
            .mg-dwc-header { display: flex; align-items: center; gap: 12px; padding: 16px; border-bottom: 1px solid #e5e7eb; }
            .mg-dwc-dot { width: 14px; height: 14px; border-radius: 50%; flex-shrink: 0; }
            .mg-dwc-dot.live { background: #d1d5db; }
            .mg-dwc-dot.maintenance { background: #22c55e; box-shadow: 0 0 8px rgba(34,197,94,.7); animation: mg-pulse-strong 1.6s ease-in-out infinite; }
            @keyframes mg-pulse-strong { 0%,100% { opacity:1; } 50% { opacity:.05; } }
            .mg-dwc-status { flex: 1; }
            .mg-dwc-status-text { font-size: 14px; font-weight: 600; color: #1f2937; line-height: 1.2; }
            .mg-dwc-status-sub { font-size: 12px; color: #6b7280; margin-top: 2px; }
            .mg-dwc-grid { display: grid; grid-template-columns: 1fr 1fr; border-bottom: 1px solid #e5e7eb; }
            .mg-dwc-cell { padding: 12px 16px; }
            .mg-dwc-cell + .mg-dwc-cell { border-left: 1px solid #e5e7eb; }
            .mg-dwc-label { font-size: 10px; color: #9ca3af; text-transform: uppercase; letter-spacing: .6px; font-weight: 600; }
            .mg-dwc-value { font-size: 18px; color: #111827; font-weight: 700; margin-top: 4px; }
            .mg-dwc-value-sub { font-size: 11px; color: #6b7280; font-weight: 400; }
            .mg-dwc-info { padding: 10px 16px; font-size: 12px; color: #4b5563; border-bottom: 1px solid #e5e7eb; background: #fafafa; }
            .mg-dwc-info strong { color: #F97316; }
            .mg-dwc-actions { display: flex; gap: 8px; padding: 12px 16px; }
            .mg-dwc-btn { flex: 1; text-align: center; padding: 8px 10px; font-size: 12px; font-weight: 600; text-decoration: none; border-radius: 4px; transition: opacity .15s; }
            .mg-dwc-btn:hover { opacity: .85; }
            .mg-dwc-btn-primary { background: #F97316; color: #fff !important; }
            .mg-dwc-btn-secondary { background: #f3f4f6; color: #374151 !important; border: 1px solid #e5e7eb; }
            .mg-dwc-footer { padding: 6px 16px; border-top: 1px solid #f3f4f6; display: flex; justify-content: space-between; align-items: center; font-size: 10px; color: #9ca3af; background: #fafafa; }
            .mg-dwc-footer a { color: #F97316; text-decoration: none; font-weight: 500; }
            .mg-dwc-footer a:hover { text-decoration: underline; }
        </style>
        <div class="mg-dwc">
            <div class="mg-dwc-header">
                <div class="mg-dwc-dot <?php echo esc_attr( $dot_class ); ?>"></div>
                <div class="mg-dwc-status">
                    <div class="mg-dwc-status-text"><?php echo esc_html( $status_text ); ?></div>
                    <div class="mg-dwc-status-sub"><?php echo esc_html( $status_sub ); ?></div>
                </div>
            </div>

            <div class="mg-dwc-grid">
                <div class="mg-dwc-cell">
                    <div class="mg-dwc-label"><?php esc_html_e( 'Visitors Blocked', 'maintenance-genius' ); ?></div>
                    <div class="mg-dwc-value"><?php echo esc_html( number_format_i18n( $blocked_count ) ); ?></div>
                    <div class="mg-dwc-value-sub"><?php echo $stats_enabled ? esc_html__( 'tracking active', 'maintenance-genius' ) : esc_html__( 'tracking disabled', 'maintenance-genius' ); ?></div>
                </div>
                <div class="mg-dwc-cell">
                    <div class="mg-dwc-label"><?php esc_html_e( 'Subscribers', 'maintenance-genius' ); ?></div>
                    <div class="mg-dwc-value"><?php echo esc_html( number_format_i18n( $notif_count ) ); ?></div>
                    <div class="mg-dwc-value-sub"><?php echo $notification_enabled ? esc_html__( 'form active', 'maintenance-genius' ) : esc_html__( 'form disabled', 'maintenance-genius' ); ?></div>
                </div>
            </div>

            <?php if ( $scheduled_enabled && $scheduled_start ) : ?>
            <div class="mg-dwc-info">
                📅 <?php
                printf(
                    /* translators: %s: date and time of scheduled maintenance */
                    esc_html__( 'Scheduled maintenance: %s', 'maintenance-genius' ),
                    '<strong>' . esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $scheduled_start ) ) ) . '</strong>'
                ); ?>
            </div>
            <?php endif; ?>

            <div class="mg-dwc-actions">
                <a href="<?php echo esc_url( $admin_url ); ?>" class="mg-dwc-btn mg-dwc-btn-primary">
                    <?php esc_html_e( 'Open Settings', 'maintenance-genius' ); ?>
                </a>
                <a href="<?php echo esc_url( $preview_url ); ?>" class="mg-dwc-btn mg-dwc-btn-secondary" target="_blank" rel="noopener">
                    <?php esc_html_e( 'Preview Page', 'maintenance-genius' ); ?>
                </a>
            </div>

            <div class="mg-dwc-footer">
                <a href="https://maintenancegenius.ca" target="_blank" rel="noopener">maintenancegenius.ca</a>
                <span>v<?php echo esc_html( MG_VERSION ); ?></span>
            </div>
        </div>
        <?php
    }

    /**
     * Rendu HTML du widget dashboard LEGACY (avec monitoring)
     * Affiche: statut maintenance, monitoring status, dernier check, uptime events
     * Conservé pour rétro-compat si MG_DISABLE_MONITORING_UI = false
     */
    public static function render_dashboard_widget_legacy() {
        $settings = MG_Settings::load();
        $monitoring_enabled = !empty($settings['monitoring_enabled']);
        $maintenance_active = !empty($settings['maintenance_enabled']);
        $status = MG_Monitoring::get_status();
        $events = MG_Monitoring::get_events(5);

        // === Hook: Permet aux addons d'injecter des données supplémentaires (v2.9.44) ===
        $addon_data = apply_filters('mg_dashboard_widget_data', [], $settings, $status);

        ?>
        <style>
            #mg_monitoring_widget .inside { padding: 0 !important; }
            .mg-dw { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
            .mg-dw-header { display: flex; align-items: center; gap: 10px; padding: 14px 16px; border-bottom: 1px solid #e2e8f0; }
            .mg-dw-status-dot { width: 14px; height: 14px; border-radius: 50%; flex-shrink: 0; }
            .mg-dw-status-dot.up { background: #22c55e; box-shadow: 0 0 6px rgba(34,197,94,.5); }
            .mg-dw-status-dot.down { background: #ef4444; box-shadow: 0 0 6px rgba(239,68,68,.5); animation: mg-pulse 1.5s infinite; }
            .mg-dw-status-dot.unknown { background: #94a3b8; }
            .mg-dw-status-dot.maintenance { background: #f59e0b; box-shadow: 0 0 6px rgba(245,158,11,.4); }
            @keyframes mg-pulse { 0%,100% { opacity:1; } 50% { opacity:.5; } }
            .mg-dw-status-text { font-size: 14px; font-weight: 600; color: #1e293b; }
            .mg-dw-status-sub { font-size: 12px; color: #64748b; font-weight: 400; }
            .mg-dw-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0; border-bottom: 1px solid #e2e8f0; }
            .mg-dw-cell { padding: 10px 16px; }
            .mg-dw-cell:first-child { border-right: 1px solid #e2e8f0; }
            .mg-dw-label { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: .5px; margin-bottom: 2px; }
            .mg-dw-value { font-size: 13px; color: #334155; font-weight: 500; }
            .mg-dw-events { padding: 10px 16px; border-bottom: 1px solid #e2e8f0; }
            .mg-dw-events-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: .5px; margin-bottom: 8px; }
            .mg-dw-event { display: flex; align-items: center; gap: 8px; padding: 4px 0; font-size: 12px; color: #475569; }
            .mg-dw-event-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
            .mg-dw-event-dot.up { background: #22c55e; }
            .mg-dw-event-dot.down { background: #ef4444; }
            .mg-dw-footer { padding: 10px 16px; display: flex; justify-content: space-between; align-items: center; }
            .mg-dw-link { font-size: 12px; color: #F97316; text-decoration: none; font-weight: 500; }
            .mg-dw-link:hover { text-decoration: underline; }
            .mg-dw-version { font-size: 11px; color: #cbd5e1; }
            .mg-dw-badge { display: inline-block; font-size: 11px; padding: 2px 8px; border-radius: 4px; font-weight: 600; }
            .mg-dw-badge.on { background: #f0fdf4; color: #16a34a; }
            .mg-dw-badge.off { background: #fef2f2; color: #dc2626; }
            .mg-dw-badge.maint { background: #fffbeb; color: #d97706; }
            .mg-dw-disabled { padding: 16px; text-align: center; color: #94a3b8; font-size: 13px; }
            /* Addon sections hook (v2.9.44) */
            .mg-dw-addon-section { border-top: 1px solid #e2e8f0; padding: 10px 16px; }
        </style>
        <div class="mg-dw">

            <?php // === Status header === ?>
            <div class="mg-dw-header">
                <?php if (!$monitoring_enabled) : ?>
                    <span class="mg-dw-status-dot unknown"></span>
                    <div>
                        <div class="mg-dw-status-text"><?php esc_html_e('Monitoring disabled', 'maintenance-genius'); ?></div>
                        <div class="mg-dw-status-sub"><?php esc_html_e('Enable it in Maintenance GENIUS settings', 'maintenance-genius'); ?></div>
                    </div>
                <?php elseif ($maintenance_active) : ?>
                    <span class="mg-dw-status-dot maintenance"></span>
                    <div>
                        <div class="mg-dw-status-text"><?php esc_html_e('Maintenance mode active', 'maintenance-genius'); ?></div>
                        <div class="mg-dw-status-sub">
                            <?php echo !empty($status['is_down'])
                                ? esc_html__('Server error detected!', 'maintenance-genius')
                                : esc_html__('Site is in maintenance — monitoring OK', 'maintenance-genius'); ?>
                        </div>
                    </div>
                <?php elseif (!empty($status['is_down'])) : ?>
                    <span class="mg-dw-status-dot down"></span>
                    <div>
                        <div class="mg-dw-status-text"><?php esc_html_e('Site is DOWN', 'maintenance-genius'); ?> 🔴</div>
                        <div class="mg-dw-status-sub"><?php echo esc_html($status['error_message'] ?? ''); ?></div>
                    </div>
                <?php else : ?>
                    <span class="mg-dw-status-dot up"></span>
                    <div>
                        <div class="mg-dw-status-text"><?php esc_html_e('Site is UP', 'maintenance-genius'); ?> 🟢</div>
                        <div class="mg-dw-status-sub"><?php esc_html_e('All systems operational', 'maintenance-genius'); ?></div>
                    </div>
                <?php endif; ?>
            </div>

            <?php // === Info grid === ?>
            <div class="mg-dw-grid">
                <div class="mg-dw-cell">
                    <div class="mg-dw-label"><?php esc_html_e('Last check', 'maintenance-genius'); ?></div>
                    <div class="mg-dw-value">
                        <?php echo !empty($status['last_check']) ? esc_html($status['last_check']) : '—'; ?>
                    </div>
                </div>
                <div class="mg-dw-cell">
                    <div class="mg-dw-label"><?php esc_html_e('Monitoring', 'maintenance-genius'); ?></div>
                    <div class="mg-dw-value">
                        <?php if ($monitoring_enabled) : ?>
                            <span class="mg-dw-badge on"><?php esc_html_e('ON', 'maintenance-genius'); ?></span>
                            <?php
                            $interval = intval($settings['monitoring_interval'] ?? 5);
                            printf(
                                /* translators: %d: interval in minutes */
                                esc_html__('every %d min', 'maintenance-genius'),
                                esc_html( $interval )
                            );
                            ?>
                        <?php else : ?>
                            <span class="mg-dw-badge off"><?php esc_html_e('OFF', 'maintenance-genius'); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <?php // === Maintenance mode badge === ?>
            <div class="mg-dw-grid">
                <div class="mg-dw-cell">
                    <div class="mg-dw-label"><?php esc_html_e('Maintenance mode', 'maintenance-genius'); ?></div>
                    <div class="mg-dw-value">
                        <?php if ($maintenance_active) : ?>
                            <span class="mg-dw-badge maint"><?php esc_html_e('ACTIVE', 'maintenance-genius'); ?></span>
                        <?php else : ?>
                            <span class="mg-dw-badge on"><?php esc_html_e('Inactive', 'maintenance-genius'); ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="mg-dw-cell">
                    <div class="mg-dw-label"><?php esc_html_e('HTTP status', 'maintenance-genius'); ?></div>
                    <div class="mg-dw-value">
                        <?php echo !empty($status['last_code']) ? intval($status['last_code']) : '—'; ?>
                    </div>
                </div>
            </div>

            <?php // === Recent events === ?>
            <?php if ($monitoring_enabled && !empty($events)) : ?>
                <div class="mg-dw-events">
                    <div class="mg-dw-events-title"><?php esc_html_e('Recent events', 'maintenance-genius'); ?></div>
                    <?php foreach ($events as $event) : ?>
                        <div class="mg-dw-event">
                            <span class="mg-dw-event-dot <?php echo esc_attr($event['type']); ?>"></span>
                            <span>
                                <?php echo $event['type'] === 'down'
                                    ? '⬇ ' . esc_html__('Down', 'maintenance-genius')
                                    : '⬆ ' . esc_html__('Up', 'maintenance-genius'); ?>
                                — <?php echo esc_html($event['datetime'] ?? ''); ?>
                                <?php if (!empty($event['status_code'])) : ?>
                                    (HTTP <?php echo intval($event['status_code']); ?>)
                                <?php endif; ?>
                            </span>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php
            // === Hook: Addon sections (v2.9.44) ===
            // Permet aux addons PRO d'ajouter des sections (TTFB, uptime %, graphiques, etc.)
            do_action('mg_dashboard_widget_after_events', $settings, $status, $events);
            ?>

            <?php // === Footer === ?>
            <div class="mg-dw-footer">
                <a href="<?php echo esc_url(admin_url('admin.php?page=maintenance-genius')); ?>" class="mg-dw-link">
                    <?php esc_html_e('Open Maintenance GENIUS', 'maintenance-genius'); ?> →
                </a>
                <span class="mg-dw-version">v<?php echo esc_html(MG_VERSION); ?></span>
            </div>

            <?php
            // === Hook: Addon footer (v2.9.44) ===
            do_action('mg_dashboard_widget_footer', $settings, $status);
            ?>
        </div>
        <?php
    }

}
