<?php

namespace App\Services\Notification;

use App\Models\Notification;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class NotificationDispatcher
{
    /**
     * Send in-app notification to a user
     */
    public function notifyUser(User $user, string $title, string $message, ?string $actionUrl = null, string $type = 'info'): Notification
    {
        $notification = Notification::create([
            'user_id' => $user->id,
            'title' => $title,
            'message' => $message,
            'type' => $type,
            'action_url' => $actionUrl,
            'is_read' => false,
        ]);

        // Log external channel dispatch simulation (SMS / WhatsApp)
        Log::info("Notification dispatched to User #{$user->id} ({$user->phone}): [{$title}] {$message}");

        return $notification;
    }

    /**
     * Notify all administrators and auction managers
     */
    public function notifyAdmins(string $title, string $message, ?string $actionUrl = null): void
    {
        $admins = User::whereIn('role', ['super_admin', 'admin', 'auction_manager', 'sales_manager'])->get();

        foreach ($admins as $admin) {
            Notification::create([
                'user_id' => $admin->id,
                'title' => $title,
                'message' => $message,
                'type' => 'admin_alert',
                'action_url' => $actionUrl,
                'is_read' => false,
            ]);
        }
    }

    /**
     * Generate WhatsApp direct link for customer support
     */
    public static function generateWhatsAppLink(string $phone, string $message): string
    {
        $cleanPhone = preg_replace('/[^0-9]/', '', $phone);
        return 'https://wa.me/' . $cleanPhone . '?text=' . urlencode($message);
    }
}
