<?php
/**
 * 系统配置模块 — 知岁OS服务商(无启用开关) + 公众号登录配置 + 开学时间
 */
$db = getDB();
$zsosSettings = $db->query("SELECT * FROM settings WHERE group_name = 'zsos' AND key_name != 'zsos_enabled' ORDER BY sort_order")->fetchAll();

// 获取公众号登录配置
$wechatSettings = $db->query("SELECT * FROM settings WHERE group_name = 'wechat' ORDER BY sort_order")->fetchAll();

// 获取学期时间配置
$semesterSettings = $db->query("SELECT * FROM settings WHERE group_name = 'semester' ORDER BY sort_order")->fetchAll();
if (empty($semesterSettings)) {
    // 自动插入默认学期时间配置
    $db->exec("INSERT INTO settings (group_name, key_name, value, remark, sort_order) VALUES ('semester', 'semester_start_date', '', '开学日期(格式:YYYY-MM-DD)', 1)");
    $db->exec("INSERT INTO settings (group_name, key_name, value, remark, sort_order) VALUES ('semester', 'semester_end_date', '', '放假截止日期(格式:YYYY-MM-DD)', 2)");
    $semesterSettings = $db->query("SELECT * FROM settings WHERE group_name = 'semester' ORDER BY sort_order")->fetchAll();
} else {
    // 确保semester_end_date存在
    $hasEndDate = false;
    foreach ($semesterSettings as $s) {
        if ($s['key_name'] === 'semester_end_date') $hasEndDate = true;
    }
    if (!$hasEndDate) {
        $db->exec("INSERT INTO settings (group_name, key_name, value, remark, sort_order) VALUES ('semester', 'semester_end_date', '', '放假截止日期(格式:YYYY-MM-DD)', 2)");
        $semesterSettings = $db->query("SELECT * FROM settings WHERE group_name = 'semester' ORDER BY sort_order")->fetchAll();
    }
}
?>

<div class="toolbar">
    <div class="toolbar-title">系统配置</div>
</div>

<!-- 开学时间配置 -->
<div class="panel-card" style="margin-bottom:16px;">
    <div class="config-group">
        <div class="config-group-title"><i class="fas fa-calendar-day"></i> 学期时间配置</div>
        <div style="padding:12px 0 8px; font-size:13px; color:#9ca3af;">
            设置本学期开学日期和放假截止日期，系统将自动计算当前为第几周，用于前端课表周次定位。
        </div>
        <?php foreach ($semesterSettings as $s): ?>
            <div class="config-item">
                <div class="config-key"><?php echo htmlspecialchars($s['key_name'] === 'semester_start_date' ? '开学日期' : ($s['key_name'] === 'semester_end_date' ? '放假截止日期' : $s['key_name'])); ?></div>
                <div class="config-desc"><?php echo htmlspecialchars($s['remark']); ?></div>
                <div class="config-value">
                    <?php if ($s['key_name'] === 'semester_start_date' || $s['key_name'] === 'semester_end_date'): ?>
                    <input type="date" id="semester_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>" style="width:100%;max-width:300px;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:14px;">
                    <?php else: ?>
                    <input type="text" id="semester_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>">
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
        <?php
        // 计算并显示当前周数
        $semesterStartDate = '';
        $semesterEndDate = '';
        foreach ($semesterSettings as $s) {
            if ($s['key_name'] === 'semester_start_date') $semesterStartDate = $s['value'];
            if ($s['key_name'] === 'semester_end_date') $semesterEndDate = $s['value'];
        }
        if ($semesterStartDate) {
            $startTimestamp = strtotime($semesterStartDate);
            $currentTimestamp = time();
            $diffDays = floor(($currentTimestamp - $startTimestamp) / 86400);
            $currentWeek = max(1, ceil(($diffDays + 1) / 7));
            $info = '<i class="fas fa-info-circle"></i> 当前第 <strong>' . $currentWeek . '</strong> 周（开学日期：' . htmlspecialchars($semesterStartDate);
            if ($semesterEndDate) {
                $endTimestamp = strtotime($semesterEndDate);
                $totalWeeks = max(1, ceil(($endTimestamp - $startTimestamp) / (7 * 86400)));
                $info .= '，放假截止：' . htmlspecialchars($semesterEndDate) . '，共' . $totalWeeks . '周';
                if ($currentTimestamp > $endTimestamp) {
                    $info .= ' <span style="color:#ef4444;">— 已放假</span>';
                }
            }
            $info .= '）';
            echo '<div style="padding:12px 0;font-size:14px;color:#3b82f6;">' . $info . '</div>';
        } else {
            echo '<div style="padding:12px 0;font-size:14px;color:#9ca3af;"><i class="fas fa-exclamation-triangle"></i> 未设置开学日期，课表将默认显示第1周</div>';
        }
        ?>
    </div>
    <div style="text-align:right; margin-top:16px;">
        <button class="btn-primary" onclick="saveSemesterConfig()"><i class="fas fa-save"></i> 保存开学时间</button>
    </div>
