<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require __DIR__ . '/../../app/admin-sidebar.php';
require_login();

$adminName = isset($_SESSION['admin_name']) ? (string)$_SESSION['admin_name'] : 'Admin';
$adminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';
$avatarText = strtoupper(substr($adminName !== '' ? $adminName : 'A', 0, 1));
$providers = ai_provider_catalog();

$providerCode = isset($_GET['provider']) ? trim((string)$_GET['provider']) : '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['provider'])) {
    $providerCode = trim((string)$_POST['provider']);
}

$error = '';
$success = '';
$testResult = null;
$testError = '';
$testSuccess = '';
$postAction = isset($_POST['action']) ? trim((string)$_POST['action']) : 'save';

if ($providerCode === '' || !isset($providers[$providerCode])) {
    header('Location: /admin/ai-model/list.php');
    exit;
}

$provider = $providers[$providerCode];
$existing = null;
$form = array(
    'model_key' => '',
    'endpoint_id' => '',
    'api_key' => '',
    'remark' => '',
    'custom_api_url' => '',
    'custom_model' => ''
);
$allowsCustomUrl = !empty($provider['allows_custom_url']);
$allowsCustomModel = !empty($provider['allows_custom_model']);

if ($allowsCustomUrl && $form['custom_api_url'] === '' && isset($provider['api_url']) && $provider['api_url'] !== '') {
    $form['custom_api_url'] = $provider['api_url'];
}

