<?php

namespace App\Services\Parents;

use App\Models\Event;
use App\Models\EventCharges;
use App\Models\Enrollment;
use App\Services\Invoices\InvoiceGenerationService;

class ParentEventParticipationService
{
    public function __construct(
        private ParentConfigService $configService,
        private InvoiceGenerationService $invoiceGeneration
    ) {
    }

    public function overview(int $parentId): array
    {
        $context = $this->configService->context();
        $schoolYear = $context['school_year'];
        $semester = $context['semester'];

        $activeEvents = Event::getActiveEvents($schoolYear, $semester) ?? [];
        $chargesList = EventCharges::getChargesWithEventInfo($parentId, $schoolYear) ?? [];

        $charges = [];
        foreach ($chargesList as $charge) {
            $key = $charge['student_id'] . ':' . $charge['event_id'];
            $charges[$key] = [
                'participation' => $charge['participation'],
                'date' => $charge['updated_at'] ?? $charge['created_at'],
            ];
        }

        $students = Enrollment::getEnrolledStudents($parentId, $schoolYear);

        return [
            'activeEvents' => $activeEvents,
            'charges' => $charges,
            'yourStudents' => $students,
        ];
    }

    public function updateParticipation(int $parentId, array $participations): void
    {
        $context = $this->configService->context();
        $schoolYear = $context['school_year'];
        $semester = $context['semester'];

        foreach ($participations as $key => $value) {
            [$studentId, $eventId] = array_map('intval', explode(':', (string) $key));
            $existing = EventCharges::query()
                ->where('parent_id', $parentId)
                ->where('student_id', $studentId)
                ->where('event_id', $eventId)
                ->first();

            if ($value === 'no') {
                if ($existing) {
                    $existing->delete();
                }
                continue;
            }

            if ($existing) {
                $existing->update(['participation' => $value]);
            } else {
                $event = Event::getEvent($eventId, $schoolYear);
                EventCharges::query()->create([
                    'parent_id' => $parentId,
                    'student_id' => $studentId,
                    'event_id' => $eventId,
                    'participation' => $value,
                    'charged' => $event['amount'] ?? 0,
                    'school_year' => $schoolYear,
                    'semester' => $semester,
                    'updated_by' => $parentId,
                ]);
            }
        }

        $this->invoiceGeneration->generateInvoice($parentId, $schoolYear);
    }
}
