<?php

namespace App\Console\Commands;

use App\Mail\OverdueInvoiceNotification;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Mtc\MercuryDataModels\Invoice;

class NotifyOverdueInvoices extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoices:send-overdue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Notify about overdue invoices';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Invoice::query()
            ->whereHas('tenant')
            ->overdue(30)
            ->get()
            ->each(fn (Invoice $invoice) => Mail::to($invoice->email)
                ->bcc(config('mail.billing'))
                ->send(new OverdueInvoiceNotification($invoice)));
        return 0;
    }
}
