<?php

namespace App\Listeners;

use App\Events\AppointmentBooked;
use App\Models\Setting;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Mail;

class SendAppointmentBookedEmail implements ShouldQueue
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(AppointmentBooked $event)
    {
        $appointment = $event->appointment;
        $patient = $appointment->patient;

        $datetimeUtc = $appointment->appointment_date . ' ' . $appointment->appointment_time;
        $dateTimeUtc = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $datetimeUtc, 'UTC');
        $appointmentTimeZone = new \Carbon\CarbonTimeZone($appointment->timezone);
        $dateTimeInAppointmentTimeZone = $dateTimeUtc->setTimezone($appointmentTimeZone);
        $appointment->appointment_date = $appointmentDate = $dateTimeInAppointmentTimeZone->format('Y-m-d');
        $appointment->appointment_time = $appointmentTime = $dateTimeInAppointmentTimeZone->format('H:i:s');

        $setting = Setting::find(1);

        Mail::send('emails.appointmentBooked', [
            'patient' => $patient,
            'appointment' => $appointment,
            'setting' => $setting
        ], function ($message) use ($patient) {
            $message->to($patient->email, $patient->first_name)
                ->subject('Appointment Booked.');
        });
    }
}
