<?php

namespace App\Http\Controllers\V1\User;

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

class ConsumeController extends Controller
{
    public function record(Request $request)
    {
        $limit  = $request->input('limit', 10);
        $page   = $request->input('page', 1);
        $offset = ($page - 1) * 10;
        $date   = $request->input('date');
        $date   = $date ?? Carbon::now()->format('Y-m');
        $lists  = UserEpisodesRecord::filterUser()
            ->when($date, function ($query, $date) {
                /* @var Builder  $query */
                return $query->where('created_at', 'like', "$date%");
            })
            ->with(['detail.episode'])
            ->orderByDesc('id')
            ->limit($limit)
            ->offset($offset)
            ->get();

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

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