<?php

namespace App\Services\Billing;

use App\Models\AdditionalCharge;
use App\Models\EventCharges;
use Illuminate\Support\Facades\Log;

class BillingTotalsService
{
    public function eventSubtotal(int $parentId, string $schoolYear): float
    {
        $eventSubtotal = 0.0;
        try {
            $events = EventCharges::getChargesWithEventInfo($parentId, $schoolYear) ?? [];
            foreach ($events as $event) {
                $eventSubtotal += (float) ($event['charged'] ?? 0.0);
            }
        } catch (\Throwable $e) {
            Log::warning('Failed to sum event charges.', ['error' => $e->getMessage()]);
        }

        return round($eventSubtotal, 2);
    }

    public function additionalSubtotal(int $invoiceId, ?string $schoolYear = null): float
    {
        $additionalSubtotal = 0.0;
        try {
            $builder = AdditionalCharge::query()
                ->select('charge_type', 'amount')
                ->where('invoice_id', $invoiceId)
                ->where('status', 'applied');

            if ($schoolYear !== null && $schoolYear !== '') {
                $builder->where('school_year', $schoolYear);
            }

            $rows = $builder->get()->map(fn ($row) => (array) $row)->all();
            foreach ($rows as $row) {
                $amount = (float) ($row['amount'] ?? 0);
                $type = strtolower((string) ($row['charge_type'] ?? 'add'));
                $amount = $type === 'deduct' ? -abs($amount) : abs($amount);
                $additionalSubtotal += $amount;
            }
        } catch (\Throwable $e) {
            Log::warning('Failed to sum additional charges.', ['error' => $e->getMessage()]);
        }

        return round($additionalSubtotal, 2);
    }
}
