<?php

namespace App\Http\Controllers\V1\User;

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

class WatchRecordsController extends Controller
{
    public function lists(Request $request)
    {
        $limit  = $request->input('limit', 10);
        $page   = $request->input('page', 1);
        $offset = ($page - 1) * 10;
        $lists  = UserWatchRecord::filterUser()
            ->with(['detail.episode'])
            ->whereHas('detail.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->detail->episode->id)->count();
            $list->detail->episode->total       = $count;
            $list->detail->episode->status_text = $list->detail->episode->status;
        }

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

    public function recent()
    {
        $info = UserWatchRecord::filterUser()
            ->with(['detail.episode'])
            ->whereHas('episode', function (Builder $query) {
                $query->where('is_opend', 1);
            })
            ->orderByDesc('updated_at')
            ->first();

        if ($info) {
            $count                              = EpisodesList::where('episodes_id', $info->detail->episodes_id)->count('id');
            $info->detail->episode->total       = $count;
            $info->detail->episode->status_text = $info->detail->episode->status;
        }

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

    public function watched()
    {
        $id     = request()->input('id');
        $listId = request()->input('list_id');
        $res    = UserWatchRecord::filterUser()->where('episode_id', $id)->first();
        if (!$res) {
            $res             = new UserWatchRecord();
            $res->user_id    = \user()->id;
            $res->episode_id = $id;
        }

        $res->list_id    = $listId;
        $res->updated_at = Carbon::now()->toDateTimeString();

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

    public function destroy($id)
    {
        $res = UserWatchRecord::filterUser()->find($id);
        if ($res) {
            $res->delete();
        }

        return $this->success();
    }
}
