<?php

namespace App\Services\Administrator;

use App\Models\Enrollment;
use App\Models\Invoice;
use App\Models\Refund;
use App\Services\FeeCalculationService;

class AdministratorEnrollmentRefundService
{
    public function __construct(
        protected FeeCalculationService $feeCalculationService
    ) {
    }

    public function processRefunds(array $parentIds, string $schoolYear, int $editorUserId): array
    {
        $errors = [];
        $refundAmountByParent = [];

        foreach ($parentIds as $pid) {
            $students = Enrollment::query()
                ->where('parent_id', $pid)
                ->where('school_year', $schoolYear)
                ->get()
                ->toArray();

            if (empty($students)) {
                continue;
            }

            $invoice = Invoice::query()
                ->where('parent_id', $pid)
                ->where('school_year', $schoolYear)
                ->latest('created_at')
                ->first();

            if (!$invoice) {
                $errors[] = "No invoice found for parent ID {$pid} (for refund calc).";
                continue;
            }

            $refundAmount = $this->feeCalculationService->calculateRefund($students, $pid);
            $refundAmountByParent[$pid] = $refundAmount;

            $existingRefund = Refund::query()
                ->where('invoice_id', $invoice->id)
                ->first();

            if ($existingRefund) {
                $existingRefund->update([
                    'refund_amount' => $refundAmount,
                    'status' => 'Pending',
                    'updated_by' => $editorUserId,
                ]);
            } else {
                Refund::query()->create([
                    'parent_id' => $pid,
                    'school_year' => $invoice->school_year,
                    'invoice_id' => $invoice->id,
                    'refund_amount' => $refundAmount,
                    'refund_paid_amount' => 0.0,
                    'status' => 'Pending',
                    'requested_at' => now(),
                    'updated_by' => $editorUserId,
                ]);
            }
        }

        return [
            'errors' => $errors,
            'refundAmountByParent' => $refundAmountByParent,
        ];
    }
}
