<?php

namespace App\Services;

use App\Models\Admin;
use App\Models\User;
use App\Notifications\AdminActionNotification;
use Illuminate\Support\Facades\Notification;

class AdminNotifier
{
      /**
       * Notify relevant admins based on the user's visibility level.
       *
       * Rules:
       * - visibility_level = 2 (super_admin user) → notify **only super admins**
       * - visibility_level = 1 (admin-only user) → notify **all admins**
       * - visibility_level = 0 (normal user or guest) → notify **all admins**
       *
       * @param string $actionType  The type of action to notify about
       * @param array $details      Additional details for the notification
       * @param User|null $user     The user who performed the action (optional)
       */
      public static function notify(string $actionType, array $details = [], User $user = null)
      {
            // Safely cast visibility_level to integer (in case it's null)
            $visibility = (int) ($user?->visibility_level ?? 0);

            if ($visibility === 2) {
                  // Only notify super admins
                  // Use LOWER(role) to prevent case sensitivity issues
                  $admins = Admin::whereRaw('LOWER(role) = ?', ['super_admin'])->get();
            } else {
                  // Notify all admins (including super admins)
                  $admins = Admin::all();
            }

            // Optional debug log: shows which admins will receive the notification
            \Log::info('Admins to notify: ' . $admins->pluck('email')->join(', '));

            // Send the notification if there are any admins to notify
            if ($admins->isNotEmpty()) {
                  Notification::send(
                        $admins,
                        new AdminActionNotification($actionType, $details, $user)
                  );
            }
      }
}