<?php

namespace Modules\Cms\Http\Controllers\Api;

use App\Api\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Cms\Http\Resources\PageCollection;
use Modules\Cms\Http\Resources\PageResource;
use Modules\Cms\Models\Page;

class PageController extends Controller
{

    /**
     * Notes   : 单页列表
     *
     * @Date   : 2021/4/16 10:45 上午
     * @Author : < Jason.C >
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $title    = $request->title;
        $subTitle = $request->sub_title;
        $slug     = $request->slug;
        $tagId    = $request->tag_id;

        $result = Page::when($title, function ($query) use ($title) {
            $query->where('title', 'like', "%{$title}%");
        })->when($subTitle, function ($query) use ($subTitle) {
            $query->where('sub_title', 'like', "%{$subTitle}%");
        })->when($slug, function ($query) use ($slug) {
            $query->where('slug', 'like', "%{$slug}%");
        })->when($tagId, function ($query) use ($tagId) {
            $query->whereHas('tags', function ($tag) use ($tagId) {
                $tag->where('tag_id', $tagId);
            });
        })->where('status', 1)->with(['tags'])->paginate();

        $result = new PageCollection($result);

        return $this->success($result);
    }

    /**
     * Notes   : 单页详情
     *
     * @Date   : 2021/4/16 11:25 上午
     * @Author : < Jason.C >
     * @param  \Modules\Cms\Models\Page  $page
     * @return mixed
     */
    public function show(Page $page)
    {
        $page->incrementClicks();

        return $this->success(new PageResource($page));
    }

    /**
     * Notes: 隐私条款
     *
     * @Author: 玄尘
     * @Date: 2022/8/29 11:59
     */
    public function secret()
    {
        $info = Page::where('slug', 'secret')->first();
        $info->incrementClicks();

        return $this->success(new PageResource($info));
    }

    /**
     * Notes: 服务协议
     *
     * @Author: 玄尘
     * @Date: 2022/8/29 12:00
     * @return \Illuminate\Http\JsonResponse
     */
    public function protocol()
    {
        $info = Page::where('slug', 'protocol')->first();
        $info->incrementClicks();

        return $this->success(new PageResource($info));
    }

}