<?php

namespace App\Services;

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

class NotificationService
{
    /**
     * Send a notification to a user
     */
    public static function send(
        int $userId,
        string $type,
        string $title,
        string $body,
        ?string $actionUrl = null,
        ?string $icon = null,
        string $iconColor = 'primary',
        ?array $data = null
    ): ?UserNotification {
        try {
            return UserNotification::create([
                'user_id' => $userId,
                'type' => $type,
                'title' => $title,
                'body' => $body,
                'action_url' => $actionUrl,
                'icon' => $icon,
                'icon_color' => $iconColor,
                'data' => $data,
            ]);
        } catch (\Exception $e) {
            Log::error("Failed to send notification: " . $e->getMessage());
            return null;
        }
    }

    /**
     * Send notification to multiple users
     */
    public static function sendToMany(
        array $userIds,
        string $type,
        string $title,
        string $body,
        ?string $actionUrl = null,
        ?string $icon = null,
        string $iconColor = 'primary',
        ?array $data = null
    ): int {
        $count = 0;
        foreach ($userIds as $userId) {
            if (self::send($userId, $type, $title, $body, $actionUrl, $icon, $iconColor, $data)) {
                $count++;
            }
        }
        return $count;
    }

    /**
     * Send notification to all users with a specific role
     */
    public static function sendToRole(
        string $roleName,
        string $type,
        string $title,
        string $body,
        ?string $actionUrl = null,
        ?string $icon = null,
        string $iconColor = 'primary',
        ?array $data = null
    ): int {
        $userIds = User::whereHas('roles', function ($q) use ($roleName) {
            $q->where('name', $roleName);
        })->pluck('id')->toArray();

        return self::sendToMany($userIds, $type, $title, $body, $actionUrl, $icon, $iconColor, $data);
    }

    // ==================== PREDEFINED NOTIFICATIONS ====================

    /**
     * Subscription activated
     */
    public static function subscriptionActivated(int $userId, string $planName, string $expiryDate): ?UserNotification
    {
        return self::send(
            $userId,
            'subscription',
            'Subscription Activated! 🎉',
            "Your {$planName} plan is now active until {$expiryDate}. Enjoy premium features!",
            route('seller.subscription.index'),
            'bi-gem',
            'success',
            ['plan_name' => $planName, 'expiry' => $expiryDate]
        );
    }

    /**
     * Subscription expiring soon
     */
    public static function subscriptionExpiring(int $userId, string $planName, int $daysLeft): ?UserNotification
    {
        $color = $daysLeft <= 1 ? 'danger' : ($daysLeft <= 3 ? 'warning' : 'info');
        return self::send(
            $userId,
            'subscription',
            "Subscription Expiring in {$daysLeft} Days",
            "Your {$planName} plan will expire soon. Renew now to avoid interruption.",
            route('seller.subscription.index'),
            'bi-clock-history',
            $color,
            ['plan_name' => $planName, 'days_left' => $daysLeft]
        );
    }

    /**
     * KYC approved
     */
    public static function kycApproved(int $userId): ?UserNotification
    {
        return self::send(
            $userId,
            'kyc',
            'KYC Verified! ✓',
            'Your documents have been verified. You are now KYC Verified!',
            route('seller.profile'),
            'bi-shield-check',
            'success'
        );
    }

    /**
     * KYC rejected
     */
    public static function kycRejected(int $userId, string $reason): ?UserNotification
    {
        return self::send(
            $userId,
            'kyc',
            'KYC Verification Failed',
            "Your documents were rejected. Reason: {$reason}. Please re-upload valid documents.",
            route('seller.verification.index'),
            'bi-shield-x',
            'danger',
            ['reason' => $reason]
        );
    }

    /**
     * Product approved
     */
    public static function productApproved(int $userId, string $productName): ?UserNotification
    {
        return self::send(
            $userId,
            'product',
            'Product Approved',
            "Your product \"{$productName}\" is now live and visible to buyers.",
            route('seller.products.index'),
            'bi-check-circle',
            'success',
            ['product_name' => $productName]
        );
    }

    /**
     * Product rejected
     */
    public static function productRejected(int $userId, string $productName, string $reason): ?UserNotification
    {
        return self::send(
            $userId,
            'product',
            'Product Rejected',
            "Your product \"{$productName}\" was rejected. Reason: {$reason}",
            route('seller.products.index'),
            'bi-x-circle',
            'danger',
            ['product_name' => $productName, 'reason' => $reason]
        );
    }

    /**
     * New inquiry received
     */
    public static function newInquiry(int $userId, string $buyerName, string $productName): ?UserNotification
    {
        return self::send(
            $userId,
            'inquiry',
            'New Inquiry Received',
            "{$buyerName} sent an inquiry about \"{$productName}\".",
            route('seller.inquiries.index'),
            'bi-envelope-open',
            'info',
            ['buyer_name' => $buyerName, 'product_name' => $productName]
        );
    }

    /**
     * Payment received (for manual approval)
     */
    public static function paymentPending(int $userId, string $amount): ?UserNotification
    {
        return self::send(
            $userId,
            'payment',
            'Payment Under Review',
            "Your payment of {$amount} is being reviewed. We'll notify you once approved.",
            route('seller.subscription.index'),
            'bi-hourglass-split',
            'warning',
            ['amount' => $amount]
        );
    }

    /**
     * Admin broadcast message
     */
    public static function adminBroadcast(int $userId, string $title, string $message): ?UserNotification
    {
        return self::send(
            $userId,
            'system',
            $title,
            $message,
            null,
            'bi-megaphone',
            'primary'
        );
    }
}
