<?php

namespace App\Services\Payments;

use App\Models\Configuration;
use Illuminate\Support\Facades\DB;

class PaymentEnrollmentEventService
{
    public function buildEventData(
        int $parentId,
        array $studentIds,
        ?string $schoolYear = null,
        ?string $semester = null,
        ?string $portalLink = null
    ): array {
        $schoolYear = $schoolYear ?: Configuration::getConfig('school_year');
        $semester = $semester ?: Configuration::getConfig('semester');
        $portalLink = $portalLink ?: url('/login');

        $parent = DB::table('users')
            ->select('id', 'firstname', 'lastname', 'email')
            ->where('id', $parentId)
            ->first();

        if (!$parent) {
            throw new \RuntimeException("Parent user #{$parentId} not found");
        }

        $ids = array_values(array_unique(array_map('intval', $studentIds)));
        if (empty($ids)) {
            $ids = DB::table('students')
                ->where('parent_id', $parentId)
                ->pluck('id')
                ->map(fn ($id) => (int) $id)
                ->all();
        }

        if (empty($ids)) {
            $data = [
                'user_id' => (int) $parent->id,
                'email' => $parent->email ?? null,
                'firstname' => $parent->firstname ?? '',
                'lastname' => $parent->lastname ?? '',
                'school_year' => $schoolYear,
                'semester' => $semester,
                'portal_link' => $portalLink,
            ];

            return [$data, []];
        }

        $rows = DB::table('students as s')
            ->select([
                's.id as student_id',
                's.firstname as s_firstname',
                's.lastname as s_lastname',
                's.registration_grade',
                'sc.class_section_id',
                'cs.class_section_name',
                'tu.firstname as t_firstname',
                'tu.lastname as t_lastname',
            ])
            ->leftJoin('student_class as sc', function ($join) use ($schoolYear) {
                $join->on('sc.student_id', '=', 's.id')
                    ->where('sc.school_year', '=', $schoolYear);
            })
            ->leftJoin('classSection as cs', 'cs.class_section_id', '=', 'sc.class_section_id')
            ->leftJoin('teacher_class as tc', function ($join) use ($schoolYear) {
                $join->on('tc.class_section_id', '=', 'sc.class_section_id')
                    ->where('tc.position', '=', 'main')
                    ->where('tc.school_year', '=', $schoolYear);
            })
            ->leftJoin('users as tu', 'tu.id', '=', 'tc.teacher_id')
            ->where('s.parent_id', $parentId)
            ->whereIn('s.id', $ids)
            ->orderByDesc('sc.updated_at')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        if (empty($rows)) {
            $rows = DB::table('students as s')
                ->select('s.id as student_id', 's.firstname as s_firstname', 's.lastname as s_lastname', 's.registration_grade')
                ->where('s.parent_id', $parentId)
                ->whereIn('s.id', $ids)
                ->get()
                ->map(fn ($row) => (array) $row)
                ->all();
        }

        $students = [];
        $seen = [];
        foreach ($rows as $row) {
            $sid = (int) ($row['student_id'] ?? 0);
            if ($sid <= 0 || isset($seen[$sid])) {
                continue;
            }
            $seen[$sid] = true;

            $teacherFull = trim(trim((string) ($row['t_firstname'] ?? '')) . ' ' . trim((string) ($row['t_lastname'] ?? '')));
            $teacherFull = $teacherFull !== '' ? $teacherFull : null;

            $students[] = [
                'id' => $sid,
                'student_id' => $sid,
                'firstname' => (string) ($row['s_firstname'] ?? ''),
                'lastname' => (string) ($row['s_lastname'] ?? ''),
                'name' => trim(((string) ($row['s_firstname'] ?? '')) . ' ' . ((string) ($row['s_lastname'] ?? ''))),
                'registration_grade' => (string) ($row['registration_grade'] ?? ''),
                'class_section_id' => isset($row['class_section_id']) ? (int) $row['class_section_id'] : null,
                'class_section_name' => $row['class_section_name'] ?? null,
                'teacher_name' => $teacherFull,
                'start_date' => '',
                'portal_link' => $portalLink,
            ];
        }

        $data = [
            'user_id' => (int) $parent->id,
            'email' => $parent->email ?? null,
            'firstname' => $parent->firstname ?? '',
            'lastname' => $parent->lastname ?? '',
            'school_year' => $schoolYear,
            'semester' => $semester,
            'portal_link' => $portalLink,
        ];

        return [$data, $students];
    }
}