</div>

<!-- 知岁OS服务商配置 -->
<div class="panel-card" style="margin-bottom:16px;">
    <div class="config-group">
        <div class="config-group-title"><i class="fas fa-cloud"></i> 知岁OS服务商配置</div>
        <div style="padding:12px 0 8px; font-size:13px; color:#9ca3af;">
            配置知岁OS数据接口的服务商凭证，用于前端课表/成绩等数据的同步导入。修改后需点击下方"同步到config.php"按钮。
        </div>
        <div style="margin-bottom:12px;">
            <a href="https://os.sx-wl.cn/website.html" target="_blank" class="btn-secondary" style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;border-radius:8px;font-size:13px;cursor:pointer;transition:all 0.15s;text-decoration:none;border:1px solid #d1d5db;color:#6b7280;">
                <i class="fas fa-external-link-alt"></i> 进入知岁OS服务商平台
            </a>
        </div>
        <?php foreach ($zsosSettings as $s): ?>
            <div class="config-item">
                <div class="config-key"><?php echo htmlspecialchars($s['key_name']); ?></div>
                <div class="config-desc"><?php echo htmlspecialchars($s['remark']); ?></div>
                <div class="config-value">
                    <input type="text" id="zsos_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>">
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <div style="text-align:right; margin-top:16px;">
        <button class="btn-primary" onclick="saveZsosConfig()"><i class="fas fa-save"></i> 保存知岁OS配置</button>
    </div>
</div>

<!-- 公众号登录配置 -->
<div class="panel-card" style="margin-bottom:16px;">
    <div class="config-group">
        <div class="config-group-title"><i class="fas fa-comment-alt"></i> 公众号登录配置</div>
        <div style="padding:12px 0 8px; font-size:13px; color:#9ca3af;">
            配置微信公众号AppID和密钥，实现公众号能力获取用户头像和微信昵称登录。用户点击"我的"将跳转登录页面。
        </div>
        <?php foreach ($wechatSettings as $s): ?>
            <div class="config-item">
                <div class="config-key"><?php echo htmlspecialchars($s['key_name']); ?></div>
                <div class="config-desc"><?php echo htmlspecialchars($s['remark']); ?></div>
                <div class="config-value">
                    <?php if ($s['key_name'] === 'wechat_force_follow'): ?>
                    <select id="wechat_<?php echo $s['id']; ?>">
                        <option value="0" <?php echo $s['value'] === '0' ? 'selected' : ''; ?>>关闭</option>
                        <option value="1" <?php echo $s['value'] === '1' ? 'selected' : ''; ?>>开启强关模式</option>
                    </select>
                    <?php elseif ($s['key_name'] === 'wechat_enabled'): ?>
                    <select id="wechat_<?php echo $s['id']; ?>">
                        <option value="0" <?php echo $s['value'] === '0' ? 'selected' : ''; ?>>关闭</option>
                        <option value="1" <?php echo $s['value'] === '1' ? 'selected' : ''; ?>>启用公众号登录</option>
                    </select>
                    <?php elseif ($s['key_name'] === 'wechat_qrcode_url'): ?>
                    <div style="display:flex;align-items:center;gap:12px;">
                        <input type="text" id="wechat_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>" style="flex:1;max-width:220px;">
                        <button class="btn-primary" onclick="uploadQrcode()" style="font-size:13px;padding:6px 12px;"><i class="fas fa-upload"></i> 上传</button>
                    </div>
                    <?php else: ?>
                    <input type="text" id="wechat_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>">
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- 配置说明 -->
    <div style="margin-top:16px;padding:16px;background:#f0f9ff;border-radius:8px;border:1px solid #bae6fd;">
        <div style="font-size:14px;font-weight:600;color:#0369a1;margin-bottom:12px;"><i class="fas fa-info-circle"></i> 公众号配置说明</div>
        <div style="font-size:13px;color:#475569;line-height:1.8;">
            <p><strong>1. 获取AppID和密钥：</strong>登录微信公众平台(mp.weixin.qq.com) → 开发 → 基本配置，获取AppID和AppSecret。</p>
            <p><strong>2. 白名单IP配置：</strong>在微信公众平台 → 开发 → 基本配置 → IP白名单中，添加您的服务器IP地址，否则API调用将被拒绝。</p>
            <p><strong>3. JS安全域名：</strong>在微信公众平台 → 设置与开发 → 公众号设置 → 功能设置 → JS接口安全域名，填写您的网站域名(不含协议和端口，如：h5.88-vip.cn)。</p>
            <p><strong>4. 网页授权域名：</strong>在微信公众平台 → 设置与开发 → 公众号设置 → 功能设置 → 网页授权域名，填写您的网站域名。这是公众号登录的核心配置，必须设置！</p>
            <p><strong>5. 强关模式说明：</strong>开启后，未关注公众号的用户访问前端时将弹出遮罩，展示公众号二维码要求扫码关注并绑定登录。关闭则仅登录时使用公众号授权。</p>
            <p><strong>6. 公众号二维码：</strong>在公众平台 → 设置与开发 → 公众号设置 → 二维码，下载公众号二维码图片上传到服务器，填写到下方二维码URL字段。</p>
        </div>
    </div>

    <div style="text-align:right; margin-top:16px;">
        <button class="btn-primary" onclick="saveWechatConfig()"><i class="fas fa-save"></i> 保存公众号配置</button>
    </div>
