<?php

namespace App\Http\Resources\Fees;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class FeeTuitionBreakdownResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $students = $this->resource['students'] ?? [];
        $fees = $this->resource['fees'] ?? [];

        return [
            'school_year' => $this->resource['school_year'] ?? null,
            'family_total' => (float) ($this->resource['family_total'] ?? 0),
            'billable_count' => (int) ($this->resource['billable_count'] ?? 0),
            'non_billable_count' => (int) ($this->resource['non_billable_count'] ?? 0),
            'fees' => [
                'first_student_fee' => (float) ($fees['first_student_fee'] ?? 0),
                'second_student_fee' => (float) ($fees['second_student_fee'] ?? 0),
                'youth_fee' => (float) ($fees['youth_fee'] ?? 0),
            ],
            'students' => array_map(function (array $row): array {
                return [
                    'student_id' => $row['student_id'] ?? null,
                    'student_name' => $row['student_name'] ?? null,
                    'grade' => $row['grade'] ?? null,
                    'grade_level' => $row['grade_level'] ?? null,
                    'enrollment_status' => $row['enrollment_status'] ?? null,
                    'admission_status' => $row['admission_status'] ?? null,
                    'fee_category' => $row['fee_category'] ?? null,
                    'tuition_fee' => (float) ($row['tuition_fee'] ?? 0),
                    'discount_amount' => (float) ($row['discount_amount'] ?? 0),
                    'final_tuition_amount' => (float) ($row['final_tuition_amount'] ?? 0),
                ];
            }, $students),
        ];
    }
}
