<?php

namespace App\Http\Resources\Fees;

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

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

        return [
            'parent_id' => (int) ($this->resource['parent_id'] ?? 0),
            'school_year' => $this->resource['school_year'] ?? null,
            'charges' => [
                'tuition' => (float) ($charges['tuition'] ?? 0),
                'extra_charges' => (float) ($charges['extra_charges'] ?? 0),
                'event_charges' => (float) ($charges['event_charges'] ?? 0),
                'late_fees' => (float) ($charges['late_fees'] ?? 0),
                'total' => (float) ($charges['total'] ?? 0),
            ],
            'credits' => [
                'discounts' => (float) ($credits['discounts'] ?? 0),
                'total' => (float) ($credits['total'] ?? 0),
            ],
            'payments' => (float) ($this->resource['payments'] ?? 0),
            'refunds_applied' => (float) ($this->resource['refunds_applied'] ?? 0),
            'remaining_balance' => (float) ($this->resource['remaining_balance'] ?? 0),
            'account_credit' => (float) ($this->resource['account_credit'] ?? 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,
                    'enrollment_status' => $row['enrollment_status'] ?? null,
                    'tuition' => (float) ($row['tuition'] ?? 0),
                    'extra_charges' => (float) ($row['extra_charges'] ?? 0),
                    'event_charges' => (float) ($row['event_charges'] ?? 0),
                    'total_charges' => (float) ($row['total_charges'] ?? 0),
                    'payments_applied' => (float) ($row['payments_applied'] ?? 0),
                    'credits_applied' => (float) ($row['credits_applied'] ?? 0),
                    'refunds_applied' => (float) ($row['refunds_applied'] ?? 0),
                    'remaining_balance' => (float) ($row['remaining_balance'] ?? 0),
                    'account_credit' => (float) ($row['account_credit'] ?? 0),
                ];
            }, $students),
        ];
    }
}
