<?php
//注册数据
add_action('admin_init', 'register_theme_settings');
function register_theme_settings() {
    register_setting("themes_demo","themes_demo");
    
    // 添加设置区块
    add_settings_section(
        'theme_general_section',
        '基本设置',
        null,
        'themes_demo'
    );
    
    // 添加设置字段
    add_settings_field(
        'site_logo',
        '网站 Logo',
        'theme_logo_callback',
        'themes_demo',
        'theme_general_section'
    );
    
    add_settings_field(
        'site_name',
        '网站名称',
        'theme_name_callback',
        'themes_demo',
        'theme_general_section'
    );
    
    add_settings_field(
        'maintenance_mode',
        '维护模式',
        'theme_maintenance_callback',
        'themes_demo',
        'theme_general_section'
    );
    
    add_settings_field(
        'maintenance_title',
        '维护页面标题',
        'theme_maintenance_title_callback',
        'themes_demo',
        'theme_general_section'
    );
    
    add_settings_field(
        'maintenance_message',
        '维护页面内容',
        'theme_maintenance_message_callback',
        'themes_demo',
        'theme_general_section'
    );
    
    add_settings_field(
        'maintenance_start_time',
        '维护开始时间',
        'theme_maintenance_start_time_callback',
        'themes_demo',
        'theme_general_section'
    );
    
    add_settings_field(
        'maintenance_end_time',
        '维护结束时间',
        'theme_maintenance_end_time_callback',
        'themes_demo',
        'theme_general_section'
    );
    
    add_settings_field(
        'maintenance_timezone',
        '时区设置',
        'theme_maintenance_timezone_callback',
        'themes_demo',
        'theme_general_section'
    );
}

//添加外观菜单主题设置选项
add_action('admin_menu', 'add_theme_menu_item');
function add_theme_menu_item() {
    add_theme_page("主题设置", "主题设置", "manage_options", "theme-panel", "theme_settings_page", null, 99);
}

/**
 * 获取主题设置选项
 */
function get_theme_option($option_name) {
    $options = get_option('themes_demo');
    return isset($options[$option_name]) ? $options[$option_name] : false;
}

/**
 * Logo 设置回调函数
 */
function theme_logo_callback() {
    $options = get_option('themes_demo');
    $logo = isset($options['site_logo']) ? $options['site_logo'] : '';
    ?>
    <input type="text" id="site_logo" name="themes_demo[site_logo]" value="<?php echo esc_attr($logo); ?>" class="regular-text">
    <button type="button" class="button button-secondary" id="upload-logo">选择图片</button>
    <p class="description">建议上传 PNG 格式的 Logo 图片</p>
    <script>
    jQuery(document).ready(function($) {
        $('#upload-logo').click(function(e) {
            e.preventDefault();
            var image = wp.media({
                title: '选择 Logo',
                multiple: false
            }).open()
            .on('select', function() {
                var uploaded_image = image.state().get('selection').first();
                var image_url = uploaded_image.toJSON().url;
                $('#site_logo').val(image_url);
                $('.logo-preview').html('<img src="' + image_url + '" style="max-width: 200px;">');
            });
        });
    });
    </script>
    <?php
}

/**
 * 网站名称设置回调函数
 */
function theme_name_callback() {
    $options = get_option('themes_demo');
    $site_name = isset($options['site_name']) ? $options['site_name'] : '';
    ?>
    <input type="text" id="site_name" name="themes_demo[site_name]" value="<?php echo esc_attr($site_name); ?>" class="regular-text">
    <p class="description">设置网站显示名称</p>
    <?php
}

/**
 * 维护模式设置回调函数
 */
function theme_maintenance_callback() {
    $options = get_option('themes_demo');
    $maintenance_mode = isset($options['maintenance_mode']) ? $options['maintenance_mode'] : '0';
    ?>
    <label>
        <input type="checkbox" name="themes_demo[maintenance_mode]" value="1" <?php checked($maintenance_mode, '1'); ?>>
        启用维护模式
    </label>
    <p class="description">启用后，非管理员用户将看到维护页面</p>
    <?php
}

/**
 * 维护页面标题设置回调函数
 */
function theme_maintenance_title_callback() {
    $options = get_option('themes_demo');
    $maintenance_title = isset($options['maintenance_title']) ? $options['maintenance_title'] : '网站维护中';
    ?>
    <input type="text" id="maintenance_title" name="themes_demo[maintenance_title]" value="<?php echo esc_attr($maintenance_title); ?>" class="regular-text">
    <p class="description">维护页面显示的标题</p>
    <?php
}

