<?php

namespace App\Services\ExtraCharges;

use App\Models\Invoice;

class ExtraChargesInvoiceService
{
    public function listInvoicesForParent(int $parentId, string $schoolYear): array
    {
        if ($parentId <= 0) {
            return [];
        }

        $rows = Invoice::getInvoicesByParentId($parentId, $schoolYear) ?? [];

        return array_map(function ($inv) {
            $id = (int) ($inv['id'] ?? 0);
            $num = (string) ($inv['invoice_number'] ?? ('INV-' . $id));
            $status = strtolower((string) ($inv['status'] ?? ''));
            $balance = (float) ($inv['balance'] ?? 0);
            $issue = $inv['issue_date'] ?? null;

            return [
                'id' => $id,
                'invoice_number' => $num,
                'status' => $status,
                'balance' => $balance,
                'issue_date' => $issue,
                'text' => $num
                    . ($status ? ' — ' . ucfirst($status) : '')
                    . ' (Bal: $' . number_format($balance, 2) . ')',
            ];
        }, $rows);
    }

    public function applyToInvoice(int $invoiceId, string $chargeType, float $amountAbs): void
    {
        if ($invoiceId <= 0 || $amountAbs <= 0) {
            return;
        }

        if ($chargeType === 'add') {
            Invoice::applyAdditionalCharge($invoiceId, $amountAbs);
        } else {
            Invoice::deductAdditionalCharge($invoiceId, $amountAbs);
        }
    }

    public function reverseOnInvoice(int $invoiceId, string $chargeType, float $amountAbs): void
    {
        if ($invoiceId <= 0 || $amountAbs <= 0) {
            return;
        }

        if ($chargeType === 'add') {
            Invoice::reverseAdditionalCharge($invoiceId, $amountAbs);
        } else {
            Invoice::applyAdditionalCharge($invoiceId, $amountAbs);
        }
    }

    public function adjustDelta(int $invoiceId, float $delta): void
    {
        if ($invoiceId <= 0 || abs($delta) <= 0.00001) {
            return;
        }

        if ($delta > 0) {
            Invoice::applyAdditionalCharge($invoiceId, $delta);
        } else {
            Invoice::reverseAdditionalCharge($invoiceId, abs($delta));
        }
    }
}
