<?php

namespace App\Http\Resources\ClassProgress;

use App\Http\Resources\Admin\Progress\ProgressGroupResource;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\ResourceCollection;

class ClassProgressGroupCollection extends ResourceCollection
{
    public function toArray($request): array
    {
        return $this->collection->toArray();
    }

    public static function fromPaginator(LengthAwarePaginator $paginator): array
    {
        $groups = [];
        foreach ($paginator->items() as $report) {
            $key = $report->week_start?->format('Y-m-d') ?? '';
            if ($key === '') {
                continue;
            }

            if (!isset($groups[$key])) {
                $groups[$key] = [
                    'week_start' => $key,
                    'week_end' => $report->week_end?->format('Y-m-d'),
                    'class_section_id' => $report->class_section_id,
                    'class_section_name' => $report->classSection?->class_section_name ?? '',
                    'reports' => [],
                ];
            }

            $groups[$key]['reports'][$report->subject] = (new ClassProgressReportResource($report))->toArray(request());
        }

        return [
            'items' => ProgressGroupResource::collection(collect(array_values($groups))),
            'pagination' => [
                'current_page' => $paginator->currentPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
                'last_page' => $paginator->lastPage(),
            ],
        ];
    }
}
