<?php

namespace App\Console\Commands;

use App\Models\Appointment;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class send1MinAlertAppointment extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send1-min-alert-appointment';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $now = Carbon::now();
        $appointments = Appointment::where('appointment_time', '<=', $now->addMinutes(1)->format('H:i:s'))->where('appointment_time', '>=', Carbon::now()->format('H:i:s'))->get();

        foreach ($appointments as $appointment) {

            // Concatenate date and time
            $datetimeUtc = $appointment->appointment_date . ' ' . $appointment->appointment_time;

            // Convert to UTC timezone
            $dateTimeUtc = Carbon::createFromFormat('Y-m-d H:i:s', $datetimeUtc, 'UTC');

            // Convert to the appointment's timezone
            $appointmentTimeZone = new CarbonTimeZone($appointment->timezone);
            $dateTimeInAppointmentTimeZone = $dateTimeUtc->setTimezone($appointmentTimeZone);

            // Split the datetime into date and time components in the appointment timezone
            $appointment->appointment_date = $appointmentDate = $dateTimeInAppointmentTimeZone->format('Y-m-d');
            $appointment->appointment_time = $appointmentTime = $dateTimeInAppointmentTimeZone->format('H:i:s');

            $patient = $appointment->patient;
            Mail::send('emails.start-meeting', ['patient' => $patient, 'appointment' => $appointment], function ($message) use ($patient) {
                $message->to($patient->email, $patient->first_name)
                    ->subject('Join Our Online Appointment Now');
            });
        }
    }
}
