<?php

namespace App\Services\Fees;

use Illuminate\Support\Facades\Log;

/**
 * TuitionCalculationService
 *
 * Responsible for producing a tuition calculation that answers the plan's
 * key questions for a family:
 *   - What was each student charged?
 *   - Why was each student charged that amount? (fee_category)
 *   - What is the family total?
 *
 * This service is a thin orchestrator built on top of FeeStudentFeeService
 * and FeeConfigService. It is the place where new business rules (discounts,
 * required fees, balance integration) should be wired in for parent-facing
 * tuition views without bloating the lower-level fee assignment service.
 */
class TuitionCalculationService
{
    public function __construct(
        private FeeConfigService $config,
        private FeeStudentFeeService $studentFees
    ) {
    }

    /**
     * Produce a family + per-student tuition calculation.
     *
     * @param array $students Each item may include: student_id, firstname,
     *     lastname, grade, class_section_id, enrollment_status,
     *     admission_status, discount_amount.
     *
     * @return array{
     *     school_year: string,
     *     fees: array<string, float>,
     *     family_total: float,
     *     billable_count: int,
     *     non_billable_count: int,
     *     students: array<int, array<string, mixed>>
     * }
     */
    public function calculate(array $students): array
    {
        $schoolYear = $this->config->getSchoolYear();
        $breakdown = $this->studentFees->calculateBreakdown($students);

        Log::info('Tuition calculation requested', [
            'school_year' => $schoolYear,
            'student_count' => count($students),
            'family_total' => $breakdown['family_total'],
        ]);

        return [
            'school_year' => $schoolYear,
            'fees' => $breakdown['fees'],
            'family_total' => $breakdown['family_total'],
            'billable_count' => $breakdown['billable_count'],
            'non_billable_count' => $breakdown['non_billable_count'],
            'students' => $breakdown['students'],
        ];
    }

    /**
     * Convenience helper: the family-level tuition total only.
     */
    public function familyTotal(array $students): float
    {
        return $this->calculate($students)['family_total'];
    }
}
