<?php

namespace App\Console\Commands;

use App\Models\Listing;
use App\Models\Setting;
use App\Notifications\ListingReconfirmationNotification;
use Illuminate\Console\Command;

class CheckListingReconfirmations extends Command
{
    protected $signature = 'listings:check-reconfirmations';

    protected $description = 'Checks listings that require reconfirmation';


    public function handle()
    {
        $enabled = (bool) Setting::query()
        ->where('key','listing_reconfirmation_enabled')
        ->value('value');

        if(!$enabled){
            return self::SUCCESS;
        }

        $listings = Listing::query()
        ->published()
        ->where('reconfirmation_status',Listing::RECONFIRMATION_CONFIRMED)
        ->whereNotNull('reconfirmation_due_at')
        ->where('reconfirmation_due_at','<=',now())
        ->get();

        foreach($listings as $listing ){
            $listing->update([
                'reconfirmation_status' => Listing::RECONFIRMATION_PENDING,
                'reconfirmation_requested_at' => now()
            ]);

            $listing->consultantProfile?->user?->notify(
                new ListingReconfirmationNotification($listing)
            );
        }

        
    }
}
