<?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;
}

// 获取参数
$id = intval($_POST['id'] ?? 0);
$type = trim($_POST['type'] ?? '');
$name = trim($_POST['name'] ?? '');
$icon = trim($_POST['icon'] ?? '');
$sort = intval($_POST['sort'] ?? 0);

// 验证
if (empty($type) || empty($name)) {
    echo json_encode(['success' => false, 'message' => '请填写完整信息']);
    exit;
}

// 检查类型是否有效
$valid_types = ['qq', 'gitee', 'wx', 'alipay', 'github', 'google', 'microsoft', 'facebook', 'twitter', 'feishu', 'wework', 'dingtalk', 'sina', 'baidu', 'xiaomi', 'huawei', 'douyin'];
if (!in_array($type, $valid_types)) {
    echo json_encode(['success' => false, 'message' => '无效的登录类型']);
    exit;
}

// 如果提供了自定义图标，验证文件是否存在
if (!empty($icon)) {
    $icon_path = __DIR__ . '/../assets/svg/' . $icon;
    if (!file_exists($icon_path)) {
        echo json_encode(['success' => false, 'message' => '图标文件不存在']);
        exit;
    }
}

if ($id > 0) {
    // 编辑
    $db->query("UPDATE quick_login_config SET name = '$name', icon = '$icon', sort = $sort WHERE id = $id");
    echo json_encode(['success' => true, 'message' => '更新成功']);
} else {
    // 添加 - 检查类型是否已存在
    $check = $db->fetchOne("SELECT id FROM quick_login_config WHERE type = '$type'");
    if ($check) {
        echo json_encode(['success' => false, 'message' => '该登录类型已存在']);
        exit;
    }
    
    $db->query("INSERT INTO quick_login_config (type, name, icon, sort, enabled) VALUES ('$type', '$name', '$icon', $sort, 1)");
    echo json_encode(['success' => true, 'message' => '添加成功']);
}
exit;