<?php

namespace App\Console\Commands;

use App\Helpers\Sms;
use App\Jobs\SendBookingMessageJob;
use App\Reservation;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;

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

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $langId = currentLanguage()->id;
        $reminderDate = Carbon::now()->addHours(12)->format('Y-m-d');
        $reservations = Reservation::where('reservations.status', '=', 'confirmed')
        ->whereDate('reservations.appointment_date', $reminderDate)

            ->join('doctors', 'doctors.id', 'reservations.doctor_id')
            ->join('doctor_descriptions AS dDesc', 'doctors.id', 'dDesc.doctor_id')
            ->where('dDesc.language_id', $langId)

            ->select([
                'reservations.id',
                'reservations.email',
                'reservations.phone',
                'reservations.appointment_date',
                'reservations.appointment_time',
                'dDesc.name as doctor_name',
            ])->cursor();


        foreach ($reservations as $reservation) {
            $message = __('reservations.appointment_msg_status_3');
            $doctorName = $reservation->doctor_name;
            $appointmentDate = date('F, D, Y', strtotime($reservation->appointment_date)) . ' at ' . date('h:i A', strtotime($reservation->appointment_time));
            $message = str_replace_array('@@', [$doctorName, $appointmentDate], $message);

//            try{
//                Sms::send($reservation->phone, $message);
//            } catch (Exception $exception){
//                return ['errors' => __('members.sms_error')];
//            }

            try{
                $data = [
                    'subject' => __('reservations.reservation_reminder_msg'),
                    'message' => $message,
                    'email' => $reservation->email
                ];
                SendBookingMessageJob::dispatch($data, 'web.bookings.emails.send_email');

            } catch (\Exception $e){}
        }
    }
}
