<?php
/**
 * Name: Maintenance Mode
 * Description: Display professional maintenance page with countdown timer and custom styling to visitors while admins access site normally during updates or development work
 * Category: Utilities
 * Icon: -
 * UseCases: [
 *   {
 *     "title": "Add Useful Functionality",
 *     "description": "Extend WordPress with helpful tools that make site management easier."
 *   },
 *   {
 *     "title": "Save Time",
 *     "description": "Automate or simplify tasks that would otherwise require manual work or additional tools."
 *   }
 * ]
 * Added: 2025-06-20
 * Tags: maintenance, offline, downtime, repair
 * WhereToFind: {
 *   "location": "Frontend (Logged Out)",
 *   "url": "/",
 *   "instructions": "Visit site while logged out - maintenance page displays",
 *   "newTab": true
 * }
 */

// Prevent direct access
if (!defined('ABSPATH')) exit;

class SwitchboardMaintenanceModeEnhanced {
    
    public function __construct() {
        add_action('template_redirect', [$this, 'show_maintenance_page']);
        add_action('admin_bar_menu', [$this, 'add_admin_bar_notice'], 100);
        add_filter('rest_authentication_errors', [$this, 'maybe_block_rest_api'], 99);
    }

    /**
     * Block unauthenticated REST API requests during maintenance mode
     */
    public function maybe_block_rest_api($result) {
        // Don't override existing errors
        if (is_wp_error($result)) {
            return $result;
        }

        // Allow authenticated users
        if (is_user_logged_in()) {
            return $result;
        }

        $settings = get_option('switchboard_maintenance-mode-enhanced_settings', []);
        $enabled = isset($settings['enabled']) ? $settings['enabled'] : 0;
        if (!$enabled) {
            return $result;
        }

        return new WP_Error(
            'maintenance_mode',
            __('Site is under maintenance.', 'wpswitchboard'),
            ['status' => 503]
        );
    }

    /**
     * Get allowed roles with safe fallback to administrator
     *
     * Centralized helper to retrieve and validate allowed roles from settings.
     * Filters out empty values and '0' (from switchboard-checkbox behavior).
     * Always returns at least ['administrator'] to prevent lockout.
     *
     * @return array List of valid role slugs that can bypass maintenance mode
     */
    private function get_allowed_roles() {
        $settings = get_option('switchboard_maintenance-mode-enhanced_settings', []);
        $roles = isset($settings['allowed_roles']) && !empty($settings['allowed_roles'])
            ? array_filter($settings['allowed_roles'], function($role) {
                // Filter out empty values and '0' (switchboard-checkbox adds '=0' for unchecked boxes)
                return !empty($role) && $role !== '0';
            })
            : [];

        // Always fallback to administrator if no valid roles exist (prevent lockout)
        return !empty($roles) ? $roles : ['administrator'];
    }

    /**
     * Register data locations for this module
     */
    public function register_data_locations() {
        return [
            'options' => [
                'switchboard_maintenance-mode-enhanced_settings'
            ],
            'option_patterns' => [],
            'tables' => [],
            'post_meta' => [],
            'user_meta' => []
        ];
    }
    
