<?php

namespace App\Livewire\Dashboard;

use App\Domain\Financial\Enums\InvoiceStatus;
use App\Domain\Financial\Models\Invoice;
use App\Domain\Participant\Models\Participant;
use App\Domain\Training\Enums\EnrollmentStatus;
use App\Domain\Training\Enums\RenewalPolicy;
use App\Domain\Training\Models\Enrollment;
use Livewire\Component;

class OverdueRenewalsAlert extends Component
{
    public bool $expanded = false;

    public function toggleExpanded(): void
    {
        $this->expanded = !$this->expanded;
    }

    public function render()
    {
        $today = now()->toDateString();

        // Find active enrollments with overdue billing that DON'T already have an unpaid invoice
        $overdueEnrollments = Enrollment::where('status', EnrollmentStatus::Active)
            ->whereNotNull('next_billing_date')
            ->where('next_billing_date', '<=', $today)
            ->whereHas('program', fn ($q) => $q->whereIn('renewal_policy', [
                RenewalPolicy::AutoRenew->value,
                RenewalPolicy::ManualRenew->value,
            ])->whereNotNull('billing_cycle'))
            ->with(['participant.person', 'program', 'group.branch'])
            ->orderBy('next_billing_date')
            ->get();

        // Filter out those who already have an unpaid invoice for this program
        $overdueEnrollments = $overdueEnrollments->filter(function ($enrollment) {
            if (!$enrollment->participant) {
                return false;
            }
            $hasUnpaidInvoice = Invoice::where('billable_type', Participant::class)
                ->where('billable_id', $enrollment->participant_id)
                ->whereIn('status', [InvoiceStatus::Sent, InvoiceStatus::PartiallyPaid, InvoiceStatus::Overdue])
                ->where('due_amount', '>', 0)
                ->where('notes', 'like', '%' . ($enrollment->program?->name_ar ?? '') . '%')
                ->exists();

            return !$hasUnpaidInvoice;
        });

        $totalOverdue = $overdueEnrollments->count();
        $displayList = $this->expanded ? $overdueEnrollments : $overdueEnrollments->take(10);

        return view('livewire.dashboard.overdue-renewals-alert', [
            'overdueEnrollments' => $displayList,
            'totalOverdue' => $totalOverdue,
        ]);
    }
}
