<?php

namespace App\Services\Administrator;

use App\Models\Invoice;
use Illuminate\Support\Facades\Event;

class AdministratorEnrollmentEventService
{
    public function dispatchGroupedEvents(
        array $groupsByParentStatus,
        array $parentInfo,
        array $refundAmountByParent,
        string $schoolYear
    ): void {
        $eventMap = [
            'admission under review' => 'admissionUnderReview',
            'payment pending' => 'paymentPending',
            'enrolled' => 'studentEnrolled',
            'withdraw under review' => 'withdrawUnderReview',
            'refund pending' => 'refundPending',
            'withdrawn' => 'withdrawn',
            'denied' => 'denied',
            'waitlist' => 'waitlist',
        ];

        foreach ($groupsByParentStatus as $pid => $byStatus) {
            $p = $parentInfo[$pid] ?? [
                'user_id' => $pid,
                'email' => null,
                'firstname' => '',
                'lastname' => '',
            ];

            $invoice = Invoice::query()
                ->where('parent_id', $pid)
                ->where('school_year', $schoolYear)
                ->latest('created_at')
                ->first();

            foreach ($byStatus as $status => $studentsArr) {
                if (!isset($eventMap[$status])) {
                    continue;
                }

                $studentData = array_map(
                    fn ($s) => [
                        'name' => $s['student_name'],
                        'student_id' => $s['student_id'],
                    ],
                    $studentsArr
                );

                $parentData = [
                    'user_id' => $p['user_id'],
                    'email' => $p['email'],
                    'firstname' => $p['firstname'],
                    'lastname' => $p['lastname'],
                    'school_year' => $schoolYear,
                    'portalLink' => url('/login'),
                ];

                if ($status === 'payment pending' && $invoice) {
                    $parentData['amount'] = (float) ($invoice->balance ?? $invoice->amount_due ?? $invoice->total_amount ?? 0);
                    $parentData['due_date'] = $invoice->due_date ?? null;
                } elseif ($status === 'refund pending') {
                    $parentData['amount'] = $refundAmountByParent[$pid] ?? null;
                }

                Event::dispatch($eventMap[$status], [$parentData, $studentData]);
            }
        }
    }
}