<?php
require_once dirname(__DIR__) . '/config.php';

header('Content-Type: application/json');

// 检查登录和权限
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

// 获取表单数据
$site_name = trim($_POST['site_name'] ?? '');
$site_keywords = trim($_POST['site_keywords'] ?? '');
$site_icp = trim($_POST['site_icp'] ?? '');
$site_copyright = trim($_POST['site_copyright'] ?? '');
$contact_info = trim($_POST['contact_info'] ?? '');
$register_enabled = isset($_POST['register_enabled']) ? '1' : '0';
$sys_version = trim($_POST['sys_version'] ?? '1.0.0');

// 处理LOGO上传
$site_logo = getSiteConfig('site_logo');
if (isset($_FILES['site_logo']) && $_FILES['site_logo']['error'] == 0) {
    $file = $_FILES['site_logo'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    
    if (in_array($file['type'], $allowed_types) && $file['size'] < 2 * 1024 * 1024) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'logo_' . time() . '.' . $ext;
        $target = UPLOAD_DIR . $filename;
        
        if (move_uploaded_file($file['tmp_name'], $target)) {
            $site_logo = UPLOAD_URL . $filename;
            updateSiteConfig('site_logo', $site_logo);
        }
    }
}

// 保存配置
updateSiteConfig('site_name', $site_name);
updateSiteConfig('site_keywords', $site_keywords);
updateSiteConfig('site_icp', $site_icp);
updateSiteConfig('site_copyright', $site_copyright);
updateSiteConfig('contact_info', $contact_info);
updateSiteConfig('register_enabled', $register_enabled);
updateSiteConfig('sys_version', $sys_version);

echo json_encode(['success' => true, 'message' => '网站配置已保存']);
exit;
?>