<?php

namespace App\Services\Invoices;

use App\Models\Student;
use App\Models\StudentClass;

class InvoiceService
{
    public function __construct(
        private InvoiceConfigService $config,
        private InvoiceManagementService $management,
        private InvoiceGenerationService $generation,
        private InvoiceTuitionService $tuition,
        private InvoiceGradeService $grades
    ) {
    }

    public function getDefaultSchoolYear(): string
    {
        return $this->config->getSchoolYear();
    }

    public function getDueDate(): ?string
    {
        return $this->config->getDueDate();
    }

    public function getManagementData(?string $schoolYear = null): array
    {
        return $this->management->getManagementData($schoolYear);
    }

    public function generateInvoiceForParent(int $parentId, ?string $schoolYear = null): array
    {
        return $this->generation->generateInvoice($parentId, $schoolYear);
    }

    public function hasClassAssignment(string $schoolYear, int $parentId): bool
    {
        if ($parentId <= 0) {
            return false;
        }
        $students = Student::query()->where('parent_id', $parentId)->get(['id']);
        if ($students->isEmpty()) {
            return false;
        }

        $studentIds = $students->pluck('id')->map(fn ($id) => (int) $id)->all();

        return StudentClass::query()
            ->whereIn('student_id', $studentIds)
            ->where('school_year', $schoolYear)
            ->exists();
    }

    public function getGradeLevelInfo(string $grade): array
    {
        return $this->grades->getGradeLevel($grade);
    }

    public function compareGrades(string $gradeA, string $gradeB): int
    {
        return $this->grades->compareGrades($gradeA, $gradeB);
    }

    public function calculateTotalTuitionFee(array $students): float
    {
        return $this->tuition->calculateTotalTuitionFee($students);
    }

    public function calculateTuitionFee(array $registeredKids, array $withdrawnKids, ?string $refundDeadline = null): float
    {
        return $this->tuition->calculateTuitionFee($registeredKids, $withdrawnKids, $refundDeadline);
    }
}