</div>

<!-- 同步配置到 config.php -->
<div class="panel-card">
    <div class="config-group-title"><i class="fas fa-sync-alt"></i> 配置同步</div>
    <div style="padding:8px 0; font-size:13px; color:#9ca3af;">
        将知岁OS配置从数据库同步写入 config.php 文件，使 PHP 代码可直接使用配置常量。
    </div>
    <div style="text-align:right; margin-top:8px;">
        <button class="btn-primary" onclick="syncConfigToFile()"><i class="fas fa-file-code"></i> 同步到 config.php</button>
    </div>
</div>

<script>
function saveSemesterConfig() {
    var data = {group: 'semester'};
    <?php foreach ($semesterSettings as $s): ?>
    data['<?php echo $s['id']; ?>'] = document.getElementById('semester_<?php echo $s['id']; ?>').value;
    <?php endforeach; ?>

    apiRequest('save_settings', data, function(res) {
        if (res.code === 1) { showToast(res.msg, 'success'); setTimeout(function(){location.reload();}, 500); }
        else { showToast(res.msg, 'error'); }
    });
}

function saveZsosConfig() {
    var data = {group: 'zsos'};
    <?php foreach ($zsosSettings as $s): ?>
    data['<?php echo $s['id']; ?>'] = document.getElementById('zsos_<?php echo $s['id']; ?>').value;
    <?php endforeach; ?>

    apiRequest('save_settings', data, function(res) {
        if (res.code === 1) { showToast(res.msg, 'success'); }
        else { showToast(res.msg, 'error'); }
    });
}

function saveWechatConfig() {
    var data = {group: 'wechat'};
    <?php foreach ($wechatSettings as $s): ?>
    data['<?php echo $s['id']; ?>'] = document.getElementById('wechat_<?php echo $s['id']; ?>').value;
    <?php endforeach; ?>

    apiRequest('save_settings', data, function(res) {
        if (res.code === 1) { showToast(res.msg, 'success'); }
        else { showToast(res.msg, 'error'); }
    });
}

function syncConfigToFile() {
    apiRequest('sync_config_file', {}, function(res) {
        if (res.code === 1) { showToast(res.msg, 'success'); }
        else { showToast(res.msg, 'error'); }
    });
}

function uploadQrcode() {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/jpeg,image/png';
    input.onchange = function(e) {
        var file = e.target.files[0];
        if (!file) return;
        var formData = new FormData();
        formData.append('action', 'upload_image');
        formData.append('file', file);
        formData.append('type', 'qrcode');
        fetch('<?php echo SITE_URL; ?>/admin/api.php', { method: 'POST', body: formData })
        .then(function(res) { return res.json(); })
        .then(function(result) {
            if (result.code === 1) {
                // 找到qrcode的input并设置值
                <?php foreach ($wechatSettings as $s): ?>
                <?php if ($s['key_name'] === 'wechat_qrcode_url'): ?>
                document.getElementById('wechat_<?php echo $s['id']; ?>').value = result.data.url;
                <?php endif; ?>
                <?php endforeach; ?>
                showToast('二维码上传成功', 'success');
            } else { showToast(result.msg || '上传失败', 'error'); }
        })
        .catch(function() { showToast('上传失败', 'error'); });
    };
    input.click();
}
</script>