<?php

namespace pictpostpersonal;

use pictpostpersonal\controller\ControllerBase;

// 記事ページ用 関連記事一覧作成用プラグイン
function parseAttributes($input)
{
    $pattern = '/\{plugin\s+(.*?)\}/';
    if (preg_match($pattern, $input, $matches)) {
        $attributes = [];
        $attr_string = $matches[1];

        // キーと値を抽出（値は "..." または 単語）
        preg_match_all('/(\w+)="([^"]*)"|(\w+)=([^\s]*)/', $attr_string, $attr_matches, PREG_SET_ORDER);

        foreach ($attr_matches as $match) {
            $key = $match[1] ?: $match[3]; // キー
            $value = $match[2] ?: $match[4]; // 値
            $attributes[$key] = $value;
        }

        return $attributes;
    }
    return null; // マッチしなかった場合
}

function plugin($db, $setting, $contents, $plugin_tag): array
{
    $article = new model\Article($db, $setting);
    $attr = parseAttributes($plugin_tag);
    $contents = preg_replace('/\{plugin name="relative_list"\s+(.*?)\}/i', '', $contents);
    if (!isset($attr['tags'])) {
        return ['contents' => $contents, 'values' => [], 'key' => 'plugin_relative_list_articles'];
    }

    $articles = $article->searchByTagWithCount($attr['tags'], false, 'created_at, id desc', 4, 1);
    return ['contents' => $contents, 'values' => $articles, 'key' => 'plugin_relative_list_articles'];
}

/*

{plugin name="relative_list" tags="news technology"}

*/
