<?php

namespace App\Http\Controllers\V1\User;

use App\Http\Controllers\V1\Controller;
use App\Models\EpisodesList;
use App\Models\UserCollect;
use Dingo\Api\Http\Request;
use Illuminate\Database\Eloquent\Builder;

class CollectController extends Controller
{
    // 收藏记录
    public function record(Request $request)
    {
        $limit  = $request->input('limit', 10);
        $page   = $request->input('page', 1);
        $offset = ($page - 1) * 10;
        $lists  = UserCollect::filterUser()
            ->with(['episode', 'watchRecord.detail'])
            ->whereHas('episode', function (Builder $query) {
                $query->where('is_opend', 1);
            })
            ->orderByDesc('id')
            ->limit($limit)
            ->offset($offset)
            ->get();

        foreach ($lists as $list) {
            $count                      = EpisodesList::where('episodes_id', $list->episode->id)->count();
            $list->episode->total       = $count;
            $list->episode->status_text = $list->episode->status;
        }

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

    // 检查当前短剧是否收藏
    public function check($id)
    {
        $res = UserCollect::filterUser()->where('episode_id', $id)->count();

        return $this->success(!empty($res));
    }

    // 添加收藏
    public function add($id)
    {
        $res = UserCollect::filterUser()->where('episode_id', $id)->count();
        if ($res) {
            return $this->success(true);
        }
        $collect             = new UserCollect();
        $collect->user_id    = \user()->id;
        $collect->episode_id = $id;

        return $this->success($collect->save());
    }

    // 删除收藏
    public function destroy($id)
    {
        $res = UserCollect::filterUser()->where('episode_id', $id)->first();
        if (!$res) {
            return $this->success(false);
        }

        return $this->success($res->delete());
    }
}
