<?php
requireAdmin();

$success = '';
$error = '';

// 获取当前配置
$config = getSiteConfig();
?>

<div class="config-container">
    <div class="page-header">
        <h2>网站配置</h2>
        <p>仅超级管理员可修改</p>
    </div>
    
    <?php if ($success): ?>
        <div class="alert alert-success"><?php echo $success; ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="form-card">
        <form method="POST" enctype="multipart/form-data" id="configForm">
            <div class="form-group">
                <label>网站名称</label>
                <input type="text" name="site_name" value="<?php echo htmlspecialchars($config['site_name'] ?? '万能授权系统'); ?>">
            </div>
            
            <div class="form-group">
                <label>网站关键词 (SEO)</label>
                <input type="text" name="site_keywords" value="<?php echo htmlspecialchars($config['site_keywords'] ?? ''); ?>">
                <small>多个关键词用英文逗号分隔</small>
            </div>
            
            <div class="form-group">
                <label>网站LOGO</label>
                <div class="logo-preview">
                    <img src="<?php echo htmlspecialchars($config['site_logo'] ?? '/assets/uploads/logo.png'); ?>" id="logoPreview" style="max-height: 60px;">
                </div>
                <input type="file" name="site_logo" accept="image/*" id="logoInput">
                <small>支持 JPG、PNG、GIF、WEBP，大小不超过2MB</small>
            </div>
            
            <div class="form-group">
                <label>备案号</label>
                <input type="text" name="site_icp" value="<?php echo htmlspecialchars($config['site_icp'] ?? ''); ?>">
                <small>例如：京ICP备12345678号</small>
            </div>
            
            <div class="form-group">
                <label>版权声明</label>
                <input type="text" name="site_copyright" value="<?php echo htmlspecialchars($config['site_copyright'] ?? ''); ?>">
                <small>显示在页脚</small>
            </div>
            
            <div class="form-group">
                <label>联系我们内容</label>
                <textarea name="contact_info" rows="5"><?php echo htmlspecialchars($config['contact_info'] ?? ''); ?></textarea>
                <small>支持HTML标签，可填写邮箱、QQ、电话等</small>
            </div>
            
            <div class="form-group">
                <label>程序版本</label>
                <input type="text" name="sys_version" value="<?php echo htmlspecialchars($config['sys_version'] ?? '1.0.0'); ?>" placeholder="例如：1.0.0">
                <small>显示在用户端版本信息页面</small>
            </div>
            
            <!-- 加密服务配置 -->
            <div class="form-group">
                <label>PHP加密服务价格（元）</label>
                <input type="number" name="encrypt_price" step="0.01" value="<?php echo htmlspecialchars($config['encrypt_price'] ?? '9.90'); ?>">
                <small>普通用户使用加密功能需支付此费用，管理员和代理商免费</small>
            </div>
            
            <div class="form-group">
                <label>加密网站公告（HTML）</label>
                <textarea name="encrypt_announcement" rows="5"><?php echo htmlspecialchars($config['encrypt_announcement'] ?? ''); ?></textarea>
                <small>支持HTML代码，显示在加密网站首页</small>
            </div>
            
            <div class="form-group">
                <label>加密网站API密钥</label>
                <input type="text" name="encrypt_api_key" value="<?php echo htmlspecialchars($config['encrypt_api_key'] ?? ''); ?>" placeholder="留空则不启用API">
                <small>供开发者调用加密API时使用</small>
            </div>
            
            <div class="form-group">
                <label class="checkbox-label">
                    <input type="checkbox" name="register_enabled" value="1" <?php echo ($config['register_enabled'] ?? '1') == '1' ? 'checked' : ''; ?>>
                    开启用户注册
                </label>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary" id="saveBtn">保存配置</button>
            </div>
        </form>
    </div>
</div>

<style>
.logo-preview {
    margin-bottom: 10px;
}
.form-card {
    max-width: 600px;
    background: var(--bg-primary);
    border-radius: var(--radius-md);
    padding: 30px;
    border: 1px solid var(--border-color);
}
.loading-spinner {
    display: inline-block;
    width: 14px;
    height: 14px;
    border: 2px solid #fff;
    border-radius: 50%;
    border-top-color: transparent;
    animation: spin 0.6s linear infinite;
    margin-right: 6px;
    vertical-align: middle;
}
@keyframes spin {
    to { transform: rotate(360deg); }
}
</style>

<script>
document.getElementById('logoInput')?.addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('logoPreview').src = e.target.result;
        };
        reader.readAsDataURL(file);
    }
});

// 表单提交 - AJAX 方式，保存后自动刷新
document.getElementById('configForm')?.addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = document.getElementById('saveBtn');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.innerHTML = '<span class="loading-spinner"></span> 保存中...';
    submitBtn.disabled = true;
    
    fetch('/api/config_save.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (window.showToast) {
                window.showToast(data.message, 'success');
            } else {
                alert(data.message);
            }
            setTimeout(() => {
                location.reload();
            }, 1000);
        } else {
            if (window.showToast) {
                window.showToast(data.message || '保存失败', 'error');
            } else {
                alert(data.message || '保存失败');
            }
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    })
    .catch(error => {
        console.error('错误:', error);
        if (window.showToast) {
            window.showToast('网络错误，请稍后重试', 'error');
        } else {
            alert('网络错误，请稍后重试');
        }
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});
</script>