<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Employee;
use Carbon\Carbon;

class UpdateEmployeeStatus extends Command
{
    protected $signature = 'employee:update-status';
    protected $description = 'Update employee status based on retirement date';

    public function handle(): int
    {
        $this->info('🔄 Updating employee statuses...');

        $updatedCount = 0;

        // Update active → retiring (30 days before)
        $approachingRetirement = Employee::where('status', 'active')
            ->whereNotNull('retirement_date')
            ->where('retirement_date', '<=', Carbon::now()->addDays(30))
            ->where('retirement_date', '>', Carbon::now())
            ->get();

        foreach ($approachingRetirement as $employee) {
            $employee->update(['status' => 'retiring']);
            $updatedCount++;
            $this->info("   🟡 {$employee->name} → retiring ({$employee->daysUntilRetirement()} days left)");
        }

        // Update retiring → retired
        $passedRetirement = Employee::whereIn('status', ['active', 'retiring', 'extended'])
            ->whereNotNull('retirement_date')
            ->where('retirement_date', '<', Carbon::now())
            ->get();

        foreach ($passedRetirement as $employee) {
            $employee->update(['status' => 'retired']);
            $updatedCount++;
            $this->info("   🔴 {$employee->name} → retired");
        }

        $this->info("✅ Total updated: {$updatedCount}");
        return 0;
    }
}