    /**
     * Render settings panel for Maintenance Mode Enhanced
     *
     * Displays comprehensive settings interface for maintenance mode with:
     * - Prominent enable/disable checkbox with warning styling
     * - Logo upload capability using WordPress media uploader
     * - Image preview with remove functionality
     * - Customizable page title and message text inputs
     * - Color pickers for background, text, and accent colors (brand matching)
     * - Optional countdown timer with datetime picker for estimated completion
     * - Clear explanatory descriptions and professional layout
     *
     * The interface uses a highlighted alert-style box at the top to make the enable
     * toggle highly visible, preventing accidental activation. The logo uploader
     * integrates with wp.media for native WordPress media library experience, with
     * conditional display logic showing/hiding the remove button based on whether
     * a logo is selected. Three color pickers provide complete visual customization
     * to match site branding. The countdown timer feature helps set visitor
     * expectations during planned maintenance. When enabled, the module displays
     * a beautiful, animated maintenance page to all non-admin visitors while admins
     * can continue working normally. This is essential for scheduled updates,
     * development work, or when making significant site changes.
     *
     * @param array $settings Current module settings with 'enabled', 'title', 'message', 'logo_id', 'bg_color', 'text_color', 'accent_color', 'show_timer', 'end_time' keys
     * @return void Outputs HTML directly
     */
    public function render_settings($settings = []) {
        // Get settings from JSON structure
        $enabled = isset($settings['enabled']) ? $settings['enabled'] : 0;
        $title = isset($settings['title']) ? wp_unslash($settings['title']) : "We'll Be Back Soon";
        $message = isset($settings['message']) ? wp_unslash($settings['message']) : 'Our site is currently undergoing scheduled maintenance. We apologize for any inconvenience.';
        $logo_id = isset($settings['logo_id']) ? $settings['logo_id'] : '';
        $logo_url = $logo_id ? wp_get_attachment_url($logo_id) : '';
        $bg_type = isset($settings['bg_type']) ? $settings['bg_type'] : 'color';
        $bg_color = !empty($settings['bg_color']) ? $settings['bg_color'] : '#1e293b';
        $bg_image_id = isset($settings['bg_image_id']) ? $settings['bg_image_id'] : '';
        $bg_image_url = $bg_image_id ? wp_get_attachment_url($bg_image_id) : '';
        $text_color = !empty($settings['text_color']) ? $settings['text_color'] : '#ffffff';
        $accent_color = !empty($settings['accent_color']) ? $settings['accent_color'] : '#f59e0b';
        $show_timer = isset($settings['show_timer']) ? $settings['show_timer'] : 0;
        $end_time = isset($settings['end_time']) ? $settings['end_time'] : '';
        $auto_disable = isset($settings['auto_disable']) ? $settings['auto_disable'] : 1; // Default to auto-disable
        $allowed_roles = $this->get_allowed_roles();
        $custom_login_url = isset($settings['custom_login_url']) ? trim($settings['custom_login_url']) : '';
        $badge_text = isset($settings['badge_text']) ? wp_unslash($settings['badge_text']) : 'Under Maintenance';
        $social_facebook = isset($settings['social_facebook']) ? trim($settings['social_facebook']) : '';
        $social_twitter = isset($settings['social_twitter']) ? trim($settings['social_twitter']) : '';
        $social_instagram = isset($settings['social_instagram']) ? trim($settings['social_instagram']) : '';
        $social_linkedin = isset($settings['social_linkedin']) ? trim($settings['social_linkedin']) : '';
        
        $html = '
            <input type="hidden" name="module" value="maintenance-mode-enhanced">

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <h3 class="sb-sp-heading">' . esc_html__('Maintenance Mode', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Display a professional maintenance page to visitors while you perform updates or development work.', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 24px;">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title">' . esc_html__('Enable Maintenance Mode', 'wpswitchboard') . '</strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="setting_enabled" value="1" ' . checked($enabled, 1, false) . '>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                    <p class="sb-module-option-text">' . esc_html__('Visitors will see the maintenance page. Users with allowed roles can still access the site normally.', 'wpswitchboard') . '</p>
                </div>
            </div>

            <div style="margin-bottom: 24px;">
                <button type="button" id="maintenance-preview-btn" class="button button-secondary" style="display: inline-flex; align-items: center; gap: 6px;">
                    <span class="dashicons dashicons-visibility" style="font-size: 16px; width: 16px; height: 16px;"></span>
                    ' . esc_html__('Preview Maintenance Page', 'wpswitchboard') . '
                </button>
                <p class="sb-sp-description" style="margin-top: 8px;">' . esc_html__('Preview your maintenance page in a new tab without enabling it.', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
                <div class="sb-sp-field-horizontal-left">
                    <label class="sb-sp-label">' . esc_html__('Logo', 'wpswitchboard') . '</label>
                    <p class="sb-sp-description">' . esc_html__('Optional logo to display on the maintenance page', 'wpswitchboard') . '</p>
                </div>
                <div>
                    <div id="maintenance-enhanced-logo-preview" style="margin-bottom: 12px;">';

        if ($logo_url) {
            $html .= '<img src="' . esc_url($logo_url) . '" style="max-width: 200px; height: auto; border-radius: 8px; display: block; border: 1px solid #e5e7eb; padding: 8px; background: #ffffff;">';
        }

        $html .= '</div>
                    <div class="sb-sp-button-group" style="display: flex; flex-direction: row; justify-content: flex-start; gap: 8px; align-items: center;">
                        <button type="button" class="button button-secondary button-small upload-logo-btn" data-target="maintenance-enhanced">' . esc_html__('Select Logo', 'wpswitchboard') . '</button>';
        if ($logo_id) {
            $html .= '<button type="button" class="button button-small remove-logo-btn" data-target="maintenance-enhanced">' . esc_html__('Remove Logo', 'wpswitchboard') . '</button>';
        }
        $html .= '</div>
                    <input type="hidden" id="setting_logo" name="setting_logo" value="' . esc_attr($logo_id) . '">
                </div>
            </div>

            <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
                <div class="sb-sp-field-horizontal-left">
                    <label for="setting_title" class="sb-sp-label">' . esc_html__('Page Title', 'wpswitchboard') . '</label>
                    <p class="sb-sp-description">' . esc_html__('Main heading shown to visitors', 'wpswitchboard') . '</p>
                </div>
                <input type="text" name="setting_title" id="setting_title" value="' . esc_attr($title) . '" class="sb-sp-input">
            </div>

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <label for="setting_message" class="sb-sp-label">' . esc_html__('Message', 'wpswitchboard') . '</label>
                <textarea name="setting_message" id="setting_message" rows="4" class="sb-sp-textarea sb-sp-w-full">' . esc_textarea($message) . '</textarea>
                <p class="sb-sp-description">' . esc_html__('Explanation message displayed to visitors', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 24px;">
                <div class="sb-sp-field-horizontal-left">
                    <label for="setting_badge_text" class="sb-sp-label">' . esc_html__('Status Badge', 'wpswitchboard') . '</label>
                    <p class="sb-sp-description">' . esc_html__('Text shown in the colored badge above the title', 'wpswitchboard') . '</p>
                </div>
                <input type="text" name="setting_badge_text" id="setting_badge_text" value="' . esc_attr($badge_text) . '" class="sb-sp-input" placeholder="Under Maintenance">
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 16px;">
                <h3 class="sb-sp-heading">' . esc_html__('Background Settings', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Choose between a solid color or background image for your maintenance page', 'wpswitchboard') . '</p>
            </div>

            <div class="switchboard-bg-type-tabs">
                <label class="switchboard-bg-tab ' . ($bg_type === 'color' ? 'active' : '') . '" data-type="color">
                    <input type="radio" name="setting_bg_type" value="color" ' . checked($bg_type, 'color', false) . '>
                    <span>' . esc_html__('Color', 'wpswitchboard') . '</span>
                </label>
                <label class="switchboard-bg-tab ' . ($bg_type === 'image' ? 'active' : '') . '" data-type="image">
                    <input type="radio" name="setting_bg_type" value="image" ' . checked($bg_type, 'image', false) . '>
                    <span>' . esc_html__('Image', 'wpswitchboard') . '</span>
                </label>
            </div>