try {
    $existing = find_ai_model_by_provider($providerCode);
    if ($existing) {
        $form['model_key'] = isset($existing['request_headers']) ? $existing['request_headers'] : '';
        $form['endpoint_id'] = $provider['requires_endpoint_id'] && isset($existing['model_name']) ? $existing['model_name'] : '';
        $form['remark'] = isset($existing['remark']) ? $existing['remark'] : '';
        if ($allowsCustomUrl && isset($existing['api_url'])) {
            $form['custom_api_url'] = $existing['api_url'];
        }
        if ($allowsCustomModel && isset($existing['model_name'])) {
            $form['custom_model'] = $existing['model_name'];
        }
    }
} catch (Exception $e) {
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $postAction === 'save') {
    require_csrf();
    $form['model_key'] = isset($_POST['model_key']) ? trim((string)$_POST['model_key']) : '';
    $form['endpoint_id'] = isset($_POST['endpoint_id']) ? trim((string)$_POST['endpoint_id']) : '';
    $form['api_key'] = isset($_POST['api_key']) ? trim((string)$_POST['api_key']) : '';
    $form['remark'] = isset($_POST['remark']) ? trim((string)$_POST['remark']) : '';
    $form['custom_api_url'] = isset($_POST['custom_api_url']) ? trim((string)$_POST['custom_api_url']) : '';
    $form['custom_model'] = isset($_POST['custom_model']) ? trim((string)$_POST['custom_model']) : '';

    $keepKey = isset($_POST['keep_api_key']) && $_POST['keep_api_key'] === '1';
    if ($form['api_key'] === '' && !$keepKey) {
        $error = '请输入 API Key。';
    } else {
        try {
            save_provider_config($providerCode, $form);
            $success = $provider['name'] . ' 配置已保存成功。';
            $existing = find_ai_model_by_provider($providerCode);
            if ($existing) {
                $form['model_key'] = isset($existing['request_headers']) ? $existing['request_headers'] : '';
                $form['endpoint_id'] = $provider['requires_endpoint_id'] && isset($existing['model_name']) ? $existing['model_name'] : '';
                $form['remark'] = isset($existing['remark']) ? $existing['remark'] : '';
                if ($allowsCustomUrl && isset($existing['api_url'])) {
                    $form['custom_api_url'] = $existing['api_url'];
                }
                if ($allowsCustomModel && isset($existing['model_name'])) {
                    $form['custom_model'] = $existing['model_name'];
                }
            }
            $form['api_key'] = '';
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $postAction === 'test') {
    require_csrf();
    $form['model_key'] = isset($_POST['model_key']) ? trim((string)$_POST['model_key']) : '';
    $form['endpoint_id'] = isset($_POST['endpoint_id']) ? trim((string)$_POST['endpoint_id']) : '';
    $form['api_key'] = isset($_POST['api_key']) ? trim((string)$_POST['api_key']) : '';
    $form['remark'] = isset($_POST['remark']) ? trim((string)$_POST['remark']) : '';
    $form['custom_api_url'] = isset($_POST['custom_api_url']) ? trim((string)$_POST['custom_api_url']) : '';
    $form['custom_model'] = isset($_POST['custom_model']) ? trim((string)$_POST['custom_model']) : '';
    try {
        save_provider_config($providerCode, $form);
        $existing = find_ai_model_by_provider($providerCode);
        if ($existing) {
            $form['model_key'] = isset($existing['request_headers']) ? $existing['request_headers'] : '';
            $form['endpoint_id'] = $provider['requires_endpoint_id'] && isset($existing['model_name']) ? $existing['model_name'] : '';
            $form['remark'] = isset($existing['remark']) ? $existing['remark'] : '';
            if ($allowsCustomUrl && isset($existing['api_url'])) {
                $form['custom_api_url'] = $existing['api_url'];
            }
            if ($allowsCustomModel && isset($existing['model_name'])) {
                $form['custom_model'] = $existing['model_name'];
            }
        }
        $form['api_key'] = '';
        $testResult = test_ai_model_by_id($existing['id'], '');
        if (!empty($testResult['success'])) {
            $testSuccess = '接口连通性测试通过，模型已正常响应。';
        } else {
            $testError = $testResult['error_message'] !== '' ? $testResult['error_message'] : '接口已响应但状态异常（HTTP ' . $testResult['http_code'] . '），请检查配置。';
        }
    } catch (Exception $ex) {
        $testError = $ex->getMessage();
    }
}

$hasKey = $existing && isset($existing['api_key']) && $existing['api_key'] !== '';
$keyDecryptFailed = false;
if ($existing && !$hasKey) {
    $rawRow = db_connection()->prepare('SELECT api_key FROM ai_models WHERE id = :id LIMIT 1');
    $rawRow->execute(array(':id' => (int)$existing['id']));
    $rawCheck = $rawRow->fetch(PDO::FETCH_ASSOC);
    if ($rawCheck && is_encrypted_value($rawCheck['api_key'])) {
        $keyDecryptFailed = true;
    }
}
$maskedKey = '';
if ($hasKey) {
    $k = (string)$existing['api_key'];
    $maskedKey = substr($k, 0, 6) . str_repeat('*', max(0, strlen($k) - 10)) . substr($k, -4);
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo e(APP_NAME); ?> - <?php echo e($provider['name']); ?> 配置</title>
    <link rel="stylesheet" href="/assets/css/admin-ui.css">
</head>
<body>
<div class="admin-shell">
    <?php render_admin_sidebar('ai_models', $adminName, $adminUsername, $avatarText); ?>
    <main class="admin-content">
        <div class="content-wrap">
            <header class="topbar">
                <div>
                    <h1><?php echo e($provider['name']); ?> 配置</h1>
                    <p><?php echo e($provider['description']); ?></p>
                </div>
                <div class="topbar-actions"><a class="btn-ghost" href="/admin/ai-model/list.php">返回服务商列表</a></div>
            </header>
            <section class="page-card">
                <div class="card-head"><div><h2>接口配置</h2><p><?php echo $allowsCustomUrl ? '填写 API 地址、Key 并输入模型名称即可接入。' : '填写 API Key 并选择模型，API 地址已根据服务商固定，无需手动填写。'; ?></p></div></div>
                <?php if ($success !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                        <strong style="color:#15803d;">保存成功</strong>
                        <p style="margin:0; color:#166534;"><?php echo e($success); ?></p>
                    </div>
                <?php endif; ?>
                <?php if ($error !== ''): ?>
                    <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                        <strong style="color:#dc2626;">操作失败</strong>
                        <p style="margin:0; color:#b91c1c;"><?php echo e($error); ?></p>
                    </div>
                <?php endif; ?>
                <form method="post" action="/admin/ai-model/config.php?provider=<?php echo e($providerCode); ?>">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="provider" value="<?php echo e($providerCode); ?>">
                    <input type="hidden" name="action" value="save" id="form-action">
                    <div class="form-grid">
                        <div class="input-group" style="grid-column: 1 / -1;">
                            <span>* API Key</span>
                            <input class="input" type="text" name="api_key" value="" placeholder="<?php echo $hasKey ? '已保存，如不修改可留空' : ($keyDecryptFailed ? '原密钥已失效，请重新输入 API Key' : '请输入 ' . e($provider['name']) . ' API Key'); ?>"<?php echo $keyDecryptFailed ? ' style="border-color:#f59e0b;"' : ''; ?>>
                            <?php if ($keyDecryptFailed): ?>
                                <p style="margin:6px 0 0; font-size:12px; color:#dc2626; font-weight:600;">⚠ 原 API Key 因系统密钥变更已无法解密，请重新输入 API Key 后保存。</p>
                            <?php elseif ($hasKey): ?>
                                <p style="margin:6px 0 0; font-size:12px; color:#94a3b8;">当前密钥：<?php echo e($maskedKey); ?></p>
                            <?php endif; ?>
                        </div>
                        <?php if ($hasKey && !$keyDecryptFailed): ?>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <label style="display:flex; gap:8px; align-items:center;"><input type="checkbox" name="keep_api_key" value="1" checked> 保留当前已保存的 API Key（留空时生效）</label>
                            </div>
                        <?php endif; ?>
                        <?php if ($allowsCustomUrl): ?>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <span>* API 地址</span>
                                <input class="input" type="text" name="custom_api_url" value="<?php echo e($form['custom_api_url']); ?>" placeholder="例如 https://sk.slapi.cn 或 https://api.openai.com">
                                <p style="margin:6px 0 0; font-size:12px; color:#94a3b8;">只需填写基础地址，系统会自动拼接 <code>/v1/chat/completions</code>；若已包含完整路径则原样使用。<?php if (isset($provider['api_url']) && $provider['api_url'] !== ''): ?>留空则使用默认地址。<?php endif; ?></p>
                            </div>
                        <?php endif; ?>
                        <?php if ($allowsCustomModel): ?>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <span>* 模型名称</span>
                                <input class="input" type="text" name="custom_model" value="<?php echo e($form['custom_model']); ?>" placeholder="例如 gpt-4o、claude-sonnet-4-20250514、deepseek-chat">
                                <p style="margin:6px 0 0; font-size:12px; color:#94a3b8;">请输入接口支持的模型ID，与请求体中的 <code>model</code> 字段对应。</p>
                            </div>
                        <?php endif; ?>
                        <?php if (!empty($provider['models'])): ?>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <span>* 模型选择</span>
                                <div style="display:flex; flex-direction:column; gap:10px; margin-top:6px;">
                                    <?php foreach ($provider['models'] as $mKey => $mInfo): ?>
                                        <label style="display:flex; align-items:flex-start; gap:10px; padding:12px 14px; border:2px solid <?php echo $form['model_key'] === $mKey ? '#3b82f6' : 'rgba(0,0,0,0.06)'; ?>; border-radius:8px; cursor:pointer; background:<?php echo $form['model_key'] === $mKey ? 'rgba(59,130,246,0.04)' : '#fff'; ?>; transition: border-color .15s;">
                                            <input type="radio" name="model_key" value="<?php echo e($mKey); ?>"<?php echo $form['model_key'] === $mKey ? ' checked' : ''; ?> style="margin-top:2px;">
                                            <div>
                                                <strong style="display:block; font-size:14px;"><?php echo e($mInfo['name']); ?></strong>
                                                <span style="font-size:12px; color:#64748b;"><?php echo e($mInfo['desc']); ?></span>
                                            </div>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        <?php if ($provider['requires_endpoint_id']): ?>
                            <div class="input-group" style="grid-column: 1 / -1;">
                                <span>* 接入点ID (Endpoint ID)</span>
                                <input class="input" type="text" name="endpoint_id" value="<?php echo e($form['endpoint_id']); ?>" placeholder="在火山引擎控制台创建推理接入点后获取，如 ep-20240101xxxxx">
                                <p style="margin:6px 0 0; font-size:12px; color:#94a3b8;">请在<a href="https://console.volcengine.com/ark/region:ark+cn-beijing/endpoint" target="_blank" style="color:#3b82f6;">火山引擎控制台</a>创建推理接入点，将接入点ID填写在此处。</p>
                            </div>
                        <?php endif; ?>
                        <div class="input-group" style="grid-column: 1 / -1;">
                            <span>备注</span>
                            <textarea class="input" name="remark" rows="2" placeholder="可选，填写用途说明或备注"><?php echo e($form['remark']); ?></textarea>
                        </div>
                    </div>
                    <div class="table-note" style="margin-top:16px;"><?php echo $allowsCustomUrl ? '请求方式 POST，请求体按 OpenAI 聊天补全格式自动生成。' . ($provider['api_url'] !== '' ? '默认 API 地址：<code>' . e($provider['api_url']) . '</code>' : '') : 'API 地址已固定为 <code>' . e($provider['api_url']) . '</code>，请求方式 POST，请求体根据所选模型自动生成。'; ?></div>
                    <div class="filter-row" style="margin-top:18px;">
                        <button class="btn-primary" type="submit">保存配置</button>
                        <button class="btn-soft" type="submit" onclick="document.getElementById('form-action').value='test';">测试连通性</button>
                        <a class="btn-ghost" href="/admin/ai-model/list.php">返回</a>
                    </div>
                </form>
            </section>
            <?php if ($testSuccess !== '' || $testError !== '' || $testResult !== null): ?>
                <section class="page-card" style="margin-top:20px;" id="test-result">
                    <div class="card-head"><div><h2>连通性测试结果</h2><p>使用已保存配置发起了一次真实接口请求。</p></div></div>
                    <?php if ($testSuccess !== ''): ?>
                        <div class="mini-item" style="margin-bottom:16px; border-color: rgba(34,197,94,0.18); background: rgba(34,197,94,0.06);">
                            <strong style="color:#15803d;">测试通过</strong>
                            <p style="margin:0; color:#166534;"><?php echo e($testSuccess); ?></p>
                        </div>
                    <?php endif; ?>
                    <?php if ($testError !== ''): ?>
                        <div class="mini-item" style="margin-bottom:16px; border-color: rgba(220,38,38,0.18); background: rgba(220,38,38,0.06);">
                            <strong style="color:#dc2626;">测试失败</strong>
                            <p style="margin:0; color:#b91c1c;"><?php echo e($testError); ?></p>
                        </div>
                    <?php endif; ?>
                    <?php if ($testResult !== null): ?>
                        <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; margin-bottom:16px;">
                            <div class="mini-item"><strong>HTTP 状态码</strong><p><?php echo (int)$testResult['http_code']; ?></p></div>
                            <div class="mini-item"><strong>调用状态</strong><p><?php echo !empty($testResult['success']) ? '成功' : '失败'; ?></p></div>
                        </div>
                        <div class="input-group" style="margin-bottom:16px;">
                            <span>模型回复</span>
                            <textarea class="input" rows="4" readonly><?php echo e($testResult['assistant_text'] !== '' ? $testResult['assistant_text'] : '未提取到 assistant 回复内容'); ?></textarea>
                        </div>
                        <div class="input-group">
                            <span>原始响应</span>
                            <textarea class="input" rows="8" readonly><?php echo e($testResult['response_body']); ?></textarea>
                        </div>
                    <?php endif; ?>
                </section>
                <script>document.getElementById('test-result').scrollIntoView({behavior:'smooth'});</script>
            <?php endif; ?>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
</body>
</html>
