<?php

namespace App\Http\Controllers\Api\ClassPreparation;

use App\Http\Controllers\Api\BaseApiController;
use App\Services\ClassPreparation\ClassPreparationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ClassPreparationController extends BaseApiController
{
    private ClassPreparationService $service;

    public function __construct(ClassPreparationService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index(Request $request): JsonResponse
    {
        $schoolYear = (string) ($request->query('school_year') ?? '');
        $semester = (string) ($request->query('semester') ?? '');

        $payload = $this->service->listPrep(
            $schoolYear !== '' ? $schoolYear : null,
            $semester !== '' ? $semester : null
        );

        return response()->json([
            'ok' => true,
            'schoolYear' => $payload['schoolYear'],
            'semester' => $payload['semester'],
            'results' => $payload['results'],
            'totals' => $payload['totals'],
            'shortages' => $payload['shortages'],
        ]);
    }

    public function markPrinted(Request $request): JsonResponse
    {
        $schoolYear = (string) ($request->input('school_year') ?? '');
        $semester = (string) ($request->input('semester') ?? '');
        $ids = $request->input('class_section_ids', []);

        if ($schoolYear === '' || !is_array($ids)) {
            return response()->json([
                'ok' => false,
                'message' => 'school_year and class_section_ids are required.',
            ], 422);
        }

        $count = $this->service->markPrinted($schoolYear, $semester, $ids);

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