/**
 * 维护页面内容设置回调函数
 */
function theme_maintenance_message_callback() {
    $options = get_option('themes_demo');
    $maintenance_message = isset($options['maintenance_message']) ? $options['maintenance_message'] : '我们正在对网站进行维护升级，请稍后再访问。给您带来的不便，敬请谅解！';
    ?>
    <textarea id="maintenance_message" name="themes_demo[maintenance_message]" rows="5" class="large-text"><?php echo esc_textarea($maintenance_message); ?></textarea>
    <p class="description">维护页面显示的详细信息</p>
    <?php
}

/**
 * 维护开始时间设置回调函数
 */
function theme_maintenance_start_time_callback() {
    $options = get_option('themes_demo');
    $start_time = isset($options['maintenance_start_time']) ? $options['maintenance_start_time'] : '';
    ?>
    <input type="datetime-local" id="maintenance_start_time" name="themes_demo[maintenance_start_time]" value="<?php echo esc_attr($start_time); ?>" class="regular-text">
    <p class="description">设置维护模式自动开启的时间（留空表示立即开启）</p>
    <?php
}

/**
 * 维护结束时间设置回调函数
 */
function theme_maintenance_end_time_callback() {
    $options = get_option('themes_demo');
    $end_time = isset($options['maintenance_end_time']) ? $options['maintenance_end_time'] : '';
    ?>
    <input type="datetime-local" id="maintenance_end_time" name="themes_demo[maintenance_end_time]" value="<?php echo esc_attr($end_time); ?>" class="regular-text">
    <p class="description">设置维护模式自动关闭的时间（留空表示手动关闭）</p>
    <?php
}

/**
 * 时区设置回调函数
 */
function theme_maintenance_timezone_callback() {
    $options = get_option('themes_demo');
    $timezone = isset($options['maintenance_timezone']) ? $options['maintenance_timezone'] : get_option('timezone_string', 'Asia/Shanghai');
    
    // 获取常用时区列表
    $timezones = array(
        'Asia/Shanghai' => '中国标准时间 (UTC+8)',
        'Asia/Hong_Kong' => '香港时间 (UTC+8)',
        'Asia/Taipei' => '台北时间 (UTC+8)',
        'Asia/Tokyo' => '日本标准时间 (UTC+9)',
        'Asia/Seoul' => '韩国标准时间 (UTC+9)',
        'America/New_York' => '美国东部时间 (UTC-5/-4)',
        'America/Los_Angeles' => '美国西部时间 (UTC-8/-7)',
        'Europe/London' => '英国时间 (UTC+0/+1)',
        'Europe/Paris' => '欧洲中部时间 (UTC+1/+2)',
        'UTC' => '协调世界时 (UTC+0)'
    );
    ?>
    <select id="maintenance_timezone" name="themes_demo[maintenance_timezone]" class="regular-text">
        <?php foreach ($timezones as $tz => $label): ?>
            <option value="<?php echo esc_attr($tz); ?>" <?php selected($timezone, $tz); ?>><?php echo esc_html($label); ?></option>
        <?php endforeach; ?>
    </select>
    <p class="description">选择维护时间所使用的时区</p>
    <?php
}

/**
 * 确保在主题设置页面加载媒体上传脚本
 */
