<?php

namespace App\Console\Commands;

use App\Models\Patient;
use App\Models\PatientRegActivity;
use App\Notifications\AppointmentReminder;
use App\Notifications\RegistrationReminder;
use Illuminate\Console\Command;

class SendReminderEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send-reminder-emails';

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

    /**
     * Execute the console command.
     */
    public function handle()
    {

        $incompleteRegistrations = PatientRegActivity::where('activity', 'patient_registered')
            ->whereNotExists(function ($query) {
                $query->select('id')
                    ->from('patient_reg_activity')
                    ->whereColumn('patient_reg_activity.patient_id', 'patient_reg_activity.patient_id')
                    ->where('activity', 'patient_appointment_booked');
            })->where("patient_reg_activity.email_sent", "!=", 1)->get();

        foreach ($incompleteRegistrations as $patient) {

            $patient->notify(new RegistrationReminder($patient->patient_id));
            $patient->email_sent = 1;
            $patient->save();
        }

        $incompleteAppointments = PatientRegActivity::where('activity', 'patient_appointment_booked')
            ->whereNotExists(function ($query) {
                $query->select('id')
                    ->from('patient_reg_activity')
                    ->whereColumn('patient_reg_activity.patient_id', 'patient_reg_activity.patient_id')
                    ->where('activity', 'patient_medical_question_entered');
            })->where("patient_reg_activity.email_sent", "!=", 1)->get();

        foreach ($incompleteAppointments as $patient) {
            echo "Into patient_medical_question_entered";
            $patient->notify(new AppointmentReminder($patient->patient_id));
            $patient->email_sent = 1;
            $patient->save();
        }

        $this->info('Reminder emails sent successfully.');
    }
}
