<?php
ob_start();
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/functions.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'] ?? '');
$sys_version = trim($_POST['sys_version'] ?? '1.0.0');
$register_enabled = isset($_POST['register_enabled']) ? '1' : '0';

updateSiteConfig('site_name', $site_name);
updateSiteConfig('site_keywords', $site_keywords);
updateSiteConfig('site_icp', $site_icp);
updateSiteConfig('site_copyright', $site_copyright);
updateSiteConfig('sys_version', $sys_version);
updateSiteConfig('register_enabled', $register_enabled);

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

// 保存联系配置
$contact_config = [
    'qq_group' => trim($_POST['qq_group'] ?? ''),
    'email' => trim($_POST['email'] ?? ''),
    'service_time' => trim($_POST['service_time'] ?? ''),
    'company_address' => trim($_POST['company_address'] ?? ''),
    'business_tip' => trim($_POST['business_tip'] ?? ''),
];

// 处理微信公众号二维码上传
if (isset($_FILES['wechat_qrcode']) && $_FILES['wechat_qrcode']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['wechat_qrcode'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $max_size = 2 * 1024 * 1024;
    
    if (in_array($file['type'], $allowed_types) && $file['size'] <= $max_size) {
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = 'wechat_qrcode.' . $ext;
        $target = UPLOAD_DIR . $filename;
        
        if (move_uploaded_file($file['tmp_name'], $target)) {
            $contact_config['wechat_qrcode'] = UPLOAD_URL . $filename;
        }
    }
} else {
    // 保留原有二维码
    $old_config = json_decode(getSiteConfig('contact_config') ?? '{}', true);
    $contact_config['wechat_qrcode'] = $old_config['wechat_qrcode'] ?? '';
}

updateSiteConfig('contact_config', json_encode($contact_config));

echo json_encode(['success' => true, 'message' => '配置保存成功']);
exit;