function theme_admin_scripts($hook) {
    if ('appearance_page_theme-panel' != $hook) {
        return;
    }
    wp_enqueue_media();
    
    // 添加维护模式时间验证脚本
    wp_add_inline_script('jquery', '
        jQuery(document).ready(function($) {
            // 时间验证函数
            function validateMaintenanceTimes() {
                var startTime = $("#maintenance_start_time").val();
                var endTime = $("#maintenance_end_time").val();
                var timezone = $("#maintenance_timezone").val();
                
                // 清除之前的错误提示
                $(".maintenance-time-error").remove();
                
                if (startTime && endTime) {
                    var start = new Date(startTime);
                    var end = new Date(endTime);
                    var now = new Date();
                    
                    // 检查结束时间是否晚于开始时间
                    if (end <= start) {
                        showTimeError("maintenance_end_time", "结束时间必须晚于开始时间");
                        return false;
                    }
                    
                    // 检查时间是否已过期（可选警告）
                    if (end <= now) {
                        showTimeWarning("maintenance_end_time", "结束时间已过期，维护模式将不会生效");
                    }
                }
                
                return true;
            }
            
            // 显示错误信息
            function showTimeError(fieldId, message) {
                $("#" + fieldId).after("<p class=\"maintenance-time-error\" style=\"color: #dc3232; font-size: 12px; margin: 5px 0;\">" + message + "</p>");
            }
            
            // 显示警告信息
            function showTimeWarning(fieldId, message) {
                $("#" + fieldId).after("<p class=\"maintenance-time-error\" style=\"color: #ffb900; font-size: 12px; margin: 5px 0;\">" + message + "</p>");
            }
            
            // 显示当前时区时间
            function updateCurrentTime() {
                var timezone = $("#maintenance_timezone").val();
                var now = new Date();
                var timeString = now.toLocaleString("zh-CN", {
                    timeZone: timezone.replace("_", "/"),
                    year: "numeric",
                    month: "2-digit",
                    day: "2-digit",
                    hour: "2-digit",
                    minute: "2-digit",
                    second: "2-digit"
                });
                
                $("#current-time-display").text("当前时间（" + timezone + "）：" + timeString);
            }
            
            // 绑定事件
            $("#maintenance_start_time, #maintenance_end_time").on("change", validateMaintenanceTimes);
            $("#maintenance_timezone").on("change", function() {
                validateMaintenanceTimes();
                updateCurrentTime();
            });
            
            // 表单提交验证
            $("form").on("submit", function(e) {
                if (!validateMaintenanceTimes()) {
                    e.preventDefault();
                    alert("请修正维护时间设置中的错误");
                    return false;
                }
            });
            
            // 添加当前时间显示
            if ($("#maintenance_timezone").length) {
                $("#maintenance_timezone").after("<p id=\"current-time-display\" style=\"font-size: 12px; color: #666; margin: 5px 0;\"></p>");
                updateCurrentTime();
                
                // 每秒更新时间显示
                setInterval(updateCurrentTime, 1000);
            }
        });
    ');
}
add_action('admin_enqueue_scripts', 'theme_admin_scripts');

/**
 * 验证维护模式时间设置
 */
function validate_maintenance_times($input) {
    $start_time = isset($input['maintenance_start_time']) ? $input['maintenance_start_time'] : '';
    $end_time = isset($input['maintenance_end_time']) ? $input['maintenance_end_time'] : '';
    $timezone = isset($input['maintenance_timezone']) ? $input['maintenance_timezone'] : 'Asia/Shanghai';
    
    // 如果设置了时间，进行验证
    if (!empty($start_time) && !empty($end_time)) {
        try {
            $tz = new DateTimeZone($timezone);
            $start_datetime = new DateTime($start_time, $tz);
            $end_datetime = new DateTime($end_time, $tz);
            
            // 检查结束时间是否晚于开始时间
            if ($end_datetime <= $start_datetime) {
                add_settings_error(
                    'themes_demo',
                    'maintenance_time_error',
                    '维护结束时间必须晚于开始时间',
                    'error'
                );
            }
            
            // 检查时间格式是否正确
            if ($start_datetime->format('Y-m-d\TH:i') !== $start_time) {
                add_settings_error(
                    'themes_demo',
                    'maintenance_start_format_error',
                    '维护开始时间格式不正确',
                    'error'
                );
            }
            
            if ($end_datetime->format('Y-m-d\TH:i') !== $end_time) {
                add_settings_error(
                    'themes_demo',
                    'maintenance_end_format_error',
                    '维护结束时间格式不正确',
                    'error'
                );
            }
            
        } catch (Exception $e) {
            add_settings_error(
                'themes_demo',
                'maintenance_timezone_error',
                '时区设置或时间格式错误：' . $e->getMessage(),
                'error'
            );
        }
    }
    
    return $input;
}

// 添加设置验证钩子
add_filter('pre_update_option_themes_demo', 'validate_maintenance_times');



function theme_settings_page() {
?>
<div id="title-box" width="204px" class="postbox box">
    <img width="210px" src="<?php bloginfo('template_url'); ?>/assets/images/logo-2.svg">
</div>
<div class="wrap">
    <h2>主题设置</h2>
    <?php settings_errors(); ?>
    
    <div class="nav-tab-wrapper">
        <a href="#general" class="nav-tab nav-tab-active">常规设置</a>
        <a href="#maintenance-status" class="nav-tab">维护状态</a>
    </div>
    
    <div class="tab-content">
        <div id="general" class="tab-pane active">
            <form method="post" action="options.php">
                <?php
                    settings_fields("themes_demo");
                    do_settings_sections("themes_demo");
                    submit_button();
                ?>
            </form>
        </div>
        
        <div id="maintenance-status" class="tab-pane">
            <h3>维护模式状态监控</h3>
            <?php
            // 获取当前维护模式设置
            $options = get_option('themes_demo');
            $maintenance_mode = isset($options['maintenance_mode']) ? $options['maintenance_mode'] : '0';
            $start_time = isset($options['maintenance_start_time']) ? $options['maintenance_start_time'] : '';
            $end_time = isset($options['maintenance_end_time']) ? $options['maintenance_end_time'] : '';
            $timezone = isset($options['maintenance_timezone']) ? $options['maintenance_timezone'] : 'Asia/Shanghai';
            
            // 检查定时维护状态
            $is_scheduled = function_exists('check_scheduled_maintenance') ? check_scheduled_maintenance() : false;
            
            echo "<div class='maintenance-status-panel'>";
            echo "<h4>当前状态</h4>";
            echo "<p><strong>手动维护模式：</strong> <span class='status-" . ($maintenance_mode === '1' ? 'active' : 'inactive') . "'>" . ($maintenance_mode === '1' ? '已启用' : '已禁用') . "</span></p>";
            echo "<p><strong>定时维护模式：</strong> <span class='status-" . ($is_scheduled ? 'active' : 'inactive') . "'>" . ($is_scheduled ? '处于维护期间' : '不在维护期间') . "</span></p>";
            
            if (!empty($start_time) || !empty($end_time)) {
                echo "<h4>定时设置</h4>";
                if (!empty($start_time)) {
                    echo "<p><strong>开始时间：</strong> " . esc_html($start_time) . "</p>";
                }
                if (!empty($end_time)) {
                    echo "<p><strong>结束时间：</strong> " . esc_html($end_time) . "</p>";
                }
                echo "<p><strong>时区：</strong> " . esc_html($timezone) . "</p>";
                
                // 显示当前时区时间
                try {
                    $tz = new DateTimeZone($timezone);
                    $current_time = new DateTime('now', $tz);
                    echo "<p><strong>当前时间：</strong> " . $current_time->format('Y-m-d H:i:s') . "</p>";
                } catch (Exception $e) {
                    echo "<p style='color: #dc3232;'><strong>时区错误：</strong> " . esc_html($e->getMessage()) . "</p>";
                }
            }
            
            // 显示定时任务状态
            echo "<h4>定时任务状态</h4>";
            $start_scheduled = wp_next_scheduled('maintenance_mode_start');
            $end_scheduled = wp_next_scheduled('maintenance_mode_end');
            
            if ($start_scheduled) {
                echo "<p><strong>开始维护任务：</strong> " . date('Y-m-d H:i:s', $start_scheduled) . "</p>";
            } else {
                echo "<p><strong>开始维护任务：</strong> 未安排</p>";
            }
            
            if ($end_scheduled) {
                echo "<p><strong>结束维护任务：</strong> " . date('Y-m-d H:i:s', $end_scheduled) . "</p>";
            } else {
                echo "<p><strong>结束维护任务：</strong> 未安排</p>";
            }
            
            echo "</div>";
            
            // 添加快速操作按钮
            echo "<div class='maintenance-quick-actions'>";
            echo "<h4>快速操作</h4>";
            echo "<p><a href='?page=maintenance-test' class='button button-secondary'>打开测试页面</a></p>";
            echo "<p><button type='button' id='refresh-status' class='button button-secondary'>刷新状态</button></p>";
            echo "</div>";
            ?>
        </div>
    </div>
</div>

<style>
.tab-content > .tab-pane {
    display: none;
}
.tab-content > .active {
    display: block;
}

/* 维护状态样式 */
.maintenance-status-panel {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
}

.maintenance-status-panel h4 {
    margin-top: 0;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.status-active {
    color: #46b450;
    font-weight: bold;
}

.status-inactive {
    color: #dc3232;
    font-weight: bold;
}

.maintenance-quick-actions {
    background: #f9f9f9;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
}

.maintenance-quick-actions h4 {
    margin-top: 0;
}
</style>

<script>
jQuery(document).ready(function($) {
    // 标签页切换
    $('.nav-tab').click(function(e) {
        e.preventDefault();
        var target = $(this).attr('href');
        
        $('.nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');
        
        $('.tab-pane').removeClass('active');
        $(target).addClass('active');
    });
    
    // 刷新状态按钮
    $('#refresh-status').click(function() {
        location.reload();
    });
});
</script>
<?php } ?>