<?php

namespace App\Services;

use App\Models\DocumentHeader;
use Illuminate\Support\Facades\DB;

class InvoiceBalanceService
{
    public function outstanding(DocumentHeader $invoice): float
    {
        $invoiceTotal = (float) $invoice->inclusive_total;

        $receiptTotal = (float) DB::table('receipt_lines as rl')
            ->join('receipts as r', 'r.id', '=', 'rl.receipt_id')
            ->where('rl.invoice_id', $invoice->id)
            ->where('r.status', 'processed')
            ->sum('rl.amount');

        $creditApplied = (float) DB::table('document_links as dl')
            ->join('document_headers as dh', 'dh.id', '=', 'dl.source_id')
            ->where('dl.target_id', $invoice->id)
            ->where('dl.target_type', 'invoice')
            ->where('dl.source_type', 'credit_note')
            ->where('dl.link_type', 'credit_apply')
            ->where('dl.status', 'active')
            ->sum('dh.inclusive_total');

        $outstanding = $invoiceTotal - $receiptTotal - $creditApplied;

        return max(0.0, $outstanding);
    }
}
