<?php

namespace App\Console\Commands;

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

class send15MinAlertAppointment extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send15-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(15)->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.upcoming-meeting', ['patient' => $patient, 'appointment' => $appointment], function ($message) use ($patient) {
                $message->to("muhammadawais95@gmail.com", $patient->first_name)
                    ->subject('Upcoming Meeting Reminder');
            });
        }
    }
}
