<?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));
$statusOptions = ai_model_status_options();
$catalogOptions = ai_model_catalog_options();
$error = '';
$success = '';
$form = array(
    'model_name' => '',
    'endpoint_id' => '',
    'api_url' => '',
    'api_key' => '',
    'status' => 'enabled',
    'remark' => ''
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_csrf();
    foreach ($form as $key => $value) {
        $form[$key] = isset($_POST[$key]) ? trim((string)$_POST[$key]) : $value;
    }

    if ($form['model_name'] === '' || !isset($catalogOptions[$form['model_name']])) {
        $error = '请选择可用的模型。';
    } elseif (!isset($statusOptions[$form['status']])) {
        $error = '模型状态值无效。';
    } elseif (!filter_var($form['api_url'], FILTER_VALIDATE_URL)) {
        $error = '接口地址格式不正确，请输入完整 URL。';
    } elseif ($form['api_key'] === '') {
        $error = '请输入 API Key。';
    } elseif (!empty($catalogOptions[$form['model_name']]['requires_endpoint_id']) && $form['endpoint_id'] === '') {
        $error = '该模型需要填写接入点ID (Endpoint ID)，请在火山引擎控制台获取。';
    } else {
        try {
            create_ai_model($form);
            $success = 'AI 模型 ' . $catalogOptions[$form['model_name']]['name'] . ' 已创建成功。';
            $form = array(
                'model_name' => '',
                'endpoint_id' => '',
                'api_url' => '',
                'api_key' => '',
                'status' => 'enabled',
                'remark' => ''
            );
        } catch (Exception $e) {
            $error = $e->getMessage();
        }
    }
}
$catalogJson = json_encode($catalogOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?><!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); ?> - 新增AI模型</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>新增AI模型</h1><p>支持 DeepSeek 与火山引擎（豆包）等 OpenAI 兼容模型。</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>带 * 号为必填项，请求参数根据服务商官方文档自动固化。</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/add.php">
                    <?php echo csrf_field(); ?>
                    <div class="form-grid">
                        <div class="input-group"><span>* 模型</span><select class="select" name="model_name" id="sel-model"><option value="">请选择模型</option><?php foreach ($catalogOptions as $key => $item): ?><option value="<?php echo e($key); ?>"<?php echo $form['model_name'] === $key ? ' selected' : ''; ?>><?php echo e($item['name']); ?>（<?php echo e($item['provider']); ?>）</option><?php endforeach; ?></select></div>
                        <div class="input-group"><span>服务商</span><input class="input" type="text" id="txt-provider" value="" readonly></div>
                        <div class="input-group" id="grp-endpoint" style="grid-column: 1 / -1; display:none;"><span>* 接入点ID</span><input class="input" type="text" name="endpoint_id" id="txt-endpoint" value="<?php echo e($form['endpoint_id']); ?>" placeholder="在火山引擎控制台创建推理接入点后获取，如 ep-20240101xxxxx"></div>
                        <div class="input-group" style="grid-column: 1 / -1;"><span>* API地址</span><input class="input" type="text" name="api_url" id="txt-apiurl" value="<?php echo e($form['api_url']); ?>" placeholder="选择模型后自动填充"></div>
                        <div class="input-group"><span>状态</span><select class="select" name="status"><?php foreach ($statusOptions as $key => $label): ?><option value="<?php echo e($key); ?>"<?php echo $form['status'] === $key ? ' selected' : ''; ?>><?php echo e($label); ?></option><?php endforeach; ?></select></div>
                        <div class="input-group" style="grid-column: 1 / -1;"><span>* API Key</span><input class="input" type="text" name="api_key" value="<?php echo e($form['api_key']); ?>" placeholder="请输入对应服务商的 API Key"></div>
                        <div class="input-group" style="grid-column: 1 / -1;"><span>备注</span><textarea class="input" name="remark" rows="3" placeholder="可选，填写用途说明或接入注意事项"><?php echo e($form['remark']); ?></textarea></div>
                    </div>
                    <div class="table-note" style="margin-top:16px;">系统根据所选模型自动固定请求方式（POST）与 OpenAI 兼容请求体；火山引擎模型需额外填写接入点ID。</div>
                    <div class="filter-row" style="margin-top:18px;">
                        <button class="btn-primary" type="submit">提交新增</button>
                        <a class="btn-ghost" href="/admin/ai-model/list.php">取消</a>
                    </div>
                </form>
            </section>
        </div>
    </main>
</div>
<script src="/assets/js/admin-ui.js"></script>
<script>
(function(){
    var catalog = <?php echo $catalogJson; ?>;
    var selModel = document.getElementById('sel-model');
    var txtProvider = document.getElementById('txt-provider');
    var txtApiUrl = document.getElementById('txt-apiurl');
    var grpEndpoint = document.getElementById('grp-endpoint');
    function onModelChange(){
        var key = selModel.value;
        var m = catalog[key] || null;
        txtProvider.value = m ? m.provider : '';
        if(m && !txtApiUrl.value) txtApiUrl.value = m.api_url;
        if(m && m.requires_endpoint_id){
            grpEndpoint.style.display = '';
        } else {
            grpEndpoint.style.display = 'none';
        }
    }
    selModel.addEventListener('change', onModelChange);
    onModelChange();
})();
</script>
</body>
</html>
