<?php

namespace App\Services\Refunds;

use Illuminate\Support\Facades\DB;

class RefundSummaryService
{
    public function getParentFinancialSummary(int $parentId, string $schoolYear, string $semester): array
    {
        $invRow = (array) DB::table('invoices')
            ->selectRaw('COALESCE(SUM(total_amount),0) AS total_invoiced')
            ->where('parent_id', $parentId)
            ->where('school_year', $schoolYear)
            ->where('semester', $semester)
            ->first();

        $payRow = (array) DB::table('payments')
            ->selectRaw('COALESCE(SUM(paid_amount),0) AS paid_in')
            ->where('parent_id', $parentId)
            ->where('school_year', $schoolYear)
            ->where('semester', $semester)
            ->first();

        $refRow = (array) DB::table('refunds')
            ->selectRaw('COALESCE(SUM(refund_paid_amount),0) AS refunded_cash')
            ->where('parent_id', $parentId)
            ->where('school_year', $schoolYear)
            ->where('semester', $semester)
            ->whereIn('status', ['Partial', 'Paid'])
            ->first();

        $totalInvoiced = (float) ($invRow['total_invoiced'] ?? 0);
        $paidIn = (float) ($payRow['paid_in'] ?? 0);
        $refundedCash = (float) ($refRow['refunded_cash'] ?? 0);

        $unapplied = $paidIn - $totalInvoiced - $refundedCash;

        return [
            'total_invoiced' => $totalInvoiced,
            'total_paid_in' => $paidIn,
            'total_refunded' => $refundedCash,
            'unapplied_balance' => $unapplied,
        ];
    }
}
