<?php

namespace App\Http\Controllers\Api\ClassPrep;

use App\Http\Controllers\Api\BaseApiController;
use App\Services\ClassPrep\ClassRosterService;
use App\Services\ClassPrep\StickerCountService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ClassPrepController extends BaseApiController
{
    private StickerCountService $stickerCounts;
    private ClassRosterService $roster;

    public function __construct(StickerCountService $stickerCounts, ClassRosterService $roster)
    {
        parent::__construct();
        $this->stickerCounts = $stickerCounts;
        $this->roster = $roster;
    }

    public function stickerCounts(Request $request): JsonResponse
    {
        $schoolYear = (string) ($request->query('school_year') ?? '');
        $semester = (string) ($request->query('semester') ?? '');
        $classSectionId = $request->query('class_section_id') ?? $request->query('class_id');
        $classSectionId = is_numeric($classSectionId) ? (int) $classSectionId : null;

        if ($classSectionId !== null && $classSectionId > 0) {
            $payload = $this->stickerCounts->listForClass($schoolYear, $semester, $classSectionId);
        } else {
            $payload = $this->stickerCounts->listAll($schoolYear, $semester);
        }

        return response()->json([
            'ok' => true,
            'data' => $payload,
        ]);
    }

    public function studentsByClass(Request $request, int $classSectionId): JsonResponse
    {
        $schoolYear = (string) ($request->query('school_year') ?? '');

        $students = $this->roster->listStudentsByClass($classSectionId, $schoolYear !== '' ? $schoolYear : null);

        return response()->json([
            'ok' => true,
            'students' => $students,
        ]);
    }
}
