<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

final class SettlementMarkOverdueBillsCommand extends Command
{
    protected $signature = 'settlement:mark-overdue-bills {--days=7}';

    protected $description = 'Mark unpaid settlement bills as overdue past grace days';

    public function handle(): int
    {
        $days = max(1, (int) $this->option('days'));
        $cutoff = now()->subDays($days);

        $updated = DB::table('settlement_bills')
            ->whereIn('status', ['confirmed', 'partial_paid'])
            ->where('unpaid_amount', '>', 0)
            ->where('updated_at', '<', $cutoff)
            ->update([
                'status' => 'overdue',
                'updated_at' => now(),
            ]);

        $this->info("Marked {$updated} bill(s) overdue.");

        return self::SUCCESS;
    }
}
