<?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) {
            $weekStart = $report->week_start?->format('Y-m-d') ?? '';
            $sectionId = (int) ($report->class_section_id ?? 0);
            if ($weekStart === '' || $sectionId <= 0) {
                continue;
            }

            $key = $sectionId . '|' . $weekStart;

            if (!isset($groups[$key])) {
                $groups[$key] = [
                    'week_start' => $weekStart,
                    'week_end' => $report->week_end?->format('Y-m-d'),
                    'class_section_id' => $sectionId,
                    '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(),
            ],
        ];
    }
}
