<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Models\Appointments;
use App\Models\Patients;
use App\Models\UserNotification;
use Illuminate\Support\Facades\Auth;
use App\Events\AppointmentCreated;
use App\Events\PatientCreated;
use App\Listeners\SendAppointmentNotification;
use App\Listeners\SendPatientNotification;

class NotificationServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        // Observador para citas nuevas
        Appointments::created(function ($appointment) {
            // Crear notificación para todos los usuarios con permiso de ver citas
            $this->createAppointmentNotification($appointment);
        });
        
        // Observador para pacientes nuevos
        Patients::created(function ($patient) {
            // Crear notificación para todos los usuarios con permiso de ver pacientes
            $this->createPatientNotification($patient);
        });
    }
    
    /**
     * Crear notificación para cita nueva
     */
    protected function createAppointmentNotification($appointment)
    {
        // Obtener usuarios con permiso de ver citas
        $users = \App\Models\User::whereHas('roles', function($q) {
            $q->whereHas('permissions', function($query) {
                $query->where('name', 'view-appointment');
            });
        })->get();
        
        // Cargar la relación con el paciente
        $appointment->load(['patient', 'user']);
        
        foreach ($users as $user) {
            // Crear notificación
            UserNotification::create([
                'user_id' => $user->id,
                'title' => 'Nueva cita registrada',
                'message' => 'Se ha registrado una nueva cita para el paciente ' . 
                            ($appointment->patient ? $appointment->patient->firstname . ' ' . $appointment->patient->lastname : 'N/A') . 
                            ' con el Dr. ' . 
                            ($appointment->user && $appointment->user->profile ? $appointment->user->profile->firstname . ' ' . $appointment->user->profile->lastname : 'N/A'),
                'link' => '/admin/detail-appointment?id=' . $appointment->id,
                'icon' => 'calendar-check',
                'type' => 'info',
                'related_id' => $appointment->id
            ]);
        }
    }
    
    /**
     * Crear notificación para paciente nuevo
     */
    protected function createPatientNotification($patient)
    {
        // Obtener usuarios con permiso de ver pacientes
        $users = \App\Models\User::whereHas('roles', function($q) {
            $q->whereHas('permissions', function($query) {
                $query->where('name', 'view-patient');
            });
        })->get();
        
        foreach ($users as $user) {
            // Crear notificación
            UserNotification::create([
                'user_id' => $user->id,
                'title' => 'Nuevo paciente registrado',
                'message' => 'Se ha registrado un nuevo paciente: ' . $patient->firstname . ' ' . $patient->lastname,
                'link' => '/admin/detail-patient?id=' . $patient->id,
                'icon' => 'user-plus',
                'type' => 'success',
                'related_id' => $patient->id
            ]);
        }
    }
}
