<?php

namespace App\Services\Messaging;

use App\Models\ParentModel;
use App\Models\Student;
use App\Models\StudentClass;
use App\Models\TeacherClass;
use App\Models\User;

class MessageRecipientService
{
    public function teachers(): array
    {
        $rows = TeacherClass::query()
            ->select('teacher_class.teacher_id', 'users.firstname', 'users.lastname')
            ->join('users', 'users.id', '=', 'teacher_class.teacher_id')
            ->orderBy('users.firstname')
            ->orderBy('users.lastname')
            ->get();

        return $rows
            ->map(fn ($row) => [
                'id' => (int) $row->teacher_id,
                'name' => trim($row->firstname . ' ' . $row->lastname),
            ])
            ->unique('id')
            ->values()
            ->all();
    }

    public function parents(): array
    {
        $sectionIds = TeacherClass::query()->pluck('class_section_id')->filter()->unique()->values()->all();
        if (empty($sectionIds)) {
            return [];
        }

        $studentIds = StudentClass::query()
            ->active()
            ->whereIn('student_class.class_section_id', $sectionIds)
            ->pluck('student_class.student_id')
            ->filter()
            ->unique()
            ->values()
            ->all();

        if (empty($studentIds)) {
            return [];
        }

        $parentIds = Student::query()
            ->whereIn('id', $studentIds)
            ->where('is_active', 1)
            ->pluck('parent_id')
            ->filter()
            ->unique()
            ->values()
            ->all();

        if (empty($parentIds)) {
            return [];
        }

        $secondParentIds = ParentModel::query()
            ->whereIn('firstparent_id', $parentIds)
            ->pluck('secondparent_id')
            ->filter()
            ->unique()
            ->values()
            ->all();

        $allIds = collect($parentIds)->merge($secondParentIds)->unique()->values()->all();

        $users = User::query()
            ->whereIn('id', $allIds)
            ->orderBy('firstname')
            ->orderBy('lastname')
            ->get();

        return $users
            ->map(fn ($row) => [
                'id' => (int) $row->id,
                'name' => trim($row->firstname . ' ' . $row->lastname),
            ])
            ->unique('id')
            ->values()
            ->all();
    }
}
