<?php

namespace Modules\VetAdmission\Console;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Modules\VetAdmission\Entities\Services\AdmissionBillingService;
use Modules\VetAdmission\Entities\VaAdmission;

/**
 * Nightly cron: for every active admission with a daily_rate +
 * daily_rate_product_id set, append a "day of stay" sell line for every
 * midnight crossed since last_daily_post_date.
 *
 * Idempotent — re-running the same day does nothing.
 */
class VaPostDailyStay extends Command
{
    protected $signature   = 'vetadmission:post-daily-stay';
    protected $description = 'Append a per-day boarding sell line for active admissions';

    public function handle(AdmissionBillingService $svc): int
    {
        $upto = Carbon::yesterday()->endOfDay();
        $total = 0;
        foreach (VaAdmission::admitted()->whereNotNull('daily_rate_product_id')->get() as $a) {
            $total += $svc->postDailyStay($a, $upto);
        }
        $this->info("Posted {$total} day-of-stay line(s).");
        return 0;
    }
}
