<?php

namespace App\Console\Commands;

use App\Classes\Notifications\PermitsReminderEmail;
use App\Models\PermitsReminder;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send Permits Reminders Email';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $currentDateTime = now();
        $startRange = $currentDateTime->subDays(3)->startOfDay();
        $endRange = $currentDateTime->copy()->addDays(6)->endOfDay();

        $reminders = PermitsReminder::whereDate('reminder_date', '>=', $startRange)
            ->whereDate('reminder_date', '<=', $endRange)
            ->orWhere('reminder_date', '<', now())
            ->pluck('model');

        if ($reminders->isEmpty()) {
            $this->info('No reminders expiring within the specified range.');
            return;
        }

        $this->info($this->getTimeStamp() . 'Reminders: ' . $reminders->toJson());

        $users = User::whereIn('email', $this->getEmailList())->get();

        foreach ($users as $user) {
            $this->info($this->getTimeStamp() . 'Reminder email sent to ' . $user->email);
            if (app()->environment('production')) {
                $user->notify(new PermitsReminderEmail($user, $reminders));
            }
        }
    }

    public function getTimeStamp()
    {
        return '[' . Carbon::now()->format('Y-m-d H:i:s') . '] - ';
    }

    protected function getEmailList(): array
    {
        return [
            'edmond.wuiming2021@gmail.com',
            'anithagurl96@gmail.com'
        ];
    }
}
