<?php

namespace App\Services\Invoices;

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

class InvoicePaymentService
{
    public function __construct(private InvoiceConfigService $config)
    {
    }

    public function getParentInvoiceSummary(int $parentId, ?string $schoolYear): array
    {
        $currentSchoolYear = $this->config->getSchoolYear();

        $schoolYears = DB::table('invoices')
            ->select('school_year')
            ->distinct()
            ->where('parent_id', $parentId)
            ->orderBy('school_year', 'DESC')
            ->get()
            ->map(fn ($r) => (array) $r)
            ->all();

        $selectedYear = $schoolYear ?: null;
        if (!$selectedYear) {
            $hasCurrentYear = in_array($currentSchoolYear, array_column($schoolYears, 'school_year'), true);
            $selectedYear = $hasCurrentYear ? $currentSchoolYear : (!empty($schoolYears) ? $schoolYears[0]['school_year'] : null);
        }

        $invoices = [];
        if ($selectedYear) {
            $invoices = Invoice::getInvoicesByParentId($parentId, $selectedYear);
        }

        $invoiceIds = array_column($invoices, 'id');
        $refunds = [];
        if (!empty($invoiceIds)) {
            $refundResults = DB::table('refunds')
                ->selectRaw('invoice_id, COALESCE(SUM(refund_paid_amount),0) as refund_paid_amount')
                ->whereIn('invoice_id', $invoiceIds)
                ->whereIn('status', ['Partial', 'Paid'])
                ->groupBy('invoice_id')
                ->get()
                ->map(fn ($r) => (array) $r)
                ->all();

            foreach ($refundResults as $row) {
                $refunds[$row['invoice_id']] = (float) ($row['refund_paid_amount'] ?? 0);
            }
        }

        $lastPayments = [];
        if (!empty($invoiceIds)) {
            $paymentResults = Payment::getPaymentsByInvoice($invoiceIds);
            foreach ($paymentResults as $payment) {
                $lastPayments[$payment['invoice_id']] = [
                    'last_paid_amount' => (float) ($payment['last_paid_amount'] ?? 0),
                    'last_payment_date' => $payment['last_payment_date'] ?? null,
                ];
            }
        }

        foreach ($invoices as &$invoice) {
            $invoice['refund_amount'] = $refunds[$invoice['id']] ?? 0.0;
            $invoice['last_paid_amount'] = $lastPayments[$invoice['id']]['last_paid_amount'] ?? 0.0;
            $invoice['last_payment_date'] = $lastPayments[$invoice['id']]['last_payment_date'] ?? null;
        }
        unset($invoice);

        return [
            'invoices' => $invoices,
            'schoolYears' => $schoolYears,
            'selectedYear' => $selectedYear,
            'currentSchoolYear' => $currentSchoolYear,
            'dueDate' => $this->config->getDueDate(),
        ];
    }
}
