<?php

namespace App\Http\Controllers;

use App\Models\VideoDanmakus;
use App\Models\Videos;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;

class DanmakuQueryController extends BaseController
{
    public function index()
    {
        $video_list = Videos::query()
            ->withCount("danmakus", "bilibili_danmakus", "ixigua_danmakus", "douyin_danmakus", "programs")
            ->orderByDesc("created_at")
            ->paginate(10)->withQueryString();
        return view("danmaku.index", [
            "video_list" => $video_list,
        ]);
    }

    public function specific_search(Request $request, string $bvid)
    {
        $video = Videos::query()->withCount("danmakus")->where("bvid", "=", $bvid)->firstOrFail();
        $keyword = $request->get("keyword", "");
        $query = VideoDanmakus::query()->where("video_bvid", "=", $bvid);
        if ($keyword) {
            $keyword_split = explode(" ", $keyword);
            foreach ($keyword_split as $_keyword) {
                $_keyword = trim($_keyword);
                if (mb_strlen($_keyword) > 0) {
                    $query->where(function (Builder $_query) use ($_keyword) {
                        $_query->where("content", "like", "%{$_keyword}%", "or")->where("from", "like", "%${_keyword}%", "or");
                    });
                }
            }
        }
        $danmakus = $query->orderBy("created_at", "asc")->paginate(20)->withQueryString();
        return view("danmaku.search_index", [
            "keyword" => $keyword,
            "video" => $video,
            "danmakus" => $danmakus,
        ]);
    }
}