<?php

namespace App\Console\Commands;

use App\Domain\Financial\Events\PaymentPlanDefaulted;
use App\Domain\Financial\Models\Installment;
use App\Domain\Financial\Models\PaymentPlan;
use App\Domain\Shared\Models\SystemSetting;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class DetectPaymentPlanDefaults extends Command
{
    protected $signature = 'payments:detect-defaults';
    protected $description = 'كشف التخلف عن خطط الدفع';

    private const DEFAULT_THRESHOLD = 2;

    public function handle(): int
    {
        $graceDays = (int) SystemSetting::get('installment_grace_days', 7);
        $graceCutoff = now()->subDays($graceDays)->toDateString();

        // Find pending installments that are overdue past grace period
        $overdueInstallments = Installment::where('status', 'pending')
            ->where('due_date', '<', $graceCutoff)
            ->with('paymentPlan')
            ->get();

        if ($overdueInstallments->isEmpty()) {
            $this->info('لا توجد أقساط متأخرة تجاوزت فترة السماح.');
            return self::SUCCESS;
        }

        $updatedCount = 0;
        $defaultedPlans = [];

        foreach ($overdueInstallments as $installment) {
            // Mark installment as overdue
            if ($installment->status === 'pending') {
                $installment->update(['status' => 'overdue']);
                $updatedCount++;
            }

            // Check if the payment plan as a whole has defaulted
            $plan = $installment->paymentPlan;
            if (!$plan || isset($defaultedPlans[$plan->id])) {
                continue;
            }

            $missedCount = Installment::where('payment_plan_id', $plan->id)
                ->where('status', 'overdue')
                ->count();

            if ($missedCount >= self::DEFAULT_THRESHOLD && $plan->status !== 'defaulted') {
                $plan->update(['status' => 'defaulted']);
                $defaultedPlans[$plan->id] = true;

                PaymentPlanDefaulted::dispatch($plan);

                Log::warning("PaymentPlan #{$plan->id} defaulted: {$missedCount} missed installments");
                $this->warn("خطة الدفع #{$plan->id} متعثرة ({$missedCount} أقساط متأخرة)");
            }
        }

        $this->info("تم تحديث {$updatedCount} قسط متأخر. خطط متعثرة: " . count($defaultedPlans));
        Log::info("DetectPaymentPlanDefaults: Updated {$updatedCount} installments, " . count($defaultedPlans) . " plans defaulted");

        return self::SUCCESS;
    }
}
