<?php

namespace App\Modules\FINANCE\Services;

use App\Modules\FINANCE\Models\Invoice;
use App\Modules\FINANCE\Models\Payment;
use Illuminate\Support\Facades\DB;

class PaymentService
{
    /**
     * Record a payment for an invoice.
     */
    public function recordPayment(array $data): Payment
    {
        return DB::transaction(function () use ($data) {
            $invoice = Invoice::findOrFail($data['invoice_id']);
            
            $payment = Payment::create([
                'invoice_id' => $invoice->id,
                'amount' => $data['amount'],
                'payment_method_id' => $data['payment_method_id'],
                'payment_date' => $data['payment_date'],
                'reference_number' => $data['reference_number'] ?? null,
                'notes' => $data['notes'] ?? null,
            ]);

            // Update invoice amounts and status
            $newPaidAmount = $invoice->paid_amount + $payment->amount;
            $newBalanceAmount = $invoice->total_amount - $newPaidAmount;
            
            $status = 'sent';
            if ($newBalanceAmount <= 0) {
                $status = 'paid';
            } elseif ($newPaidAmount > 0) {
                $status = 'partially_paid';
            }

            $invoice->update([
                'paid_amount' => $newPaidAmount,
                'balance_amount' => $newBalanceAmount,
                'status' => $status,
            ]);

            return $payment;
        });
    }

    /**
     * Get payment history for an invoice.
     */
    public function getInvoicePaymentHistory(int $invoiceId)
    {
        return Payment::where('invoice_id', $invoiceId)->orderBy('payment_date', 'desc')->get();
    }
}
