<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

class AIAutoTool_Cron_Status_Widget {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function __construct() {
        // Always ensure the widget is active - set option to 'true' if not already set
        $this->ensure_widget_active();
        
        add_action('wp_ajax_get_cron_status', array($this, 'get_cron_status_callback'));
        add_action('wp_ajax_get_notifications', array($this, 'get_notifications_callback'));
        add_action('admin_footer', array($this, 'add_cron_status_widget'));
        
        // Load text domain for translations at 'init' action to comply with WordPress 6.7.0+ requirements
        add_action('init', array($this, 'load_textdomain'));
    }
    
    /**
     * Ensure widget is always active - automatically enable if not already set
     * This widget should always run and cannot be disabled
     */
    private function ensure_widget_active() {
        $active_option = 'AIAutoTool_Cron_Status_Widget_active';
        $current_value = get_option($active_option);
        
        // If option doesn't exist or is not 'true', set it to 'true'
        if ($current_value === false || $current_value !== 'true') {
            update_option($active_option, 'true');
        }
    }
    
    public function load_textdomain() {
        load_plugin_textdomain('aiautotool-cron-widget', false, dirname(plugin_basename(__FILE__)) . '/languages');
    }
    
    public function get_cron_status_callback() {
        // Set proper headers for JSON response
        if (!headers_sent()) {
            header('Content-Type: application/json; charset=UTF-8');
        }
        
        // Check nonce without dying - handle error gracefully
        $nonce_check = check_ajax_referer('aiautotool_nonce', 'security', false);
        if (!$nonce_check) {
            wp_send_json_error(array(
                'message' => __('Security check failed. Please refresh the page and try again.', 'aiautotool-cron-widget'),
                'code' => 'nonce_failed'
            ));
            wp_die();
            return;
        }
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_send_json_error(array(
                'message' => __('You must be logged in.', 'aiautotool-cron-widget'),
                'code' => 'not_logged_in'
            ));
            wp_die();
            return;
        }
        
