<?php
if (!defined('APP_ROOT')) exit;

function api_config(): array
{
    $raw = plugin_config('api', []);

    return [
        'enabled' => !isset($raw['enabled']) || (int)$raw['enabled'] === 1,
        'index_limit' => min(100, max(10, (int)($raw['index_limit'] ?? 30))),
        'view_limit' => min(200, max(20, (int)($raw['view_limit'] ?? 100))),
    ];
}

function api_json_headers(): void
{
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: public, max-age=60');
}

function api_avatar_url(array $user): string
{
    $style = (string)($user['avatar_style'] ?? 'dylan');
    $seed = (string)($user['avatar_seed'] ?? '1');

    return avatar_remote_url($style, $seed);
}

function api_index_rows(int $limit): array
{
    return q(
        'SELECT
            t.id,
            t.title,
            t.reply_count,
            t.created_at,
            t.last_reply_at,
            t.user_id,
            u.username,
            u.avatar_style,
            u.avatar_seed
        FROM app_topics t
        JOIN app_users u ON u.id=t.user_id
        ORDER BY t.last_reply_at DESC,t.id DESC
        LIMIT ?',
        [$limit]
    )->fetchAll();
}

function api_topic_row(int $topic_id): ?array
{
    $row = one(
        'SELECT
            t.id,
            t.title,
            t.body,
            t.created_at,
            t.user_id,
            u.username,
            u.avatar_style,
            u.avatar_seed
        FROM app_topics t
        JOIN app_users u ON u.id=t.user_id
        WHERE t.id=?',
        [$topic_id]
    );

    return is_array($row) ? $row : null;
}

function api_reply_rows(int $topic_id, int $limit): array
{
    return q(
        'SELECT
            r.id,
            r.body,
            r.created_at,
            r.user_id,
            u.username,
            u.avatar_style,
            u.avatar_seed
        FROM app_replies r
        JOIN app_users u ON u.id=r.user_id
        WHERE r.topic_id=?
        ORDER BY r.id ASC
        LIMIT ?',
        [$topic_id, $limit]
    )->fetchAll();
}

function api_index_page(array $plugin): void
{
    $config = api_config();

    if (!$config['enabled']) {
        err('API 未启用', 404);
    }

    $data = [];

    foreach (api_index_rows($config['index_limit']) as $row) {
        $lasttime = max(
            (int)$row['created_at'],
            (int)$row['last_reply_at']
        );

        $data[] = [
            'own' => (string)$row['username'],
            'lasttime' => (string)$lasttime,
            'reply' => (int)$row['reply_count'],
            'title' => (string)$row['title'],
            'postid' => (string)$row['id'],
            'tag' => 0,
            'perm' => 0,
            'img' => api_avatar_url($row),
            'pintop' => 0,
        ];
    }

    api_json_headers();

    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );

    exit;
}

function api_view_page(array $plugin): void
{
    $config = api_config();

    if (!$config['enabled']) {
        err('API 未启用', 404);
    }

    $topic_id = max(1, (int)($_GET['id'] ?? 0));

    $topic = api_topic_row($topic_id);

    if (!$topic) {
        err('主题不存在', 404);
    }

    $data = [];

    $data[] = [
        'id' => 1,
        'user' => (string)$topic['username'],
        'img' => api_avatar_url($topic),
        'op' => true,
        'post' => (string)$topic['body'],
        'post_time' => (int)$topic['created_at'],
        'tag' => 1,
        'postid' => (string)$topic['id'],
    ];

    $floor = 2;

    foreach (api_reply_rows($topic_id, $config['view_limit']) as $reply) {
        $data[] = [
            'id' => $floor,
            'user' => (string)$reply['username'],
            'img' => api_avatar_url($reply),
            'op' => false,
            'post' => (string)$reply['body'],
            'post_time' => (int)$reply['created_at'],
            'tag' => 0,
            'postid' => (string)$reply['id'],
        ];

        $floor++;
    }

    api_json_headers();

    echo json_encode(
        $data,
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );

    exit;
}

function api_admin_page(array $plugin): string
{
    need_admin();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        require_post();
        need_manage();

        plugin_save_config('api', [
            'enabled' => isset($_POST['enabled']) ? 1 : 0,
            'index_limit' => min(100, max(10, (int)($_POST['index_limit'] ?? 30))),
            'view_limit' => min(200, max(20, (int)($_POST['view_limit'] ?? 100))),
        ]);

        set_flash('API 设置已保存');

        go(admin_url(['tab' => 'api']));
    }

    $config = api_config();

    $index_url = route_url('api_index');
    $view_url = route_url('api_view') . '&id=1';

    $form =
        '<form class="plugin-settings-form" method="post" action="' . h(admin_url(['tab' => 'api'])) . '">'
        . form_token()
        . checkbox('启用 API', 'enabled', $config['enabled'])
        . number_input('首页主题数量', 'index_limit', $config['index_limit'], 10, 100, true)
        . number_input('详情回复数量', 'view_limit', $config['view_limit'], 20, 200, true)
        . '<button>保存设置</button>'
        . '</form>';

    return
        '<div class="admin-list-panel plugin-manage-panel">'
        . admin_list_head(
            '<div class="admin-plugin-summary"><strong>RESTful API</strong><span>提供 RESTful API 接口</span></div>',
            ''
        )
        . '<div class="plugin-panel-body">'
        . '<p>Index API：<a href="' . h($index_url) . '" target="_blank" rel="noopener">' . h($index_url) . '</a></p>'
        . '<p>View API：<a href="' . h($view_url) . '" target="_blank" rel="noopener">' . h($view_url) . '</a></p>'
        . $form
        . '</div>'
        . '</div>';
}

return [
    'id' => 'restful_api',
    'name' => 'RESTful API',
    'version' => '1.0.3',
    'description' => '提供 RESTful API 接口以输出列表和帖子的 JSON 数据供第三方客户端APP调用',
    'author' => 'beku',
    'routes' => [
        'api_index' => 'api_index_page',
        'api_view' => 'api_view_page',
    ],
    'admin_tabs' => [
        'api' => 'api_admin_page',
    ],
];