<?php

namespace App\Services\Admin\Finances;

use App\Models\TuitionInvoice;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class TuitionInvoiceService
{
    public function paginated(int $perPage = 25, string $search = '', ?int $academicTermId = null): LengthAwarePaginator
    {
        return TuitionInvoice::query()
            ->select(['id', 'student_id', 'academic_term_id', 'amount_due', 'due_date'])
            ->withSum('payments as paid_total', 'amount_paid')
            ->withCount('payments')
            ->with(['student.user.profile', 'student.department', 'academicTerm:id,name,semester,start_date,end_date'])
            ->when($search, fn ($q) => $q->whereHas('student', fn ($q) => $q->where('student_number', 'like', "%{$search}%")
                ->orWhereHas('user.profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"))))
            ->when($academicTermId, fn ($q) => $q->where('academic_term_id', $academicTermId))
            ->latest()
            ->paginate($perPage);
    }

    public function createMany(array $studentIds, array $data): void
    {
        DB::transaction(function () use ($studentIds, $data) {
            foreach ($studentIds as $studentId) {
                TuitionInvoice::create([
                    'student_id' => $studentId,
                    'academic_term_id' => $data['academic_term_id'],
                    'amount_due' => $data['amount_due'],
                    'due_date' => $data['due_date'],
                ]);
            }
        });
    }

    public function update(TuitionInvoice $invoice, array $data): TuitionInvoice
    {
        $invoice->student_id = $data['student_id'];
        $invoice->academic_term_id = $data['academic_term_id'];
        $invoice->amount_due = $data['amount_due'];
        $invoice->due_date = $data['due_date'] ?? null;
        $invoice->update();

        return $invoice;
    }

    public function delete(TuitionInvoice $invoice): bool
    {
        return $invoice->delete();
    }
}
