<?php

namespace App\Console\Commands;

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

class CheckPasswordExpiry extends Command
{
    /**
     * コマンドの名前と説明
     *
     * @var string
     */
    protected $signature = 'password:check-expiry {ope_id?}';

    /**
     * @var string
     */
    protected $description = 'パスワード有効期限をチェック';

    /**
     * コマンド実行
     */
    public function handle(): int
    {
        $opeId = $this->argument('ope_id');
        
        if ($opeId) {
            $ope = Ope::find($opeId);
            if (!$ope) {
                $this->error("Ope with ID {$opeId} not found");
                return 1;
            }
            $this->checkOpe($ope);
        } else {
            // すべてのオペレータをチェック
            $opes = Ope::all();
            foreach ($opes as $ope) {
                $this->checkOpe($ope);
            }
        }

        return 0;
    }

    /**
     * 単一オペレータの有効期限をチェック
     */
    private function checkOpe(Ope $ope): void
    {
        $this->info("=== Ope ID: {$ope->ope_id} ({$ope->ope_name}) ===");
        $this->info("ope_pass_changed_at: " . ($ope->ope_pass_changed_at ?? 'NULL'));

        if (is_null($ope->ope_pass_changed_at)) {
            $this->warn("❌ Password change REQUIRED (never changed)");
            return;
        }

        try {
            $changedAt = Carbon::parse($ope->ope_pass_changed_at);
            $now = Carbon::now();
            $monthsDiff = $now->diffInMonths($changedAt);

            $this->info("Changed At: " . $changedAt->format('Y-m-d H:i:s'));
            $this->info("Now: " . $now->format('Y-m-d H:i:s'));
            $this->info("Months Difference: {$monthsDiff}");

            if ($monthsDiff >= 3) {
                $this->warn("❌ Password change REQUIRED ({$monthsDiff} months passed)");
            } else {
                $this->line("✅ Password is valid ({$monthsDiff} months passed, {3 - $monthsDiff} months remaining)");
            }
        } catch (\Exception $e) {
            $this->error("Error parsing date: {$e->getMessage()}");
        }

        $this->line("");
    }
}
