<?php

/**
 * @id 41
 * @name 网站变灰
 * @version 1.0.0
 * @description 一键将全站变为灰色调，支持自定义灰度参数设置和特定日期自动启用，适合特殊纪念日使用
 * @price 0
 * @type 插件
 * @width 420
 * @height 400
 * @thumbnail /img/id41.png
 * @tpl templates/footer.html
 */

$plugin_config = <<<EOT
[config_params]
插件开关 =
变灰程度 =
启用时间 =
结束时间 =
[/config_params]

[Plugin Instructions]
[/Plugin Instructions]
EOT;

$config = array();
if (preg_match('/\[config_params\](.*?)\[\/config_params\]/s', $plugin_config, $matches)) {
    $lines = explode("\n", $matches[1]);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || strpos($line, '=') === false) continue;
        list($key, $value) = explode('=', $line, 2);
        $key = trim($key);
        $value = trim($value);
        if ($key !== '') {
            $config[$key] = $value;
        }
    }
}

function qk_gray_parse_bool($v, $default = false)
{
    if ($v === null) return $default;
    if ($v === true || $v === 1 || $v === '1') return true;
    if ($v === false || $v === 0 || $v === '0') return false;
    $s = strtolower(trim((string)$v));
    if (in_array($s, array('true', 'yes', 'on', '开启', '是'), true)) return true;
    if (in_array($s, array('false', 'no', 'off', '关闭', '否'), true)) return false;
    $filtered = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
    return $filtered !== null ? $filtered : $default;
}

function qk_gray_get_config_value($config, $key, $default = '')
{
    if (!is_array($config) || !isset($config[$key])) return $default;
    $value = $config[$key];
    if (strpos((string)$value, '|select|') !== false) {
        $parts = explode('|select|', (string)$value, 2);
        return trim($parts[0]);
    }
    return trim($value);
}

function qk_gray_parse_datetime($str)
{
    $str = trim($str);
    if ($str === '') return false;
    $parts = explode('.', $str);
    if (count($parts) < 3) return false;
    $year = intval($parts[0]);
    $month = intval($parts[1]);
    $day = intval($parts[2]);
    $hour = isset($parts[3]) ? intval($parts[3]) : 0;
    $minute = isset($parts[4]) ? intval($parts[4]) : 0;
    if ($year < 2000 || $year > 2100 || $month < 1 || $month > 12 || $day < 1 || $day > 31) return false;
    if ($hour < 0 || $hour > 23 || $minute < 0 || $minute > 59) return false;
    return mktime($hour, $minute, 0, $month, $day, $year);
}

function qk_gray_check_time_range($start_str, $end_str)
{
    $start_str = trim($start_str);
    $end_str = trim($end_str);
    if ($start_str === '' && $end_str === '') return false;
    $now = time();
    if ($start_str !== '' && $end_str !== '') {
        if (strpos($start_str, '——') !== false || strpos($end_str, '——') !== false) {
            $range_str = strpos($start_str, '——') !== false ? $start_str : $end_str;
            $range_parts = explode('——', $range_str, 2);
            if (count($range_parts) === 2) {
                $start_time = qk_gray_parse_datetime($range_parts[0]);
                $end_time = qk_gray_parse_datetime($range_parts[1]);
                if ($start_time !== false && $end_time !== false) {
                    return $now >= $start_time && $now <= $end_time;
                }
            }
        }
    }
    $start_time = qk_gray_parse_datetime($start_str);
    $end_time = qk_gray_parse_datetime($end_str);
    if ($start_time !== false && $end_time !== false) {
        return $now >= $start_time && $now <= $end_time;
    }
    if ($start_time !== false) {
        return $now >= $start_time;
    }
    if ($end_time !== false) {
        return $now <= $end_time;
    }
    return false;
}

function qk_gray($cfg)
{
    global $config_params;
    if (is_array($config_params) && !empty($config_params)) {
        $cfg = array_merge($cfg, $config_params);
    }
    $enabled = qk_gray_parse_bool(qk_gray_get_config_value($cfg, '插件开关', 'false'), false);
    if (!$enabled) return '';
    $start_time = qk_gray_get_config_value($cfg, '启用时间', '');
    $end_time = qk_gray_get_config_value($cfg, '结束时间', '');
    if ($start_time === '' && $end_time === '') return '';
    if (!qk_gray_check_time_range($start_time, $end_time)) return '';
    $grayscale = intval(qk_gray_get_config_value($cfg, '变灰程度', '100'));
    $grayscale = max(0, min(100, $grayscale));
    return '<style id="qk-gray-style">html,body,*{filter:grayscale(' . $grayscale . '%)!important;-webkit-filter:grayscale(' . $grayscale . '%)!important}</style>';
}