            <div id="color-settings" class="switchboard-bg-settings" style="display: ' . ($bg_type === 'color' ? 'block' : 'none') . ';">
                <label for="setting_bg_color" class="sb-sp-label">' . esc_html__('Background Color', 'wpswitchboard') . '</label>
                <div class="sb-sp-flex sb-sp-gap-2" style="margin-bottom: 20px;">
                    <input type="color" name="setting_bg_color" id="setting_bg_color" value="' . esc_attr($bg_color) . '" data-default="#1e293b" style="width: 80px; height: 40px; border: 2px solid #ddd; border-radius: 8px; cursor: pointer;">
                    <input type="text" id="setting_bg_color_hex" value="' . esc_attr($bg_color) . '" class="sb-sp-input sb-sp-flex-1" maxlength="7" placeholder="#000000">
                </div>
            </div>

            <div id="image-settings" class="switchboard-bg-settings" style="display: ' . ($bg_type === 'image' ? 'block' : 'none') . ';">
                <label class="sb-sp-label">' . esc_html__('Background Image', 'wpswitchboard') . '</label>
                <div id="maintenance-enhanced-bg-preview" class="switchboard-image-preview">';

        if ($bg_image_url) {
            $html .= '<img src="' . esc_url($bg_image_url) . '" alt="Background preview">';
        } else {
            $html .= '<div class="switchboard-image-placeholder">
                        <span class="dashicons dashicons-format-image" style="font-size: 48px; opacity: 0.3;"></span>
                        <p>' . esc_html__('No image selected', 'wpswitchboard') . '</p>
                      </div>';
        }

        $html .= '</div>
                <input type="hidden" id="setting_bg_image" name="setting_bg_image" value="' . esc_attr($bg_image_id) . '">
                <div class="switchboard-image-actions">
                    <button type="button" class="button button-secondary button-small upload-bg-btn" data-target="maintenance-enhanced">' . esc_html__('Select Image', 'wpswitchboard') . '</button>
                    <button type="button" class="button button-small remove-bg-btn" data-target="maintenance-enhanced" style="display:' . ($bg_image_id ? 'inline-block' : 'none') . ';">' . esc_html__('Remove', 'wpswitchboard') . '</button>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 16px;">
                <h3 class="sb-sp-heading">' . esc_html__('Color Scheme', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Customize text and accent colors', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-sp-group" style="margin-bottom: 20px;">
                <label for="setting_text_color" class="sb-sp-label">' . esc_html__('Text Color', 'wpswitchboard') . '</label>
                <div class="sb-sp-flex sb-sp-gap-2">
                    <input type="color" name="setting_text_color" id="setting_text_color" value="' . esc_attr($text_color) . '" data-default="#ffffff" style="width: 80px; height: 40px; border: 2px solid #ddd; border-radius: 8px; cursor: pointer;">
                    <input type="text" id="setting_text_color_hex" value="' . esc_attr($text_color) . '" class="sb-sp-input sb-sp-flex-1" maxlength="7" placeholder="#000000">
                </div>
            </div>

            <div class="sb-sp-group" style="margin-bottom: 24px;">
                <label for="setting_accent_color" class="sb-sp-label">' . esc_html__('Accent Color', 'wpswitchboard') . '</label>
                <div class="sb-sp-flex sb-sp-gap-2">
                    <input type="color" name="setting_accent_color" id="setting_accent_color" value="' . esc_attr($accent_color) . '" data-default="#3b82f6" style="width: 80px; height: 40px; border: 2px solid #ddd; border-radius: 8px; cursor: pointer;">
                    <input type="text" id="setting_accent_color_hex" value="' . esc_attr($accent_color) . '" class="sb-sp-input sb-sp-flex-1" maxlength="7" placeholder="#000000">
                </div>
                <p class="sb-sp-description">' . esc_html__('Used for highlights and decorative elements', 'wpswitchboard') . '</p>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <!-- Collapsible: User Access Control -->
            <div class="sb-collapsible-section" data-collapsed="true">
                <div class="sb-collapsible-header" onclick="toggleCollapsible(this)">
                    <div>
                        <h3 class="sb-sp-heading" style="margin: 0;">' . esc_html__('User Access Control', 'wpswitchboard') . '</h3>
                        <p class="sb-sp-description" style="margin: 4px 0 0 0;">' . esc_html__('Select which user roles can bypass maintenance mode', 'wpswitchboard') . '</p>
                    </div>
                    <span class="dashicons dashicons-arrow-down-alt2 sb-collapsible-icon"></span>
                </div>
                <div class="sb-collapsible-content" style="display: none;">';

        // Get all WordPress roles
        global $wp_roles;
        if (!isset($wp_roles)) {
            $wp_roles = new WP_Roles();
        }

        $html .= '<div style="display: flex; flex-direction: column; gap: 12px; margin-top: 16px;">';

        if (isset($wp_roles->roles) && is_array($wp_roles->roles)) {
            foreach ($wp_roles->roles as $role_slug => $role_info) {
                $checked = in_array($role_slug, $allowed_roles) ? 'checked' : '';
                $html .= '
                    <div class="sb-module-option-item sb-module-toggle-item">
                        <div class="sb-module-option-content">
                            <div class="sb-module-toggle-header">
                                <strong class="sb-module-option-title">' . esc_html($role_info['name']) . '</strong>
                                <label class="sb-module-toggle">
                                    <input type="checkbox" name="setting_allowed_roles[]" value="' . esc_attr($role_slug) . '" ' . $checked . '>
                                    <span class="sb-module-toggle-slider"></span>
                                </label>
                            </div>
                        </div>
                    </div>';
            }
        } else {
            $html .= '<div class="sb-sp-info-box sb-sp-info-box-error">
                <p style="margin: 0; color: #dc2626;">' . esc_html__('Error: Unable to load WordPress roles. Administrator access will be used as fallback.', 'wpswitchboard') . '</p>
            </div>';
        }

