<?php

namespace App\Domain\Financial\Listeners;

use App\Domain\Financial\Events\InvoicePaid;
use App\Domain\Training\Models\Enrollment;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class ActivateEnrollmentOnPayment implements ShouldQueue
{
    public function handle(InvoicePaid $event): void
    {
        try {
            $invoice = $event->invoice;

            // Activate pending enrollments linked to this invoice
            $pendingEnrollments = Enrollment::where('invoice_id', $invoice->id)
                ->where('status', 'pending')
                ->get();

            $attendanceService = app(\App\Domain\Attendance\Services\AttendanceGenerationService::class);

            foreach ($pendingEnrollments as $enrollment) {
                $enrollment->update([
                    'status' => 'active',
                    'payment_status' => 'paid',
                    'activated_at' => now(),
                ]);

                $attendanceService->generateForEnrollment($enrollment);
            }

            // Mark payment_status as paid for active enrollments linked to this invoice
            Enrollment::where('invoice_id', $invoice->id)
                ->where('status', 'active')
                ->where('payment_status', '!=', 'paid')
                ->update(['payment_status' => 'paid']);

            // Handle renewal invoices: match by participant + subscription description
            if ($invoice->billable_type === \App\Domain\Participant\Models\Participant::class) {
                $hasSubscriptionItem = $invoice->items()
                    ->where('description', 'ilike', '%اشتراك%')
                    ->exists();

                if ($hasSubscriptionItem) {
                    Enrollment::where('participant_id', $invoice->billable_id)
                        ->where('status', 'active')
                        ->whereIn('payment_status', ['pending', 'partial', 'overdue'])
                        ->update(['payment_status' => 'paid']);
                }
            }
        } catch (\Throwable $e) {
            Log::error('ActivateEnrollmentOnPayment failed: ' . $e->getMessage(), [
                'invoice_id' => $event->invoice->id,
            ]);
        }
    }

    public function failed(InvoicePaid $event, \Throwable $exception): void
    {
        Log::critical('ActivateEnrollmentOnPayment PERMANENTLY FAILED', [
            'invoice_id' => $event->invoice->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