$plugin_instructions = '';
if (preg_match('/\[Plugin Instructions\](.*?)\[\/Plugin Instructions\]/s', $plugin_config, $matches)) {
    $plugin_instructions = trim($matches[1]);
}

$plugin_switch = isset($config['插件开关']) ? $config['插件开关'] : 'false';
$is_enabled = qk_gray_parse_bool($plugin_switch, false);
$grayscale_value = isset($config['变灰程度']) ? intval($config['变灰程度']) : 100;
$start_time = isset($config['启用时间']) ? $config['启用时间'] : '';
$end_time = isset($config['结束时间']) ? $config['结束时间'] : '';
$is_in_range = qk_gray_check_time_range($start_time, $end_time);

if (isset($_POST['plugin']) || isset($_GET['plugin'])) {
?>
    <!DOCTYPE html>
    <html>

    <head>
        <meta charset="UTF-8">
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }

            body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                background: #fff;
                padding: 20px;
            }

            .form-group {
                margin-bottom: 16px;
            }

            .form-label {
                display: block;
                font-size: 13px;
                color: #333;
                margin-bottom: 6px;
                font-weight: 500;
            }

            .switch-wrap {
                display: flex;
                align-items: center;
                gap: 12px;
                margin-top: 6px;
            }

            .switch {
                position: relative;
                width: 44px;
                height: 24px;
                background: #ddd;
                border-radius: 12px;
                cursor: pointer;
                transition: background .3s;
            }

            .switch.active {
                background: #2196F3;
            }

            .switch::after {
                content: '';
                position: absolute;
                top: 2px;
                left: 2px;
                width: 20px;
                height: 20px;
                background: #fff;
                border-radius: 50%;
                transition: transform .3s;
                box-shadow: 0 1px 3px rgba(0, 0, 0, .2);
            }

            .switch.active::after {
                transform: translateX(20px);
            }

            .switch-text {
                font-size: 14px;
                color: #666;
            }

            input[type="text"] {
                width: 100%;
                height: 38px;
                padding: 0 12px;
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                font-size: 14px;
                transition: border-color .2s;
            }

            input[type="text"]:focus {
                outline: none;
                border-color: #2196F3;
            }

            .range-wrap {
                display: flex;
                align-items: center;
                gap: 12px;
                margin-top: 6px;
            }

            input[type="range"] {
                flex: 1;
                height: 6px;
                -webkit-appearance: none;
                background: #e0e0e0;
                border-radius: 3px;
                outline: none;
            }

            input[type="range"]::-webkit-slider-thumb {
                -webkit-appearance: none;
                width: 18px;
                height: 18px;
                background: #2196F3;
                border-radius: 50%;
                cursor: pointer;
            }

            .range-value {
                min-width: 50px;
                text-align: right;
                font-size: 14px;
                color: #333;
                font-weight: 500;
            }

            .status-bar {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 10px 14px;
                background: #f8f9fa;
                border-radius: 6px;
                margin-bottom: 16px;
            }

            .status-text {
                font-size: 13px;
                color: #333;
            }

            .status-badge {
                padding: 3px 10px;
                border-radius: 10px;
                font-size: 11px;
                font-weight: 500;
            }

            .status-badge.active {
                background: #e3f2fd;
                color: #1976d2;
            }

            .status-badge.inactive {
                background: #f5f5f5;
                color: #999;
            }

            .hint {
                font-size: 11px;
                color: #999;
                margin-top: 4px;
            }

            .btn-save {
                width: 100%;
                height: 40px;
                background: #2196F3;
                color: #fff;
                border: none;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: background .2s;
            }

            .btn-save:hover {
                background: #1976d2;
            }
        </style>
    </head>

    <body>
        <div class="status-bar">
            <span class="status-text" id="statusText"><?php echo $is_enabled && $is_in_range ? '网站当前处于变灰状态' : '网站变灰未生效'; ?></span>
            <span class="status-badge <?php echo $is_enabled && $is_in_range ? 'active' : 'inactive'; ?>" id="statusBadge"><?php echo $is_enabled && $is_in_range ? '生效中' : '未生效'; ?></span>
        </div>
        <form id="configForm">
            <div class="form-group">
                <label class="form-label">插件开关</label>
                <div class="switch-wrap">
                    <div class="switch <?php echo $is_enabled ? 'active' : ''; ?>" id="toggleSwitch"></div>
                    <span class="switch-text" id="switchText"><?php echo $is_enabled ? '已开启' : '已关闭'; ?></span>
                    <input type="hidden" name="插件开关" id="enabled" value="<?php echo $is_enabled ? 'true' : 'false'; ?>">
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">变灰程度</label>
                <div class="range-wrap">
                    <input type="range" name="变灰程度" id="grayscale" min="0" max="100" value="<?php echo $grayscale_value; ?>">
                    <span class="range-value" id="grayscaleValue"><?php echo $grayscale_value; ?>%</span>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">启用时间</label>
                <input type="text" name="启用时间" id="startTime" value="<?php echo htmlspecialchars($start_time, ENT_QUOTES, 'UTF-8'); ?>" placeholder="2026.3.31.0.0">
                <div class="hint">格式：年.月.日.时.分</div>
            </div>
            <div class="form-group">
                <label class="form-label">结束时间</label>
                <input type="text" name="结束时间" id="endTime" value="<?php echo htmlspecialchars($end_time, ENT_QUOTES, 'UTF-8'); ?>" placeholder="2026.4.1.23.59">
                <div class="hint">格式：年.月.日.时.分</div>
            </div>
            <button type="button" class="btn-save" id="saveBtn">保存设置</button>
        </form>
        <script>
            window.callParentToast = function(msg, opts) {
                window.parent.postMessage({
                    type: 'toast',
                    func: 'showToast',
                    message: msg,
                    options: opts || {}
                }, window.parent.location.origin);
            };
            var qkDefaultTitle = document.title ? String(document.title) : '';
            if (!qkDefaultTitle) {
                qkDefaultTitle = '网站变灰';
                document.title = qkDefaultTitle;
            }
            var qkTitleTimer = null;
            function setTempTitle(t) {
                if (qkTitleTimer) clearTimeout(qkTitleTimer);
                document.title = String(t || qkDefaultTitle || '');
                qkTitleTimer = setTimeout(function() {
                    document.title = qkDefaultTitle;
                }, 1000);
            }
            var toggleSwitch = document.getElementById('toggleSwitch');
            var enabledInput = document.getElementById('enabled');
            var switchText = document.getElementById('switchText');
            toggleSwitch.addEventListener('click', function() {
                toggleSwitch.classList.toggle('active');
                var isActive = toggleSwitch.classList.contains('active');
                enabledInput.value = isActive ? 'true' : 'false';
                switchText.textContent = isActive ? '已开启' : '已关闭';
                updateStatus();
            });
            var grayscaleInput = document.getElementById('grayscale');
            var grayscaleValue = document.getElementById('grayscaleValue');
            grayscaleInput.addEventListener('input', function() {
                grayscaleValue.textContent = this.value + '%';
            });

            function parseDateTime(str) {
                if (!str) return null;
                var parts = str.split('.');
                if (parts.length < 3) return null;
                var year = parseInt(parts[0]),
                    month = parseInt(parts[1]) - 1,
                    day = parseInt(parts[2]);
                var hour = parts[3] ? parseInt(parts[3]) : 0,
                    minute = parts[4] ? parseInt(parts[4]) : 0;
                return new Date(year, month, day, hour, minute);
            }

            function updateStatus() {
                var isEnabled = enabledInput.value === 'true';
                var startStr = document.getElementById('startTime').value;
                var endStr = document.getElementById('endTime').value;
                var now = new Date();
                var start = parseDateTime(startStr);
                var end = parseDateTime(endStr);
                var inRange = false;
                if (start && end) inRange = now >= start && now <= end;
                else if (start) inRange = now >= start;
                else if (end) inRange = now <= end;
                var statusText = document.getElementById('statusText');
                var statusBadge = document.getElementById('statusBadge');
                if (isEnabled && inRange) {
                    statusText.textContent = '网站当前处于变灰状态';
                    statusBadge.textContent = '生效中';
                    statusBadge.className = 'status-badge active';
                } else {
                    statusText.textContent = isEnabled ? '网站变灰已启用（非生效时段）' : '网站变灰未启用';
                    statusBadge.textContent = '未生效';
                    statusBadge.className = 'status-badge inactive';
                }
            }
            document.getElementById('startTime').addEventListener('input', updateStatus);
            document.getElementById('endTime').addEventListener('input', updateStatus);
            updateStatus();
            document.getElementById('saveBtn').addEventListener('click', function() {
                var formData = new FormData(document.getElementById('configForm'));
                var settings = {};
                for (var pair of formData.entries()) settings[pair[0]] = pair[1];
                fetch('/admin/Plugin.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        body: 'action=save_plugin_settings&plugin=41_gray&settings=' + encodeURIComponent(JSON.stringify(settings))
                    })
                    .then(function(r) {
                        return r.json();
                    })
                    .then(function(data) {
                        if (data.success) {
                            setTempTitle('配置保存成功');
                            callParentToast('保存成功', {
                                type: 'success'
                            });
                        }
                        else callParentToast('保存失败：' + (data.message || ''), {
                            type: 'error'
                        });
                    })
                    .catch(function() {
                        callParentToast('网络错误', {
                            type: 'error'
                        });
                    });
            });
        </script>
    </body>

    </html>
<?php
}

if (!isset($_POST['plugin'])) {
    echo qk_gray($config);
}
?>