        $html .= '</div>
                <p class="sb-sp-description" style="margin-top: 16px;">' . esc_html__('Users with selected roles will see the normal site. All others will see the maintenance page.', 'wpswitchboard') . '</p>
                <div style="text-align: right; margin-top: 12px;">
                    <button type="button" class="button button-secondary button-small" onclick="resetMaintenanceRolesToDefault()" style="display: inline-flex; align-items: center; gap: 4px;">
                        <span class="dashicons dashicons-image-rotate" style="font-size: 14px; width: 14px; height: 14px;"></span>
                        ' . esc_html__('Reset to Admin Only', 'wpswitchboard') . '
                    </button>
                </div>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <!-- Collapsible: Custom Login Page -->
            <div class="sb-collapsible-section" data-collapsed="true">
                <div class="sb-collapsible-header" onclick="toggleCollapsible(this)">
                    <div>
                        <h3 class="sb-sp-heading" style="margin: 0;">' . esc_html__('Custom Login Page', 'wpswitchboard') . '</h3>
                        <p class="sb-sp-description" style="margin: 4px 0 0 0;">' . esc_html__('Keep your custom login page accessible during maintenance', 'wpswitchboard') . '</p>
                    </div>
                    <span class="dashicons dashicons-arrow-down-alt2 sb-collapsible-icon"></span>
                </div>
                <div class="sb-collapsible-content" style="display: none;">';

        // Check if Hide My Login module is enabled and active
        $active_modules = get_option('switchboard_active_modules', []);
        $hide_my_login_active = in_array('hide-my-login', $active_modules);
        $hide_my_login_settings = get_option('switchboard_hide-my-login_settings', []);
        $hide_my_login_slug = isset($hide_my_login_settings['custom_slug']) ? trim($hide_my_login_settings['custom_slug']) : '';

