<?php
/**
 * api_publish.php - 独立文章发布接口（绕过 CMS apikey 限制）
 * 
 * 放到 FastAdmin 网站根目录（与 index.php 同级）
 * 
 * POST 请求体 JSON:
 * {"token":"hermes2026","channel_id":227,"title":"标题","content":"<p>正文</p>"}
 */
define('APP_PATH', __DIR__ . '/application/');
define('BIND_MODULE', '');
require __DIR__ . '/thinkphp/start.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit(json_encode(['code' => 0, 'msg' => '仅支持POST']));
}

$input = json_decode(file_get_contents('php://input'), true);
if (!$input || ($input['token'] ?? '') !== 'hermes2026') {
    http_response_code(403);
    exit(json_encode(['code' => 0, 'msg' => '鉴权失败']));
}

if (empty($input['title']) || empty($input['content'])) {
    http_response_code(400);
    exit(json_encode(['code' => 0, 'msg' => '缺少必填字段']));
}

if (empty($input['channel_id']) && empty($input['channel'])) {
    http_response_code(400);
    exit(json_encode(['code' => 0, 'msg' => '缺少 channel_id 或 channel']));
}

try {
    if (!empty($input['channel_id'])) {
        $channel = \addons\cms\model\Channel::get(intval($input['channel_id']));
    } else {
        $channel = \addons\cms\model\Channel::where('name', $input['channel'])->find();
    }
    if (!$channel || $channel['status'] != 'normal') {
        exit(json_encode(['code' => 0, 'msg' => '栏目未找到']));
    }

    $model = \addons\cms\model\Modelx::get($channel['model_id']);
    \think\Db::startTrans();
    $archives = new \app\admin\model\cms\Archives;
    $archives->allowField(true)->save([
        'channel_id'  => $channel['id'],
        'model_id'    => $model['id'],
        'title'       => $input['title'],
        'content'     => $input['content'],
        'description' => $input['description'] ?? '',
        'image'       => $input['image'] ?? '',
        'user_id'     => $input['user_id'] ?? 1,
        'publishtime' => time(),
        'weigh'       => 0,
        'status'      => 'normal',
    ]);
    \think\Db::commit();

    echo json_encode([
        'code' => 1, 'msg' => 'OK',
        'data' => ['id' => $archives->id, 'url' => $archives->fullurl]
    ], JSON_UNESCAPED_UNICODE);
} catch (\Exception $e) {
    \think\Db::rollback();
    http_response_code(500);
    echo json_encode(['code' => 0, 'msg' => $e->getMessage()]);
}
