<?php

namespace App\Http\Controllers;

use App\Services\LiquidRenderer;
use Illuminate\Http\Request;
use App\Models\SitePage;
use App\Models\SitePageTag;

class CollectionController extends Controller
{

    protected $liquidRenderer;

    public function __construct(LiquidRenderer $liquidRenderer)
    {
        $this->liquidRenderer = $liquidRenderer;
    }

    public function index()
    {

        //模板支持多级目录，需要目录符号
        $output = LiquidRenderer::render('collection_list.liquid', [

        ]);

        return response($output);
    }

    public function detail($slug)
    {

        // Find the tag by either slug or id
        $tag = SitePageTag::where('dist_id', getDistId())
            ->where(function ($query) use ($slug) {
                $query->where('slug', $slug)
                    ->orWhere('id', $slug);
            })
            ->first();

        if (!$tag) {

            abort('404','tag not found.');
        }


        // 获取关联的 pages

        $perPage = 12;
        $pages = $tag->pages($perPage); // 使用分页

        // 创建分页数据结构
        $paginator = [
            'previous_page' => $pages->previousPageUrl() ? true : false, // 是否有上一页
            'previous_page_url' => $pages->previousPageUrl(), // 上一页的 URL
            'next_page' => $pages->nextPageUrl() ? true : false, // 是否有下一页
            'next_page_url' => $pages->nextPageUrl(), // 下一页的 URL
            'current_page' => $pages->currentPage(), // 当前页
            'total_pages' => $pages->lastPage(), // 总页数
            'pages' => range(1, $pages->lastPage()), // 页码数组
            'page_url' => array_combine(
                range(1, $pages->lastPage()),
                array_map(fn($page) => $pages->url($page), range(1, $pages->lastPage()))
            ), // 每页的 URL
        ];


        // 构建导航数据 开始
        $breadcrumbs = [
            [
                'url' => '/',
                'name' => 'Home',
            ]
        ];


        $breadcrumbs[] = [
            'url' => '#',
            'name' => $tag->name,
        ];

        // 构建导航数据 结束

        //模板支持多级目录，需要目录符号
        $output = LiquidRenderer::render('collection_list.liquid', [
            'tag' => $tag,
            'pages' => $pages,
            'paginator' => $paginator, // 分页信息
            'breadcrumbs' => $breadcrumbs,
        ]);

        return response($output);
    }


}
