<?php

namespace App\Services\Families;

use Illuminate\Support\Facades\DB;

class FamilyFinanceService
{
    public function loadFinancialsForParents(array $parentIds, int $paymentLimit = 10): array
    {
        $parentIds = array_values(array_filter(array_map('intval', $parentIds)));

        if (empty($parentIds)) {
            return [
                'invoices' => [],
                'payments' => [],
                'invoice_map' => [],
                'summary' => [
                    'invoices_count' => 0,
                    'total_amount' => 0.0,
                    'paid_amount' => 0.0,
                    'balance' => 0.0,
                ],
            ];
        }

        $invRows = DB::table('invoices')
            ->select('id', 'parent_id', 'invoice_number', 'status', 'total_amount', 'paid_amount', 'balance', 'issue_date', 'due_date')
            ->whereIn('parent_id', $parentIds)
            ->orderBy('issue_date', 'DESC')
            ->get()
            ->map(fn ($r) => (array) $r)
            ->all();

        $invoiceMap = [];
        $summary = [
            'invoices_count' => 0,
            'total_amount' => 0.0,
            'paid_amount' => 0.0,
            'balance' => 0.0,
        ];
        foreach ($invRows as $ir) {
            $invoiceMap[(int) ($ir['id'] ?? 0)] = (string) ($ir['invoice_number'] ?? '');
            $summary['invoices_count']++;
            $summary['total_amount'] += (float) ($ir['total_amount'] ?? 0);
            $summary['paid_amount'] += (float) ($ir['paid_amount'] ?? 0);
            $summary['balance'] += (float) ($ir['balance'] ?? 0);
        }

        $payRows = DB::table('payments')
            ->select('id', 'parent_id', 'invoice_id', 'paid_amount', 'balance', 'payment_method', 'payment_date', 'status')
            ->whereIn('parent_id', $parentIds)
            ->orderBy('payment_date', 'DESC')
            ->limit($paymentLimit)
            ->get()
            ->map(fn ($r) => (array) $r)
            ->all();

        return [
            'invoices' => $invRows,
            'payments' => $payRows,
            'invoice_map' => $invoiceMap,
            'summary' => $summary,
        ];
    }
}