        if ($hide_my_login_active && !empty($hide_my_login_slug)) {
            $html .= '
            <div class="sb-sp-info-box sb-sp-info-box-success" style="margin-bottom: 16px;">
                <p style="margin: 0;"><strong>' . esc_html__('Hide My Login Integration Active', 'wpswitchboard') . '</strong></p>
                <p style="margin: 8px 0 0 0;">' . sprintf(
                    esc_html__('Your custom login URL %s will automatically be excluded from maintenance mode.', 'wpswitchboard'),
                    '<code>/' . esc_html($hide_my_login_slug) . '</code>'
                ) . '</p>
            </div>';
        }

        $html .= '
            <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 16px;">
                <div class="sb-sp-field-horizontal-left">
                    <label for="setting_custom_login_url" class="sb-sp-label">' . esc_html__('Additional Custom Login URL', 'wpswitchboard') . '</label>
                    <p class="sb-sp-description">' . esc_html__('For other security plugins (WPS Hide Login, iThemes Security, etc.), enter the path here (e.g., /my-login)', 'wpswitchboard') . '</p>
                </div>
                <input type="text" name="setting_custom_login_url" id="setting_custom_login_url" value="' . esc_attr($custom_login_url) . '" class="sb-sp-input" placeholder="/my-login">
            </div>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 16px;">
                <h3 class="sb-sp-heading">' . esc_html__('Countdown Timer', 'wpswitchboard') . '</h3>
            </div>

            <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 16px;">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title">' . esc_html__('Show Countdown Timer', 'wpswitchboard') . '</strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="setting_show_timer" value="1" ' . checked($show_timer, 1, false) . '>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                    <p class="sb-module-option-text">' . esc_html__('Display a countdown timer showing time remaining until maintenance is complete', 'wpswitchboard') . '</p>
                </div>
            </div>

            <div class="sb-sp-group sb-sp-field-horizontal" style="margin-bottom: 16px;">
                <div class="sb-sp-field-horizontal-left">
                    <label for="setting_end_time" class="sb-sp-label">' . esc_html__('Estimated End Time', 'wpswitchboard') . '</label>
                    <p class="sb-sp-description">' . esc_html__('When will maintenance be complete? This will be displayed in the countdown timer.', 'wpswitchboard') . '</p>
                </div>
                <input type="datetime-local" name="setting_end_time" id="setting_end_time" value="' . esc_attr($end_time) . '" class="sb-sp-input" style="width: 300px;">
            </div>

            <div class="sb-module-option-item sb-module-toggle-item" style="margin-bottom: 24px;">
                <div class="sb-module-option-content">
                    <div class="sb-module-toggle-header">
                        <strong class="sb-module-option-title">' . esc_html__('Auto-disable when timer ends', 'wpswitchboard') . '</strong>
                        <label class="sb-module-toggle">
                            <input type="checkbox" name="setting_auto_disable" value="1" ' . checked($auto_disable, 1, false) . '>
                            <span class="sb-module-toggle-slider"></span>
                        </label>
                    </div>
                    <p class="sb-module-option-text">' . esc_html__('Automatically disable maintenance mode when the countdown reaches zero. If unchecked, visitors will see "Maintenance complete!" but the page will remain active.', 'wpswitchboard') . '</p>
                </div>
            </div>

            <div class="sb-sp-divider" style="margin: 24px 0;"></div>

            <div class="sb-sp-group" style="margin-bottom: 16px;">
                <h3 class="sb-sp-heading">' . esc_html__('Social Links', 'wpswitchboard') . '</h3>
                <p class="sb-sp-description">' . esc_html__('Add social media links to your maintenance page (leave empty to hide)', 'wpswitchboard') . '</p>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px;">
                <div class="sb-sp-group">
                    <label for="setting_social_facebook" class="sb-sp-label" style="display: flex; align-items: center; gap: 6px;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="#1877F2"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
                        ' . esc_html__('Facebook', 'wpswitchboard') . '
                    </label>
                    <input type="url" name="setting_social_facebook" id="setting_social_facebook" value="' . esc_attr($social_facebook) . '" class="sb-sp-input" placeholder="https://facebook.com/yourpage">
                </div>
                <div class="sb-sp-group">
                    <label for="setting_social_twitter" class="sb-sp-label" style="display: flex; align-items: center; gap: 6px;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="#000000"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
                        ' . esc_html__('X (Twitter)', 'wpswitchboard') . '
                    </label>
                    <input type="url" name="setting_social_twitter" id="setting_social_twitter" value="' . esc_attr($social_twitter) . '" class="sb-sp-input" placeholder="https://x.com/yourhandle">
                </div>
                <div class="sb-sp-group">
                    <label for="setting_social_instagram" class="sb-sp-label" style="display: flex; align-items: center; gap: 6px;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="#E4405F"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/></svg>
                        ' . esc_html__('Instagram', 'wpswitchboard') . '
                    </label>
                    <input type="url" name="setting_social_instagram" id="setting_social_instagram" value="' . esc_attr($social_instagram) . '" class="sb-sp-input" placeholder="https://instagram.com/yourhandle">
                </div>
                <div class="sb-sp-group">
                    <label for="setting_social_linkedin" class="sb-sp-label" style="display: flex; align-items: center; gap: 6px;">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="#0A66C2"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
                        ' . esc_html__('LinkedIn', 'wpswitchboard') . '
                    </label>
                    <input type="url" name="setting_social_linkedin" id="setting_social_linkedin" value="' . esc_attr($social_linkedin) . '" class="sb-sp-input" placeholder="https://linkedin.com/company/yourcompany">
                </div>
            </div>

            <style>
            /* Background Type Tabs */
            .switchboard-bg-type-tabs {
                display: flex;
                gap: 0;
                margin-bottom: 0;
                border: 1px solid var(--primary-100);
                border-radius: 8px 8px 0 0;
                overflow: hidden;
                background: #f8fafc;
            }

            .switchboard-bg-tab {
                flex: 1;
                position: relative;
                cursor: pointer;
                transition: all 0.2s ease;
            }

            .switchboard-bg-tab input[type="radio"] {
                position: absolute;
                opacity: 0;
                pointer-events: none;
            }

            .switchboard-bg-tab span {
                display: block;
                padding: 10px 20px;
                text-align: center;
                font-weight: 500;
                font-size: 14px;
                color: #64748b;
                transition: all 0.2s ease;
            }

            .switchboard-bg-tab:hover span {
                background: #f1f5f9;
                color: #334155;
            }

            .switchboard-bg-tab.active span {
                background: white;
                color: var(--primary-500);
                border-bottom: 2px solid var(--primary-500);
            }

            .switchboard-bg-settings {
                padding: 20px;
                background: white;
                border: 1px solid var(--primary-100);
                border-top: none;
                border-radius: 0 0 8px 8px;
                margin-bottom: 24px;
            }

            .switchboard-image-preview {
                margin-bottom: 16px;
                border-radius: 8px;
                overflow: hidden;
                border: 1px solid #e5e7eb;
                background: #f9fafb;
                min-height: 200px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .switchboard-image-preview img {
                max-width: 100%;
                height: auto;
                display: block;
            }

            .switchboard-image-placeholder {
                text-align: center;
                padding: 40px;
                color: #94a3b8;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
            }

            .switchboard-image-placeholder .dashicons {
                font-size: 48px;
                width: 48px;
                height: 48px;
                opacity: 0.4;
                color: #94a3b8;
            }

            .switchboard-image-placeholder p {
                margin-top: 12px;
                font-size: 14px;
                color: #94a3b8;
            }

            .switchboard-image-actions {
                display: flex;
                flex-direction: row;
                flex-wrap: nowrap;
                gap: 8px;
                align-items: center;
            }

            .switchboard-image-actions .button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
                white-space: nowrap;
            }

            /* Collapsible Sections */
            .sb-collapsible-section {
                border: 1px solid #e5e7eb;
                border-radius: 8px;
                overflow: hidden;
                margin-bottom: 0;
            }
            .sb-collapsible-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px 20px;
                background: #f9fafb;
                cursor: pointer;
                transition: background 0.2s ease;
            }
            .sb-collapsible-header:hover {
                background: #f1f5f9;
            }
            .sb-collapsible-icon {
                transition: transform 0.2s ease;
                color: #64748b;
            }
            .sb-collapsible-section[data-collapsed="false"] .sb-collapsible-icon {
                transform: rotate(180deg);
            }
            .sb-collapsible-content {
                padding: 20px;
                background: white;
                border-top: 1px solid #e5e7eb;
            }
            </style>

            <script>
            jQuery(document).ready(function($) {
                // Background type tab switching
                $(".switchboard-bg-tab").on("click", function() {
                    var type = $(this).data("type");

                    // Update tabs
                    $(".switchboard-bg-tab").removeClass("active");
                    $(this).addClass("active");

                    // Update radio
                    $(this).find("input[type=radio]").prop("checked", true);

                    // Toggle settings panels
                    if (type === "color") {
                        $("#color-settings").show();
                        $("#image-settings").hide();
                    } else {
                        $("#color-settings").hide();
                        $("#image-settings").show();
                    }
                });

                // Bidirectional sync between color pickers and hex inputs
                function syncColorPicker(colorInput, hexInput) {
                    // Color picker -> Hex input
                    $(colorInput).on("input change", function() {
                        $(hexInput).val($(this).val());
                    });
                    // Hex input -> Color picker
                    $(hexInput).on("input change", function() {
                        var val = $(this).val();
                        // Validate hex format
                        if (/^#[0-9A-Fa-f]{6}$/.test(val)) {
                            $(colorInput).val(val);
                        }
                    });
                }
                syncColorPicker("#setting_bg_color", "#setting_bg_color_hex");
                syncColorPicker("#setting_text_color", "#setting_text_color_hex");
                syncColorPicker("#setting_accent_color", "#setting_accent_color_hex");

                // Note: Background image and logo upload/removal handlers are in switchboard-admin.js
                // They use generic selectors: .upload-bg-btn, .remove-bg-btn, .upload-logo-btn, .remove-logo-btn
                // with data-target="maintenance-enhanced" to identify this module

                // Preview button handler
                $("#maintenance-preview-btn").on("click", function() {
                    // Open preview in new tab with preview parameter
                    var previewUrl = window.location.origin + "/?switchboard_maintenance_preview=1";
                    window.open(previewUrl, "_blank");
                });
            });

            // Collapsible section toggle
            function toggleCollapsible(header) {
                var section = header.parentElement;
                var content = section.querySelector(".sb-collapsible-content");
                var isCollapsed = section.getAttribute("data-collapsed") === "true";

                if (isCollapsed) {
                    content.style.display = "block";
                    section.setAttribute("data-collapsed", "false");
                } else {
                    content.style.display = "none";
                    section.setAttribute("data-collapsed", "true");
                }
            }

            function resetMaintenanceRolesToDefault() {
                // Uncheck all role checkboxes
                document.querySelectorAll(\'input[name="setting_allowed_roles[]"]\').forEach(function(checkbox) {
                    checkbox.checked = false;
                });
                // Check only administrator
                const adminCheckbox = document.querySelector(\'input[name="setting_allowed_roles[]"][value="administrator"]\');
                if (adminCheckbox) {
                    adminCheckbox.checked = true;
                }
            }
            </script>
        ';
        echo $html;
    }
    
    public function show_maintenance_page() {
        // Get settings from JSON structure
        $settings = get_option('switchboard_maintenance-mode-enhanced_settings', []);

        // Check for preview mode (only for admins)
        $is_preview = isset($_GET['switchboard_maintenance_preview']) && $_GET['switchboard_maintenance_preview'] === '1';
        if ($is_preview && current_user_can('manage_options')) {
            // Skip all checks for preview mode - go directly to rendering
        } else {
            // Normal mode - run all checks
            $enabled = isset($settings['enabled']) ? $settings['enabled'] : 0;
            if (!$enabled) {
                return;
            }

            // Check if countdown timer has ended and auto-disable is enabled
            $show_timer = isset($settings['show_timer']) ? $settings['show_timer'] : 0;
            $end_time = isset($settings['end_time']) ? $settings['end_time'] : '';
            $auto_disable = isset($settings['auto_disable']) ? $settings['auto_disable'] : 1;

            if ($show_timer && !empty($end_time) && $auto_disable) {
                $wp_timezone = wp_timezone();
                try {
                    $end_datetime = new DateTime($end_time, $wp_timezone);
                    $end_timestamp = $end_datetime->getTimestamp();
                    $current_timestamp = time();

                    if ($end_timestamp <= $current_timestamp) {
                        $settings['enabled'] = 0;
                        $settings['end_time'] = '';
                        $settings['show_timer'] = 0;
                        update_option('switchboard_maintenance-mode-enhanced_settings', $settings);
                        return;
                    }
                } catch (Exception $e) {
                    // Invalid date format, continue showing maintenance page
                }
            }

            // Always exclude core WordPress access paths
            $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
            $request_path = parse_url($request_uri, PHP_URL_PATH);

            if (strpos($request_path, 'wp-login.php') !== false) {
                return;
            }
            if (strpos($request_path, '/wp-admin') !== false) {
                return;
            }
            if (strpos($request_path, 'admin-ajax.php') !== false) {
                return;
            }
            if (strpos($request_path, '/wp-json/') !== false) {
                if (is_user_logged_in()) {
                    return;
                }
                // Return proper JSON response for non-authenticated REST API requests
                if (!headers_sent()) {
                    header('HTTP/1.1 503 Service Unavailable');
                    header('Content-Type: application/json; charset=UTF-8');
                    header('Retry-After: 3600');
                    nocache_headers();
                }
                echo wp_json_encode([
                    'code' => 'maintenance_mode',
                    'message' => __('Site is under maintenance.', 'wpswitchboard'),
                    'data' => ['status' => 503],
                ]);
                exit;
            }

            // Build list of custom login URLs to exclude
            $excluded_login_urls = [];
            $active_modules = get_option('switchboard_active_modules', []);
            if (in_array('hide-my-login', $active_modules)) {
                $hide_my_login_settings = get_option('switchboard_hide-my-login_settings', []);
                $hide_my_login_slug = isset($hide_my_login_settings['custom_slug']) ? trim($hide_my_login_settings['custom_slug']) : '';
                if (!empty($hide_my_login_slug)) {
                    $excluded_login_urls[] = $hide_my_login_slug;
                }
            }

            $custom_login_url = isset($settings['custom_login_url']) ? trim($settings['custom_login_url']) : '';
            if (!empty($custom_login_url)) {
                $excluded_login_urls[] = trim($custom_login_url, '/');
            }

            if (!empty($excluded_login_urls)) {
                $request_path = trim($request_path, '/');
                $home_path = trim(parse_url(home_url(), PHP_URL_PATH), '/');
                if (!empty($home_path) && strpos($request_path, $home_path) === 0) {
                    $request_path = trim(substr($request_path, strlen($home_path)), '/');
                }

                foreach ($excluded_login_urls as $login_path) {
                    if ($request_path === $login_path || strpos($request_path, $login_path . '/') === 0) {
                        return;
                    }
                }
            }

            // Check if user has any of the allowed roles
            $allowed_roles = $this->get_allowed_roles();
            $user = wp_get_current_user();
            if ($user && is_array($user->roles)) {
                foreach ($user->roles as $user_role) {
                    if (in_array($user_role, $allowed_roles)) {
                        return;
                    }
                }
            }
        }

        $title = isset($settings['title']) ? wp_unslash($settings['title']) : "We'll Be Back Soon";
        $message = isset($settings['message']) ? wp_unslash($settings['message']) : 'Our site is currently undergoing scheduled maintenance. We apologize for any inconvenience.';
        $logo_id = isset($settings['logo_id']) ? $settings['logo_id'] : '';
        $logo_url = $logo_id ? wp_get_attachment_url($logo_id) : '';
        $bg_type = isset($settings['bg_type']) ? $settings['bg_type'] : 'color';
        $bg_color = isset($settings['bg_color']) ? $settings['bg_color'] : '#1e293b';
        $bg_image_id = isset($settings['bg_image_id']) ? $settings['bg_image_id'] : '';
        $bg_image_url = $bg_image_id ? wp_get_attachment_url($bg_image_id) : '';
        $text_color = isset($settings['text_color']) ? $settings['text_color'] : '#ffffff';
        $accent_color = isset($settings['accent_color']) ? $settings['accent_color'] : '#f59e0b';
        $show_timer = isset($settings['show_timer']) ? $settings['show_timer'] : 0;
        $end_time = isset($settings['end_time']) ? $settings['end_time'] : '';
        $badge_text = isset($settings['badge_text']) ? wp_unslash($settings['badge_text']) : 'Under Maintenance';
        $social_facebook = isset($settings['social_facebook']) ? trim($settings['social_facebook']) : '';
        $social_twitter = isset($settings['social_twitter']) ? trim($settings['social_twitter']) : '';
        $social_instagram = isset($settings['social_instagram']) ? trim($settings['social_instagram']) : '';
        $social_linkedin = isset($settings['social_linkedin']) ? trim($settings['social_linkedin']) : '';
        $has_social_links = !empty($social_facebook) || !empty($social_twitter) || !empty($social_instagram) || !empty($social_linkedin);

        // Set proper HTTP status for SEO (503 Service Unavailable) - skip for preview
        $is_admin_preview = $is_preview && current_user_can('manage_options');
        if (!$is_admin_preview && !headers_sent()) {
            header('HTTP/1.1 503 Service Unavailable');
            header('Status: 503 Service Unavailable');
            // Tell search engines to retry in 1 hour
            header('Retry-After: 3600');
            nocache_headers();
        }

        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title><?php echo esc_html($title); ?></title>
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
                    <?php if ($bg_type === 'image' && $bg_image_url): ?>
                    background: url('<?php echo esc_url($bg_image_url); ?>') center center / cover no-repeat fixed;
                    <?php else: ?>
                    background: <?php echo esc_attr($bg_color); ?>;
                    <?php endif; ?>
                    color: <?php echo esc_attr($text_color); ?>;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    min-height: 100vh;
                    text-align: center;
                    padding: 20px;
                }
                <?php if ($bg_type === 'image' && $bg_image_url): ?>
                body::before {
                    content: '';
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background: rgba(0, 0, 0, 0.5);
                    z-index: 0;
                }
                .container {
                    position: relative;
                    z-index: 1;
                }
                <?php endif; ?>
                .container {
                    max-width: 700px;
                    animation: fadeIn 0.8s ease-out;
                }
                @keyframes fadeIn {
                    from { opacity: 0; transform: translateY(30px); }
                    to { opacity: 1; transform: translateY(0); }
                }
                .icon {
                    margin-bottom: 30px;
                    animation: pulse 2s infinite;
                }
                .icon svg {
                    width: 80px;
                    height: 80px;
                }
                @keyframes pulse {
                    0%, 100% { transform: scale(1); opacity: 1; }
                    50% { transform: scale(1.05); opacity: 0.8; }
                }
                .logo {
                    margin-bottom: 40px;
                }
                .logo img {
                    max-width: 250px;
                    height: auto;
                    border-radius: 16px;
                    box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                }
                h1 {
                    font-size: 52px;
                    margin-bottom: 24px;
                    font-weight: 700;
                    line-height: 1.2;
                }
                p {
                    font-size: 20px;
                    line-height: 1.7;
                    opacity: 0.9;
                    margin-bottom: 40px;
                }
                .countdown {
                    display: flex;
                    justify-content: center;
                    gap: 20px;
                    margin-top: 40px;
                }
                .countdown-item {
                    background: rgba(255,255,255,0.1);
                    padding: 20px 30px;
                    border-radius: 12px;
                    backdrop-filter: blur(10px);
                }
                .countdown-value {
                    font-size: 48px;
                    font-weight: 700;
                    color: <?php echo esc_attr($accent_color); ?>;
                    display: block;
                }
                .countdown-label {
                    font-size: 14px;
                    opacity: 0.7;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                    margin-top: 8px;
                }
                .status-badge {
                    display: inline-block;
                    background: <?php echo esc_attr($accent_color); ?>;
                    color: <?php
                        // Pick readable text color based on accent luminance
                        $hex = ltrim($accent_color, '#');
                        $r = hexdec(substr($hex, 0, 2));
                        $g = hexdec(substr($hex, 2, 2));
                        $b = hexdec(substr($hex, 4, 2));
                        echo (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255 < 0.5 ? '#ffffff' : '#1e293b';
                    ?>;
                    padding: 12px 24px;
                    border-radius: 50px;
                    font-weight: 600;
                    font-size: 14px;
                    text-transform: uppercase;
                    letter-spacing: 1px;
                    margin-bottom: 30px;
                }
                .social-link {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 48px;
                    height: 48px;
                    background: rgba(255,255,255,0.1);
                    border-radius: 50%;
                    color: <?php echo esc_attr($text_color); ?>;
                    transition: all 0.2s ease;
                    text-decoration: none;
                }
                .social-link:hover {
                    background: <?php echo esc_attr($accent_color); ?>;
                    transform: translateY(-2px);
                }
                .social-link svg {
                    width: 20px;
                    height: 20px;
                }
                @media (max-width: 600px) {
                    h1 { font-size: 36px; }
                    p { font-size: 18px; }
                    .icon svg { width: 60px; height: 60px; }
                    .countdown { flex-wrap: wrap; gap: 15px; }
                    .countdown-item { padding: 15px 20px; }
                    .countdown-value { font-size: 36px; }
                    .social-link { width: 40px; height: 40px; }
                    .social-link svg { width: 18px; height: 18px; }
                }
            </style>
        </head>
        <body>
            <div class="container">
                <?php if ($logo_url): ?>
                    <div class="logo">
                        <img src="<?php echo esc_url($logo_url); ?>" alt="Logo">
                    </div>
                <?php else: ?>
                    <div class="icon">
                        <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="opacity: 0.8;">
                            <circle cx="12" cy="12" r="3"></circle>
                            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
                        </svg>
                    </div>
                <?php endif; ?>
                
                <div class="status-badge"><?php echo esc_html($badge_text); ?></div>
                <h1><?php echo esc_html($title); ?></h1>
                <p><?php echo nl2br(esc_html($message)); ?></p>
                
                <?php if ($show_timer && $end_time): ?>
                    <div class="countdown" id="countdown">
                        <div class="countdown-item">
                            <span class="countdown-value" id="days">00</span>
                            <span class="countdown-label">Days</span>
                        </div>
                        <div class="countdown-item">
                            <span class="countdown-value" id="hours">00</span>
                            <span class="countdown-label">Hours</span>
                        </div>
                        <div class="countdown-item">
                            <span class="countdown-value" id="minutes">00</span>
                            <span class="countdown-label">Minutes</span>
                        </div>
                        <div class="countdown-item">
                            <span class="countdown-value" id="seconds">00</span>
                            <span class="countdown-label">Seconds</span>
                        </div>
                    </div>
                    
                    <script>
                    <?php
                    // Convert end_time to UTC timestamp for JavaScript
                    // This ensures both PHP and JS use the exact same moment in time
                    $wp_timezone = wp_timezone();
                    $end_timestamp_ms = 0;
                    try {
                        $end_datetime = new DateTime($end_time, $wp_timezone);
                        $end_timestamp_ms = $end_datetime->getTimestamp() * 1000; // Convert to milliseconds for JS
                    } catch (Exception $e) {
                        $end_timestamp_ms = 0;
                    }
                    ?>
                    const endTimeMs = <?php echo intval($end_timestamp_ms); ?>;

                    if (endTimeMs > 0) {
                        function updateCountdown() {
                            const now = Date.now();
                            const distance = endTimeMs - now;

                            if (distance < 0) {
                                document.getElementById('countdown').innerHTML = '<p><?php echo esc_js(__('Maintenance complete! Redirecting...', 'wpswitchboard')); ?></p>';
                                // Auto-refresh to allow normal site access
                                setTimeout(function() {
                                    window.location.reload();
                                }, 1500);
                                return;
                            }

                            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
                            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

                            document.getElementById('days').textContent = String(days).padStart(2, '0');
                            document.getElementById('hours').textContent = String(hours).padStart(2, '0');
                            document.getElementById('minutes').textContent = String(minutes).padStart(2, '0');
                            document.getElementById('seconds').textContent = String(seconds).padStart(2, '0');
                        }

                        updateCountdown();
                        setInterval(updateCountdown, 1000);
                    } else {
                        document.getElementById('countdown').innerHTML = '<p class="opacity-70">Countdown will appear when end time is set</p>';
                    }
                    </script>
                <?php endif; ?>

                <?php if ($has_social_links): ?>
                <div class="social-links" style="margin-top: 40px; display: flex; justify-content: center; gap: 16px;">
                    <?php if (!empty($social_facebook)): ?>
                    <a href="<?php echo esc_url($social_facebook); ?>" target="_blank" rel="noopener noreferrer" class="social-link" title="Facebook">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
                    </a>
                    <?php endif; ?>
                    <?php if (!empty($social_twitter)): ?>
                    <a href="<?php echo esc_url($social_twitter); ?>" target="_blank" rel="noopener noreferrer" class="social-link" title="X (Twitter)">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
                    </a>
                    <?php endif; ?>
                    <?php if (!empty($social_instagram)): ?>
                    <a href="<?php echo esc_url($social_instagram); ?>" target="_blank" rel="noopener noreferrer" class="social-link" title="Instagram">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/></svg>
                    </a>
                    <?php endif; ?>
                    <?php if (!empty($social_linkedin)): ?>
                    <a href="<?php echo esc_url($social_linkedin); ?>" target="_blank" rel="noopener noreferrer" class="social-link" title="LinkedIn">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
                    </a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
    
    public function add_admin_bar_notice($wp_admin_bar) {
        $settings = get_option('switchboard_maintenance-mode-enhanced_settings', []);
        $enabled = isset($settings['enabled']) ? $settings['enabled'] : 0;

        if (!$enabled) {
            return;
        }

        // Only show notice to users who can see the site during maintenance
        $allowed_roles = $this->get_allowed_roles();
        $user = wp_get_current_user();
        $has_access = false;

        if ($user && is_array($user->roles)) {
            foreach ($user->roles as $user_role) {
                if (in_array($user_role, $allowed_roles)) {
                    $has_access = true;
                    break;
                }
            }
        }

        if (!$has_access) {
            return;
        }

        $wp_admin_bar->add_node([
            'id' => 'maintenance-mode-enhanced',
            'title' => '<span style="display: inline-flex; align-items: center; gap: 6px;"><span style="width: 8px; height: 8px; background: #ef4444; border-radius: 50%; animation: sb-pulse 2s infinite;"></span>' . esc_html__('Maintenance Mode', 'wpswitchboard') . '</span><style>@keyframes sb-pulse{0%,100%{opacity:1}50%{opacity:0.5}}</style>',
            'href' => admin_url('admin.php?page=switchboard'),
            'meta' => [
                'title' => __('Click to manage Maintenance Mode settings', 'wpswitchboard'),
            ]
        ]);
    }
}

// Initialize and register with data system
$switchboard_instance = new SwitchboardMaintenanceModeEnhanced();
Switchboard_Data_Registry::get_instance()->auto_register($switchboard_instance, __FILE__);
