<?php

namespace App\Modules\Billing\Services;

use App\Core\Base\BaseService;
use App\Modules\Billing\Repositories\InvoiceRepository;
use App\Models\Invoice;

class InvoiceService extends BaseService
{
    protected $repository;

    public function __construct(InvoiceRepository $repository)
    {
        $this->repository = $repository;
    }

    public function createInvoice(array $data): Invoice
    {
        $data['due_amount'] = $data['total_amount'] - ($data['paid_amount'] ?? 0);
        return $this->repository->create($data);
    }

    public function recordPayment(Invoice $invoice, float $amount): bool
    {
        $paid = $invoice->paid_amount + $amount;
        $due = $invoice->total_amount - $paid;

        return $invoice->update([
            'paid_amount' => $paid,
            'due_amount' => max(0, $due),
            'status' => $due <= 0 ? 'Paid' : 'Partial',
        ]);
    }
}