        // Chỉ cho phép admin có quyền cao nhất
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Unauthorized access', 'aiautotool-cron-widget'),
                'code' => 'insufficient_permissions'
            ));
            wp_die();
            return;
        }
        
        $user = wp_get_current_user();
        if (!$user || !$user->exists()) {
            wp_send_json_error(array(
                'message' => __('Invalid user', 'aiautotool-cron-widget'),
                'code' => 'invalid_user'
            ));
            wp_die();
            return;
        }
        
        $user_roles = $user->roles;
        if (!is_array($user_roles)) {
            $user_roles = array();
        }
        
        if (!in_array('administrator', $user_roles) && !is_super_admin()) {
            wp_send_json_error(array(
                'message' => __('Insufficient permissions', 'aiautotool-cron-widget'),
                'code' => 'insufficient_permissions'
            ));
            wp_die();
            return;
        }
        
        try {
            $cron_status = get_transient('aiautotool_cron_status');
            if (!$cron_status || !is_array($cron_status)) {
                $cron_status = array(
                    'is_running' => false,
                    'current_task' => '',
                    'current_post_title' => '',
                    'progress' => 0,
                    'last_update' => '',
                    'next_schedule' => '',
                    'cron_type' => ''
                );
            }
            
            // Calculate next schedule time for all cron types
            $this->update_next_schedule_times($cron_status);
            
            wp_send_json_success($cron_status);
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => __('Error retrieving cron status: ', 'aiautotool-cron-widget') . $e->getMessage(),
                'code' => 'exception'
            ));
        }
        
        wp_die(); // Always die after AJAX response
    }
    
    private function update_next_schedule_times(&$cron_status) {
        $next_schedules = array();
        
        // Auto Content cron
        $content_interval = get_option('aiautotool_draft_public_time', 5);
        $next_content_run = time() + ($content_interval * 60);
        $next_schedules[] = __('Auto Content', 'aiautotool-cron-widget') . ': ' . date('H:i:s', $next_content_run);
        
        // Auto Comment cron
        $comment_interval = get_option('aiautotool_autocomment_time', 10);
        $next_comment_run = time() + ($comment_interval * 60);
        $next_schedules[] = __('Auto Comment', 'aiautotool-cron-widget') . ': ' . date('H:i:s', $next_comment_run);
        
        // Auto Create Tag cron
        $tag_interval = get_option('aiautotool_autocreatetag_time', 15);
        $next_tag_run = time() + ($tag_interval * 60);
        $next_schedules[] = __('Auto Create Tag', 'aiautotool-cron-widget') . ': ' . date('H:i:s', $next_tag_run);
        
        // Auto Suggest cron
        $suggest_interval = get_option('aiautotool_suggestauto_time', 20);
        $next_suggest_run = time() + ($suggest_interval * 60);
        $next_schedules[] = __('Auto Suggest', 'aiautotool-cron-widget') . ': ' . date('H:i:s', $next_suggest_run);
        
        $cron_status['next_schedule'] = implode(' | ', $next_schedules);
    }
    
    public function get_notifications_callback() {
        // Set proper headers for JSON response
        if (!headers_sent()) {
            header('Content-Type: application/json; charset=UTF-8');
        }
        
        // Check nonce without dying - handle error gracefully
        $nonce_check = check_ajax_referer('aiautotool_nonce', 'security', false);
        if (!$nonce_check) {
            wp_send_json_error(array(
                'message' => __('Security check failed. Please refresh the page and try again.', 'aiautotool-cron-widget'),
                'code' => 'nonce_failed'
            ));
            wp_die();
            return;
        }
        
        // Check if user is logged in
        if (!is_user_logged_in()) {
            wp_send_json_error(array(
                'message' => __('You must be logged in.', 'aiautotool-cron-widget'),
                'code' => 'not_logged_in'
            ));
            wp_die();
            return;
        }
        
        // Chỉ cho phép admin có quyền cao nhất
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array(
                'message' => __('Unauthorized access', 'aiautotool-cron-widget'),
                'code' => 'insufficient_permissions'
            ));
            wp_die();
            return;
        }
        
        $user = wp_get_current_user();
        if (!$user || !$user->exists()) {
            wp_send_json_error(array(
                'message' => __('Invalid user', 'aiautotool-cron-widget'),
                'code' => 'invalid_user'
            ));
            wp_die();
            return;
        }
        
        $user_roles = $user->roles;
        if (!is_array($user_roles)) {
            $user_roles = array();
        }
        
        if (!in_array('administrator', $user_roles) && !is_super_admin()) {
            wp_send_json_error(array(
                'message' => __('Insufficient permissions', 'aiautotool-cron-widget'),
                'code' => 'insufficient_permissions'
            ));
            wp_die();
            return;
        }
        
        try {
            $notifications = get_transient('aiautotool_notifications');
            if ($notifications === false) {
                $notifications = array();
            }
            
            if (!is_array($notifications)) {
                $notifications = array();
            }
            
            // Clear after sending
            delete_transient('aiautotool_notifications');
            
            wp_send_json_success($notifications);
        } catch (Exception $e) {
            wp_send_json_error(array(
                'message' => __('Error retrieving notifications: ', 'aiautotool-cron-widget') . $e->getMessage(),
                'code' => 'exception'
            ));
        }
        
        wp_die(); // Always die after AJAX response
    }
    
    public function update_cron_status($status_data) {
        $status_data['last_update'] = current_time('Y-m-d H:i:s');
        set_transient('aiautotool_cron_status', $status_data, 300); // 5 minutes
        
        // Send notification for important events
        if (isset($status_data['current_task'])) {
            if (strpos($status_data['current_task'], __('Post published successfully', 'aiautotool-cron-widget')) !== false) {
                $this->send_notification(__('Post published:', 'aiautotool-cron-widget') . ' ' . $status_data['current_post_title'], 'success');
            } elseif (strpos($status_data['current_task'], __('Content creation completed', 'aiautotool-cron-widget')) !== false) {
                $this->send_notification(__('Content created for post:', 'aiautotool-cron-widget') . ' ' . $status_data['current_post_title'], 'success');
            } elseif (strpos($status_data['current_task'], __('Comment creation completed', 'aiautotool-cron-widget')) !== false) {
                $this->send_notification(__('Comment created for post:', 'aiautotool-cron-widget') . ' ' . $status_data['current_post_title'], 'success');
            } elseif (strpos($status_data['current_task'], __('Tag creation completed', 'aiautotool-cron-widget')) !== false) {
                $this->send_notification(__('Tag created for post:', 'aiautotool-cron-widget') . ' ' . $status_data['current_post_title'], 'success');
            } elseif (strpos($status_data['current_task'], __('Suggestion creation completed', 'aiautotool-cron-widget')) !== false) {
                $this->send_notification(__('Draft post created:', 'aiautotool-cron-widget') . ' ' . $status_data['current_post_title'], 'success');
            } elseif (strpos($status_data['current_task'], __('Error:', 'aiautotool-cron-widget')) !== false) {
                $this->send_notification($status_data['current_task'], 'error');
            }
        }
    }
    
    public function send_notification($message, $type = 'info') {
        // Store notification for JavaScript to display
        $notifications = get_transient('aiautotool_notifications') ?: array();
        $notifications[] = array(
            'message' => $message,
            'type' => $type,
            'time' => current_time('Y-m-d H:i:s')
        );
        set_transient('aiautotool_notifications', $notifications, 60); // 1 minute
    }
    
    public function add_cron_status_widget() {
        // Chỉ hiển thị cho admin có quyền cao nhất
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Kiểm tra thêm quyền super admin hoặc administrator
        $user = wp_get_current_user();
        $user_roles = $user->roles;
        
        // Chỉ hiển thị cho administrator hoặc super admin
        if (!in_array('administrator', $user_roles) && !is_super_admin()) {
            return;
        }
        ?>
        <div id="aiautotool-cron-widget" class="aiautotool-cron-widget" style="display: none;">
            <div class="cron-widget-header">
                <i class="fa-regular fa-clock"></i>
                <span class="cron-widget-title"><?php echo esc_html__('AI Auto Tool', 'aiautotool-cron-widget'); ?></span>
                <button class="cron-widget-close" onclick="toggleCronWidget()">×</button>
            </div>
            <div class="cron-widget-content">
                <div class="cron-status">
                    <div class="status-indicator">
                        <span class="status-dot"></span>
                        <span class="status-text"><?php echo esc_html__('Waiting...', 'aiautotool-cron-widget'); ?></span>
                    </div>
                </div>
                <div class="cron-progress">
                    <div class="progress-bar">
                        <div class="progress-fill"></div>
                    </div>
                    <div class="progress-text">0%</div>
                </div>
                <div class="cron-details">
                    <div class="current-task"><?php echo esc_html__('No tasks available', 'aiautotool-cron-widget'); ?></div>
                    <div class="current-post">
                        <span class="current-post-label"><?php echo esc_html__('Đang viết:', 'aiautotool-cron-widget'); ?></span>
                        <span class="current-post-title"></span>
                    </div>
                    <div class="cron-type"></div>
                    <div class="next-schedule"></div>
                    <div class="last-update"></div>
                </div>
                <div class="cron-actions">
                    <button class="cron-action-btn" onclick="refreshCronStatus()">
                        <i class="fa-solid fa-sync-alt"></i> <?php echo esc_html__('Refresh', 'aiautotool-cron-widget'); ?>
                    </button>
                </div>
            </div>
        </div>

        <div id="aiautotool-cron-toggle" class="aiautotool-cron-toggle" onclick="toggleCronWidget()">
            <i class="fa-regular fa-clock"></i>
        </div>

        <style>
        .aiautotool-cron-widget {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 320px;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.12);
            z-index: 9999;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            border: 1px solid #e1e5e9;
            overflow: hidden;
        }

        .cron-widget-header {
            background: var(--aiautotool-color);
            color: white;
            padding: 12px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-weight: 600;
        }

        .cron-widget-header i {
            margin-right: 8px;
            font-size: 16px;
        }

        .cron-widget-close {
            background: none;
            border: none;
            color: white;
            font-size: 18px;
            cursor: pointer;
            padding: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: background 0.2s;
        }

        .cron-widget-close:hover {
            background: rgba(255,255,255,0.2);
        }

        .cron-widget-content {
            padding: 16px;
        }

        .cron-status {
            margin-bottom: 16px;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #e0e0e0;
            animation: pulse 2s infinite;
        }

        .status-dot.running {
            background: #4caf50;
            animation: pulse 1s infinite;
        }

        .status-dot.completed {
            background: #2196f3;
        }

        .status-text {
            font-size: 14px;
            font-weight: 500;
            color: #333;
        }

        .cron-progress {
            margin-bottom: 16px;
        }

        .progress-bar {
            width: 100%;
            height: 6px;
            background: #f0f0f0;
            border-radius: 3px;
            overflow: hidden;
            margin-bottom: 8px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #4caf50, #8bc34a);
            width: 0%;
            transition: width 0.3s ease;
        }

        .progress-text {
            font-size: 12px;
            color: #666;
            text-align: center;
        }

        .cron-details {
            font-size: 12px;
            color: #666;
        }

        .current-task {
            margin-bottom: 4px;
            font-weight: 500;
        }

        .current-post {
            margin-bottom: 4px;
            color: #4a90e2;
        }

        .current-post-label {
            font-weight: 500;
            margin-right: 4px;
        }

        .current-post-title {
            font-weight: 600;
        }

        .cron-type {
            margin-bottom: 4px;
            color: #666;
            font-style: italic;
        }

        .next-schedule {
            font-style: italic;
        }

        .aiautotool-cron-toggle {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 50px;
            height: 50px;
            background: var(--aiautotool-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
            z-index: 9998;
            transition: all 0.3s ease;
        }

        .aiautotool-cron-toggle:hover {
            transform: scale(1.1);
            box-shadow: 0 6px 16px rgba(74, 144, 226, 0.4);
        }

        .aiautotool-cron-toggle i {
            font-size: 18px;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4caf50;
            color: white;
            padding: 12px 16px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 10000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }

        .notification.show {
            transform: translateX(0);
        }

        .notification.error {
            background: #f44336;
        }

        .notification.info {
            background: #2196f3;
        }

        .cron-actions {
            margin-top: 12px;
            text-align: center;
        }

        .cron-action-btn {
            background: var(--aiautotool-color);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: all 0.3s ease;
        }

        .cron-action-btn:hover {
            background: var(--gradient) !important;
            transform: translateY(-1px);
        }

        .cron-action-btn i {
            font-size: 10px;
        }

        .last-update {
            font-size: 10px;
            color: #999;
            margin-top: 4px;
        }
        </style>

        <script>
        (function() {
            // Ensure we have the necessary settings
            if (typeof aiautotool_js_setting === 'undefined') {
                aiautotool_js_setting = {
                    ajax_url: '<?php echo esc_js(admin_url('admin-ajax.php')); ?>',
                    security: '<?php echo wp_create_nonce('aiautotool_nonce'); ?>'
                };
            }
            
            // Ensure security nonce is available
            if (!aiautotool_js_setting.security) {
                aiautotool_js_setting.security = '<?php echo wp_create_nonce('aiautotool_nonce'); ?>';
            }
            
            // Ensure ajax_url is available
            if (!aiautotool_js_setting.ajax_url) {
                aiautotool_js_setting.ajax_url = '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';
            }
            
            let cronWidgetVisible = false;
            let cronUpdateInterval;

            window.toggleCronWidget = function() {
                const widget = document.getElementById('aiautotool-cron-widget');
                const toggle = document.getElementById('aiautotool-cron-toggle');
                
                if (cronWidgetVisible) {
                    widget.style.display = 'none';
                    toggle.style.display = 'flex';
                    cronWidgetVisible = false;
                    if (cronUpdateInterval) {
                        clearInterval(cronUpdateInterval);
                    }
                } else {
                    widget.style.display = 'block';
                    toggle.style.display = 'none';
                    cronWidgetVisible = true;
                    updateCronStatus();
                    cronUpdateInterval = setInterval(updateCronStatus, 3000);
                }
            }

            function updateCronStatus() {
                if (!cronWidgetVisible) return;
                
                // Get fresh nonce if available, otherwise use cached one
                var securityNonce = (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.security) 
                    ? aiautotool_js_setting.security 
                    : '<?php echo wp_create_nonce('aiautotool_nonce'); ?>';
                
                var ajaxUrl = (typeof aiautotool_js_setting !== 'undefined' && aiautotool_js_setting.ajax_url)
                    ? aiautotool_js_setting.ajax_url
                    : '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';
                
                jQuery.ajax({
                    url: ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'get_cron_status',
                        security: securityNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            updateCronWidget(response.data);
                        } else {
                            // Handle error response
                            var errorMessage = 'Unknown error';
                            var errorCode = 'unknown';
                            
                            if (response.data) {
                                if (typeof response.data === 'string') {
                                    errorMessage = response.data;
                                } else if (response.data.message) {
                                    errorMessage = response.data.message;
                                    errorCode = response.data.code || 'unknown';
                                }
                            }
                            
                            // Log security errors
                            if (errorCode === 'nonce_failed' || errorMessage.indexOf('Security check failed') !== -1) {
                                console.error('Cron status security error:', errorMessage);
                                // Stop polling on security errors
                                if (cronUpdateInterval) {
                                    clearInterval(cronUpdateInterval);
                                }
                            } else {
                                console.error('Cron status error:', errorMessage);
                            }
                        }
                    },
                    error: function(xhr, status, error) {
                        // Handle HTTP errors
                        var errorMessage = 'AJAX request failed';
                        if (xhr.responseText) {
                            try {
                                var errorResponse = JSON.parse(xhr.responseText);
                                if (errorResponse.data && errorResponse.data.message) {
                                    errorMessage = errorResponse.data.message;
                                }
                            } catch (e) {
                                // Not JSON, use status text
                                errorMessage = xhr.statusText || error;
                            }
                        }
                        
                        console.error('Cron status AJAX error:', {
                            status: xhr.status,
                            statusText: xhr.statusText,
                            error: error,
                            message: errorMessage,
                            responseText: xhr.responseText ? xhr.responseText.substring(0, 200) : 'No response'
                        });
                        
                        // If 400 error with security-related message, stop polling
                        if (xhr.status === 400 && (errorMessage.indexOf('Security') !== -1 || errorMessage.indexOf('nonce') !== -1)) {
                            if (cronUpdateInterval) {
                                clearInterval(cronUpdateInterval);
                            }
                            console.error('400 Bad Request - Security issue detected. Try refreshing the page.');
                        }
                    }
                });
                
                // Check for notifications
                jQuery.ajax({
                    url: ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'get_notifications',
                        security: securityNonce
                    },
                    success: function(response) {
                        if (response.success) {
                            if (response.data && Array.isArray(response.data) && response.data.length > 0) {
                                response.data.forEach(function(notification) {
                                    if (notification && notification.message) {
                                        showNotification(notification.message, notification.type || 'info');
                                    }
                                });
                            }
                        } else {
                            // Handle error response
                            var errorMessage = 'Unknown error';
                            var errorCode = 'unknown';
                            
                            if (response.data) {
                                if (typeof response.data === 'string') {
                                    errorMessage = response.data;
                                } else if (response.data.message) {
                                    errorMessage = response.data.message;
                                    errorCode = response.data.code || 'unknown';
                                }
                            }
                            
                            // Log security errors
                            if (errorCode === 'nonce_failed' || errorMessage.indexOf('Security check failed') !== -1) {
                                console.error('Notifications security error:', errorMessage);
                                // Stop polling on security errors
                                if (cronUpdateInterval) {
                                    clearInterval(cronUpdateInterval);
                                }
                            } else {
                                console.warn('Notifications error:', errorMessage);
                            }
                        }
                    },
                    error: function(xhr, status, error) {
                        // Handle HTTP errors
                        var errorMessage = 'AJAX request failed';
                        if (xhr.responseText) {
                            try {
                                var errorResponse = JSON.parse(xhr.responseText);
                                if (errorResponse.data && errorResponse.data.message) {
                                    errorMessage = errorResponse.data.message;
                                }
                            } catch (e) {
                                // Not JSON, use status text
                                errorMessage = xhr.statusText || error;
                            }
                        }
                        
                        console.error('Notifications AJAX error:', {
                            status: xhr.status,
                            statusText: xhr.statusText,
                            error: error,
                            message: errorMessage,
                            responseText: xhr.responseText ? xhr.responseText.substring(0, 200) : 'No response'
                        });
                        
                        // If 400 error with security-related message, stop polling
                        if (xhr.status === 400 && (errorMessage.indexOf('Security') !== -1 || errorMessage.indexOf('nonce') !== -1)) {
                            if (cronUpdateInterval) {
                                clearInterval(cronUpdateInterval);
                            }
                        }
                    }
                });
            }

            function updateCronWidget(status) {
                const statusDot = document.querySelector('.status-dot');
                const statusText = document.querySelector('.status-text');
                const progressFill = document.querySelector('.progress-fill');
                const progressText = document.querySelector('.progress-text');
                const currentTask = document.querySelector('.current-task');
                const currentPost = document.querySelector('.current-post');
                const cronType = document.querySelector('.cron-type');
                const nextSchedule = document.querySelector('.next-schedule');
                const lastUpdate = document.querySelector('.last-update');

                // Update status
                statusDot.className = 'status-dot';
                if (status.is_running) {
                    statusDot.classList.add('running');
                    statusText.textContent = '<?php echo esc_js(__('Running...', 'aiautotool-cron-widget')); ?>';
                } else if (status.progress === 100) {
                    statusDot.classList.add('completed');
                    statusText.textContent = '<?php echo esc_js(__('Completed', 'aiautotool-cron-widget')); ?>';
                } else {
                    statusText.textContent = '<?php echo esc_js(__('Waiting...', 'aiautotool-cron-widget')); ?>';
                }

                // Update progress
                progressFill.style.width = status.progress + '%';
                progressText.textContent = status.progress + '%';

                // Update details
                currentTask.textContent = status.current_task || '<?php echo esc_js(__('No tasks available', 'aiautotool-cron-widget')); ?>';
                
                // Update current post title
                const currentPostTitle = document.querySelector('.current-post-title');
                if (currentPostTitle) {
                    if (status.current_post_title && status.current_post_title.trim() !== '') {
                        currentPostTitle.textContent = status.current_post_title;
                        currentPostTitle.style.display = 'inline';
                        currentPostTitle.style.fontStyle = 'normal';
                        currentPostTitle.style.opacity = '1';
                    } else {
                        currentPostTitle.textContent = '<?php echo esc_js(__('Chưa có bài viết', 'aiautotool-cron-widget')); ?>';
                        currentPostTitle.style.display = 'inline';
                        currentPostTitle.style.fontStyle = 'italic';
                        currentPostTitle.style.opacity = '0.7';
                    }
                }
                
                cronType.textContent = status.cron_type || '';
                nextSchedule.textContent = status.next_schedule || '';
                lastUpdate.textContent = status.last_update || '';
            }

            function showNotification(message, type = 'success') {
                const notification = document.createElement('div');
                notification.className = `notification ${type}`;
                notification.textContent = message;
                document.body.appendChild(notification);
                
                setTimeout(() => {
                    notification.classList.add('show');
                }, 100);
                
                setTimeout(() => {
                    notification.classList.remove('show');
                    setTimeout(() => {
                        document.body.removeChild(notification);
                    }, 300);
                }, 5000);
            }

            window.refreshCronStatus = function() {
                updateCronStatus();
            };

            // Auto-hide toggle button when widget is visible
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', initWidget);
            } else {
                initWidget();
            }
            
            function initWidget() {
                const widget = document.getElementById('aiautotool-cron-widget');
                if (widget) {
                    const observer = new MutationObserver(function(mutations) {
                        mutations.forEach(function(mutation) {
                            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                                const toggle = document.getElementById('aiautotool-cron-toggle');
                                if (widget.style.display === 'block') {
                                    toggle.style.display = 'none';
                                } else {
                                    toggle.style.display = 'flex';
                                }
                            }
                        });
                    });
                    observer.observe(widget, { attributes: true });
                }
            }
        })();
        </script>
        <?php
    }
}

// Initialize the widget
AIAutoTool_Cron_Status_Widget::get_instance(); 