<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;

class DeactivateEmployeesPastLastWorkingDay extends Command
{
    protected $signature = 'employees:deactivate-past-lwd {--dry-run : List employees without updating}';

    protected $description = 'Set employees to inactive when last working date has passed';

    public function handle(): int
    {
        $today = now()->toDateString();
        $query = User::query()
            ->withoutGlobalScopes()
            ->forTenantDirectory()
            ->where('status', User::STATUS_ACTIVE)
            ->whereNotNull('last_working_date')
            ->whereDate('last_working_date', '<', $today);

        $employees = $query->get(['id', 'name', 'employee_number', 'last_working_date', 'company_id']);

        if ($employees->isEmpty()) {
            $this->info('No employees to deactivate.');

            return self::SUCCESS;
        }

        if ($this->option('dry-run')) {
            foreach ($employees as $employee) {
                $this->line("Would deactivate #{$employee->id} {$employee->name} (LWD: {$employee->last_working_date?->format('Y-m-d')})");
            }

            return self::SUCCESS;
        }

        $count = $query->update(['status' => User::STATUS_INACTIVE]);
        $this->info("Deactivated {$count} employee(s) with last working day before {$today}.");

        return self::SUCCESS;
    }
}
