<?php
/**
 * 跨站节点授权管理 - 被对接方后台
 */
$title = '跨站授权管理';
include __DIR__ . '/head.php';

// 凭证弹窗 API 根地址（与 common 中 $hosturl 一致）
if (!isset($parts) || !is_array($parts) || empty($parts['host'])) {
	$u = isset($hosturl) ? parse_url($hosturl) : [];
	$parts = [
		'protocol' => (!empty($u['scheme']) && strtolower($u['scheme']) === 'https') ? 'https' : 'http',
		'host' => ($u['host'] ?? ($_host ?? 'localhost')) . (isset($u['port']) && $u['port'] && !in_array((int)$u['port'], [80, 443], true) ? ':' . $u['port'] : ''),
	];
}

$act = isset($_GET['my']) ? trim($_GET['my']) : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
?>

<div class="p-4 md:p-6">
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="p-4 md:p-6 border-b border-gray-200 flex items-center justify-between">
            <h2 class="text-base md:text-lg font-semibold text-gray-800">跨站授权管理</h2>
            <a href="?my=add" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition">
                <i class="fas fa-plus mr-2"></i>添加授权
            </a>
        </div>
        
        <?php if ($act == 'add' || $act == 'edit'): ?>
        <!-- 添加/编辑表单 -->
        <?php
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $row = null;
        if ($act == 'edit' && $id > 0) {
            $row = $DB->getRow("SELECT * FROM pre_node_auth WHERE id = ?", [$id]);
            if (!$row) {
                exit('<script>showToast("授权不存在", "error"); setTimeout(function(){location.href="?"},1000);</script>');
            }
        }
        
        // 获取分类列表
        $classList = [];
        $rs = $DB->query("SELECT id, name FROM pre_login_class ORDER BY sort ASC");
        while ($res = $rs->fetch()) {
            $classList[] = $res;
        }
        
        // 获取节点列表
        $nodeList = [];
        $rs = $DB->query("SELECT id, citybz, cids FROM pre_loginconfig WHERE status = 1 ORDER BY sort ASC");
        while ($res = $rs->fetch()) {
            $nodeList[] = $res;
        }
        ?>
        
        <div class="p-4 md:p-6">
            <form id="formAuth" onsubmit="saveAuth();return false;" class="space-y-6">
                <input type="hidden" name="id" value="<?php echo $id; ?>">
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">授权类型</label>
                    <div class="md:col-span-3">
                        <select name="auth_type" id="auth_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" onchange="toggleAuthType()">
                            <option value="1" <?php echo ($row && $row['auth_type'] == 1) ? 'selected' : ''; ?>>全站节点（所有节点）</option>
                            <option value="2" <?php echo ($row && $row['auth_type'] == 2) ? 'selected' : ''; ?>>分类节点（指定分类下所有节点）</option>
                            <option value="3" <?php echo ($row && $row['auth_type'] == 3) ? 'selected' : ''; ?>>单节点（指定单个节点）</option>
                        </select>
                    </div>
                </div>
                
                <div id="class_row" class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center" style="display:none;">
                    <label class="text-sm font-medium text-gray-700">选择分类</label>
                    <div class="md:col-span-3">
                        <select name="class_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <?php foreach ($classList as $c): ?>
                            <option value="<?php echo $c['id']; ?>" <?php echo ($row && $row['class_id'] == $c['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div id="node_row" class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center" style="display:none;">
                    <label class="text-sm font-medium text-gray-700">选择节点</label>
                    <div class="md:col-span-3">
                        <select name="node_id" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <?php foreach ($nodeList as $n): ?>
                            <option value="<?php echo $n['id']; ?>" <?php echo ($row && $row['node_id'] == $n['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($n['citybz']); ?> (ID: <?php echo $n['id']; ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">App ID</label>
                    <div class="md:col-span-3">
                        <div class="flex gap-2">
                            <input type="text" name="app_id" id="app_id" value="<?php echo $row ? $row['app_id'] : ''; ?>" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" <?php echo $row ? 'readonly' : ''; ?> placeholder="自动生成或手动填写">
                            <?php if (!$row): ?>
                            <button type="button" onclick="generateAppId()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">生成</button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">App Secret</label>
                    <div class="md:col-span-3">
                        <div class="flex gap-2">
                            <input type="text" name="app_secret" id="app_secret" value="<?php echo $row ? $row['app_secret'] : ''; ?>" class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="自动生成或手动填写">
                            <button type="button" onclick="generateAppSecret()" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition">生成</button>
                        </div>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">对接方站点名称</label>
                    <div class="md:col-span-3">
                        <input type="text" name="site_name" value="<?php echo $row ? htmlspecialchars($row['site_name']) : ''; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="对接方站点名称">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">对接方站点URL</label>
                    <div class="md:col-span-3">
                        <input type="url" name="site_url" value="<?php echo $row ? htmlspecialchars($row['site_url']) : ''; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="https://example.com">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">联系QQ</label>
                    <div class="md:col-span-3">
                        <input type="text" name="contact_qq" value="<?php echo $row ? htmlspecialchars($row['contact_qq']) : ''; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="联系QQ号">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">授权到期时间</label>
                    <div class="md:col-span-3">
                        <input type="datetime-local" name="expire_time" value="<?php echo $row && $row['expire_time'] ? date('Y-m-d\TH:i', strtotime($row['expire_time'])) : ''; ?>" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <p class="mt-1 text-xs text-gray-500">留空表示永久有效</p>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-center">
                    <label class="text-sm font-medium text-gray-700">状态</label>
                    <div class="md:col-span-3">
                        <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="1" <?php echo (!$row || $row['status'] == 1) ? 'selected' : ''; ?>>启用</option>
                            <option value="0" <?php echo ($row && $row['status'] == 0) ? 'selected' : ''; ?>>禁用</option>
                        </select>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-start">
                    <label class="text-sm font-medium text-gray-700 pt-2">备注</label>
                    <div class="md:col-span-3">
                        <textarea name="remark" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="备注信息"><?php echo $row ? htmlspecialchars($row['remark']) : ''; ?></textarea>
                    </div>
                </div>
                
                <div class="flex items-center gap-4 pt-4">
                    <button type="submit" class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">
                        <i class="fas fa-save mr-2"></i>保存
                    </button>
                    <button type="button" class="px-6 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 font-medium rounded-lg transition" onclick="location.href='?'">
                        <i class="fas fa-arrow-left mr-2"></i>返回
                    </button>
                </div>
            </form>
        </div>
        
        <?php else: ?>
        <!-- 搜索区域 -->
        <div class="p-4 md:p-6 border-b border-gray-200">
            <form method="GET" class="flex flex-wrap items-center gap-3">
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" class="flex-1 min-w-[200px] px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="搜索QQ / 站点名称 / 站点URL">
                <button type="submit" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition">
                    <i class="fas fa-search mr-2"></i>搜索
                </button>
                <?php if ($search): ?>
                <a href="?" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-700 font-medium rounded-lg transition">清除</a>
                <?php endif; ?>
            </form>
        </div>
        
        <!-- 列表 -->
        <div class="overflow-x-auto">
            <table class="w-full min-w-[1200px]">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">ID</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">App ID</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">授权类型</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">节点名称</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">对接方站点</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">联系QQ</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">到期时间</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">状态</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase whitespace-nowrap">操作</th>
                    </tr>
                </thead>
                <tbody id="listBody" class="divide-y divide-gray-200">
                    <tr><td colspan="9" class="px-4 py-8 text-center text-gray-400">加载中...</td></tr>
                </tbody>
            </table>
        </div>
        
        <div class="p-4 border-t border-gray-200 flex items-center justify-between">
            <p class="text-sm text-gray-600">共有 <span id="total" class="font-medium">0</span> 条记录</p>
            <select id="page" class="px-3 py-2 border border-gray-300 rounded-lg text-sm" onchange="loadList()">
            </select>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- 凭证信息弹窗 -->
<div id="credentialModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-lg font-semibold">凭证信息</h3>
            <button type="button" class="text-gray-400 hover:text-gray-600" onclick="closeCredentialModal()">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div class="p-4 space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">API地址</label>
                <div class="flex gap-2">
                    <input type="text" id="modal_api_url" class="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50" readonly>
                    <button type="button" onclick="copyToClipboard('modal_api_url')" class="px-3 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg"><i class="fas fa-copy"></i></button>
                </div>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">App ID</label>
                <div class="flex gap-2">
                    <input type="text" id="modal_app_id" class="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50" readonly>
                    <button type="button" onclick="copyToClipboard('modal_app_id')" class="px-3 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg"><i class="fas fa-copy"></i></button>
                </div>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">App Secret</label>
                <div class="flex gap-2">
                    <input type="text" id="modal_app_secret" class="flex-1 px-3 py-2 border border-gray-300 rounded-lg bg-gray-50" readonly>
                    <button type="button" onclick="copyToClipboard('modal_app_secret')" class="px-3 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg"><i class="fas fa-copy"></i></button>
                </div>
            </div>
        </div>
        <div class="p-4 border-t border-gray-200 flex justify-end">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg" onclick="closeCredentialModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 调整时长弹窗 -->
<div id="expireModal" class="fixed inset-0 bg-black/50 hidden items-center justify-center z-50 p-4">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-md">
        <div class="p-4 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-lg font-semibold">调整到期时间</h3>
            <button type="button" class="text-gray-400 hover:text-gray-600" onclick="closeExpireModal()">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div class="p-4 space-y-4">
            <input type="hidden" id="expire_auth_id">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">当前到期时间</label>
                <p id="current_expire_time" class="text-sm text-gray-600">-</p>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">调整方式</label>
                <select id="expire_action" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                    <option value="add">增加时长</option>
                    <option value="subtract">减少时长</option>
                    <option value="set">设置为永久</option>
                    <option value="custom">自定义时间</option>
                </select>
            </div>
            <div id="expire_amount_row">
                <label class="block text-sm font-medium text-gray-700 mb-1">时长数量</label>
                <div class="flex gap-2">
                    <input type="number" id="expire_amount" class="flex-1 px-3 py-2 border border-gray-300 rounded-lg" value="30" min="1">
                    <select id="expire_unit" class="px-3 py-2 border border-gray-300 rounded-lg">
                        <option value="day">天</option>
                        <option value="month">月</option>
                        <option value="year">年</option>
                    </select>
                </div>
            </div>
            <div id="expire_custom_row" style="display:none;">
                <label class="block text-sm font-medium text-gray-700 mb-1">自定义到期时间</label>
                <input type="datetime-local" id="expire_custom_time" class="w-full px-3 py-2 border border-gray-300 rounded-lg">
            </div>
        </div>
        <div class="p-4 border-t border-gray-200 flex justify-end gap-3">
            <button type="button" class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg" onclick="closeExpireModal()">取消</button>
            <button type="button" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg" onclick="saveExpireTime()">保存</button>
        </div>
    </div>
</div>

<style>
.status-toggle { cursor: pointer; }
.status-toggle:hover { opacity: 0.8; }
</style>

<script>
var currentPage = 1;
var currentSearch = '<?php echo addslashes($search); ?>';
var apiBase = '<?php echo htmlspecialchars($parts["protocol"] . "://" . $parts["host"]); ?>/api/node.php';

$(document).ready(function() {
    <?php if ($act != 'add' && $act != 'edit'): ?>
    loadList();
    <?php else: ?>
    toggleAuthType();
    <?php endif; ?>
    
    // 监听调整方式变化
    $('#expire_action').on('change', function() {
        var action = $(this).val();
        if (action === 'set') {
            $('#expire_amount_row').hide();
            $('#expire_custom_row').hide();
        } else if (action === 'custom') {
            $('#expire_amount_row').hide();
            $('#expire_custom_row').show();
        } else {
            $('#expire_amount_row').show();
            $('#expire_custom_row').hide();
        }
    });
});

function toggleAuthType() {
    var authType = $('#auth_type').val();
    $('#class_row').hide();
    $('#node_row').hide();
    
    if (authType == '2') {
        $('#class_row').show();
    } else if (authType == '3') {
        $('#node_row').show();
    }
}

function generateAppId() {
    var appId = 'node_' + Math.random().toString(36).substring(2, 10) + Date.now().toString(36);
    $('#app_id').val(appId);
}

function generateAppSecret() {
    var appSecret = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
    $('#app_secret').val(appSecret);
}

function loadList() {
    $.ajax({
        url: 'ajax.php?act=node_auth_list',
        type: 'GET',
        data: { page: currentPage, search: currentSearch },
        dataType: 'json',
        success: function(res) {
            if (res.code == 0) {
                renderList(res.data.list);
                $('#total').text(res.data.total);
                renderPagination(res.data.totalPages);
            } else {
                showToast(res.msg, 'error');
            }
        },
        error: function() {
            showToast('请求失败', 'error');
        }
    });
}

function renderList(list) {
    var html = '';
    var authTypes = {1: '全站', 2: '分类', 3: '单节点'};
    
    for (var i = 0; i < list.length; i++) {
        var item = list[i];
        var expireLabel = item.expire_time ? (new Date(item.expire_time) < new Date() ? '<span class="text-red-600">已过期</span>' : item.expire_time) : '<span class="text-gray-400">永久</span>';
        
        var statusHtml = item.status == 1 
            ? '<span class="status-toggle px-2 py-1 text-xs rounded-full bg-green-100 text-green-700" onclick="toggleStatus(' + item.id + ', 0)">启用</span>'
            : '<span class="status-toggle px-2 py-1 text-xs rounded-full bg-red-100 text-red-700" onclick="toggleStatus(' + item.id + ', 1)">禁用</span>';
        
        var expireTimeData = item.expire_time || '';
        
        html += '<tr>' +
            '<td class="px-4 py-3 text-sm">' + item.id + '</td>' +
            '<td class="px-4 py-3 text-sm font-mono">' + item.app_id + '</td>' +
            '<td class="px-4 py-3 text-sm">' + authTypes[item.auth_type] + '</td>' +
            '<td class="px-4 py-3 text-sm">' + (item.node_name || '<span class="text-gray-400">-</span>') + '</td>' +
            '<td class="px-4 py-3 text-sm">' + (item.site_name || '-') + (item.site_url ? '<br><span class="text-xs text-gray-400">' + item.site_url + '</span>' : '') + '</td>' +
            '<td class="px-4 py-3 text-sm">' + (item.contact_qq || '-') + '</td>' +
            '<td class="px-4 py-3 text-sm"><span class="cursor-pointer hover:text-blue-600" onclick="showExpireModal(' + item.id + ', \'' + expireTimeData + '\')">' + expireLabel + '</span></td>' +
            '<td class="px-4 py-3 text-sm">' + statusHtml + '</td>' +
            '<td class="px-4 py-3 text-sm">' +
                '<button onclick="showCredential(' + item.id + ', \'' + item.app_id + '\', \'' + item.app_secret + '\')" class="text-blue-600 hover:text-blue-800 mr-2"><i class="fas fa-key"></i>凭证</button>' +
                '<a href="?my=edit&id=' + item.id + '" class="text-green-600 hover:text-green-800 mr-2"><i class="fas fa-edit"></i>编辑</a>' +
                '<button onclick="deleteAuth(' + item.id + ')" class="text-red-600 hover:text-red-800"><i class="fas fa-trash"></i>删除</button>' +
            '</td>' +
        '</tr>';
    }
    
    $('#listBody').html(html || '<tr><td colspan="9" class="px-4 py-8 text-center text-gray-400">暂无数据</td></tr>');
}

function renderPagination(totalPages) {
    var html = '';
    for (var i = 1; i <= totalPages; i++) {
        html += '<option value="' + i + '" ' + (i == currentPage ? 'selected' : '') + '>第' + i + '页</option>';
    }
    $('#page').html(html);
}

function toggleStatus(id, newStatus) {
    $.ajax({
        url: 'ajax.php?act=node_auth_toggle_status',
        type: 'POST',
        data: { id: id, status: newStatus },
        dataType: 'json',
        success: function(res) {
            if (res.code == 0) {
                showToast(res.msg, 'success');
                loadList();
            } else {
                showToast(res.msg, 'error');
            }
        },
        error: function() {
            showToast('请求失败', 'error');
        }
    });
}

function showExpireModal(id, expireTime) {
    $('#expire_auth_id').val(id);
    $('#current_expire_time').text(expireTime || '永久');
    $('#expire_action').val('add');
    $('#expire_amount').val(30);
    $('#expire_unit').val('day');
    $('#expire_amount_row').show();
    $('#expire_custom_row').hide();
    $('#expireModal').removeClass('hidden').addClass('flex');
}

function closeExpireModal() {
    $('#expireModal').removeClass('flex').addClass('hidden');
}

function saveExpireTime() {
    var id = $('#expire_auth_id').val();
    var action = $('#expire_action').val();
    var data = { id: id, action: action };
    
    if (action === 'add' || action === 'subtract') {
        data.amount = $('#expire_amount').val();
        data.unit = $('#expire_unit').val();
    } else if (action === 'custom') {
        data.custom_time = $('#expire_custom_time').val();
    }
    
    $.ajax({
        url: 'ajax.php?act=node_auth_adjust_expire',
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(res) {
            if (res.code == 0) {
                showToast(res.msg, 'success');
                closeExpireModal();
                loadList();
            } else {
                showToast(res.msg, 'error');
            }
        },
        error: function() {
            showToast('请求失败', 'error');
        }
    });
}

function saveAuth() {
    $.ajax({
        url: 'ajax.php?act=node_auth_save',
        type: 'POST',
        data: $('#formAuth').serialize(),
        dataType: 'json',
        success: function(res) {
            if (res.code == 0) {
                showToast(res.msg, 'success');
                setTimeout(function() { location.href = '?'; }, 1000);
            } else {
                showToast(res.msg, 'error');
            }
        },
        error: function() {
            showToast('请求失败', 'error');
        }
    });
}

function deleteAuth(id) {
    if (!confirm('确定要删除此授权吗？')) return;
    
    $.ajax({
        url: 'ajax.php?act=node_auth_delete',
        type: 'POST',
        data: { id: id },
        dataType: 'json',
        success: function(res) {
            if (res.code == 0) {
                showToast(res.msg, 'success');
                loadList();
            } else {
                showToast(res.msg, 'error');
            }
        },
        error: function() {
            showToast('请求失败', 'error');
        }
    });
}

function showCredential(id, appId, appSecret) {
    $('#modal_api_url').val(apiBase);
    $('#modal_app_id').val(appId);
    $('#modal_app_secret').val(appSecret);
    $('#credentialModal').removeClass('hidden').addClass('flex');
}

function closeCredentialModal() {
    $('#credentialModal').removeClass('flex').addClass('hidden');
}

function copyToClipboard(inputId) {
    var input = document.getElementById(inputId);
    input.select();
    document.execCommand('copy');
    showToast('已复制', 'success');
}

$('#page').on('change', function() {
    currentPage = $(this).val();
    loadList();
});
</script>

<?php include 'foot.php'; ?>
