<?php

namespace App\Http\Controllers\Api\Scores;

use App\Http\Controllers\Api\BaseApiController;
use App\Http\Requests\Scores\ScoreCommentListRequest;
use App\Http\Requests\Scores\ScoreCommentSaveRequest;
use App\Http\Requests\Scores\ScoreCommentUpdateRequest;
use App\Http\Resources\Scores\ScoreCommentResource;
use App\Services\Scores\ScoreCommentService;
use Illuminate\Http\JsonResponse;

class ScoreCommentController extends BaseApiController
{
    public function __construct(private ScoreCommentService $service)
    {
        parent::__construct();
    }

    public function index(ScoreCommentListRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $query = $request->query->all();
        if ($query === []) {
            $rawQuery = (string) $request->server->get('QUERY_STRING', '');
            parse_str($rawQuery, $query);
        }
        $json = $request->json()->all();
        if ($json === []) {
            $decoded = json_decode($request->getContent() ?: '', true);
            $json = is_array($decoded) ? $decoded : [];
        }
        $classSectionId = $payload['class_section_id']
            ?? ($query['class_section_id'] ?? null)
            ?? $request->input('class_section_id')
            ?? ($json['class_section_id'] ?? null);
        $semester = $payload['semester']
            ?? ($query['semester'] ?? null)
            ?? $request->input('semester')
            ?? ($json['semester'] ?? null);
        $schoolYear = $payload['school_year']
            ?? ($query['school_year'] ?? null)
            ?? $request->input('school_year')
            ?? ($json['school_year'] ?? null);
        $data = $this->service->list(
            $classSectionId !== null ? (string) $classSectionId : null,
            $semester !== null ? (string) $semester : null,
            $schoolYear !== null ? (string) $schoolYear : null
        );

        $studentRows = [];
        foreach ($data['students'] as $student) {
            $studentId = (int) ($student['student_id'] ?? 0);
            $studentRows[] = [
                'student_id' => $studentId,
                'firstname' => $student['firstname'] ?? null,
                'lastname' => $student['lastname'] ?? null,
                'school_id' => $student['school_id'] ?? null,
                'comments' => $data['comments'][$studentId] ?? [],
            ];
        }

        return response()->json([
            'ok' => true,
            'students' => ScoreCommentResource::collection($studentRows),
            'semester' => $data['semester'],
            'school_year' => $data['schoolYear'],
            'class_section_id' => $data['classSectionId'],
            'scores_locked' => $data['scoresLocked'],
        ]);
    }

    public function store(ScoreCommentSaveRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $result = $this->service->save(
            (int) $payload['class_section_id'],
            (string) $payload['semester'],
            (string) $payload['school_year'],
            $payload['comments'],
            $payload['missing_ok'] ?? [],
            (int) (auth()->id() ?? 0)
        );

        if (!empty($result['errors'])) {
            return response()->json(['ok' => false, 'errors' => $result['errors']], 422);
        }

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

    public function update(ScoreCommentUpdateRequest $request): JsonResponse
    {
        $payload = $request->validated();
        $result = $this->service->update(
            (int) $payload['class_section_id'],
            (string) $payload['semester'],
            (string) $payload['school_year'],
            $payload['comments'] ?? [],
            $payload['reviews'] ?? [],
            (int) (auth()->id() ?? 0)
        );

        if (!empty($result['errors'])) {
            return response()->json(['ok' => false, 'errors' => $result['errors']], 422);
        }

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