<?php

namespace App\Services\Events;

use App\Models\EventCharges;
use App\Models\Student;

class EventStudentChargeService
{
    public function listStudentsWithCharges(int $parentId, string $schoolYear, string $semester): array
    {
        $students = Student::query()
            ->where('parent_id', $parentId)
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        $chargedIds = EventCharges::query()
            ->where('parent_id', $parentId)
            ->where('school_year', $schoolYear)
            ->where('semester', $semester)
            ->distinct()
            ->pluck('student_id')
            ->map(fn ($id) => (int) $id)
            ->all();

        $chargedMap = array_flip($chargedIds);

        $data = [];
        foreach ($students as $student) {
            $data[] = [
                'id' => (int) ($student['id'] ?? 0),
                'name' => trim(($student['firstname'] ?? '') . ' ' . ($student['lastname'] ?? '')),
                'charged' => isset($chargedMap[(int) ($student['id'] ?? 0)]),
            ];
        }

        return $data;
    }
}
