libra/app/Console/Commands/Send2HourReminders.php

74 lines
2.2 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Enums\ConsultationStatus;
use App\Models\Consultation;
use App\Notifications\ConsultationReminder2h;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class Send2HourReminders extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'reminders:send-2h';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send consultation reminders 2 hours before appointment';
/**
* Execute the console command.
*/
public function handle(): int
{
$targetTime = now()->addHours(2);
$windowStart = $targetTime->copy()->subMinutes(7);
$windowEnd = $targetTime->copy()->addMinutes(7);
$consultations = Consultation::query()
->where('status', ConsultationStatus::Approved)
->whereNull('reminder_2h_sent_at')
->whereDate('booking_date', $targetTime->toDateString())
->get()
->filter(function ($consultation) use ($windowStart, $windowEnd) {
$consultationDateTime = Carbon::parse(
$consultation->booking_date->format('Y-m-d').' '.
$consultation->booking_time
);
return $consultationDateTime->between($windowStart, $windowEnd);
});
$count = 0;
foreach ($consultations as $consultation) {
try {
$consultation->user->notify(new ConsultationReminder2h($consultation));
$consultation->update(['reminder_2h_sent_at' => now()]);
$count++;
$this->info("Sent 2h reminder for consultation #{$consultation->id}");
} catch (\Exception $e) {
$this->error("Failed to send reminder for consultation #{$consultation->id}: {$e->getMessage()}");
Log::error('2h reminder failed', [
'consultation_id' => $consultation->id,
'error' => $e->getMessage(),
]);
}
}
$this->info("Sent {$count} 2-hour reminders");
return Command::SUCCESS;
}
}