<?php

namespace App\Services;

use App\Models\Client;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use Kreait\Firebase\Messaging\AndroidConfig;
use Kreait\Firebase\Messaging\ApnsConfig;
use Illuminate\Support\Facades\Log;

class FcmService
{
    protected $messaging;

    public function __construct()
    {
        $factory = app('firebase');
        $this->messaging = $factory->createMessaging();
    }

    /**
     * إرسال إشعار لعميل واحد
     */
    public function sendToClient(Client $client, string $title, string $body, array $data = []): bool
    {
        if (!$client->fcm_token) {
            Log::warning("Client {$client->id} does not have an FCM token");
            return false;
        }

        return $this->sendToToken($client->fcm_token, $title, $body, $data);
    }

    /**
     * إرسال إشعار لعدة عملاء
     */
    public function sendToClients($clients, string $title, string $body, array $data = []): array
    {
        $results = [
            'success' => 0,
            'failed' => 0,
            'skipped' => 0,
        ];

        foreach ($clients as $client) {
            $token = is_array($client) ? ($client['fcm_token'] ?? null) : ($client->fcm_token ?? null);
            $clientId = is_array($client) ? ($client['id'] ?? '?') : ($client->id ?? '?');

            if (!$token) {
                $results['skipped']++;
                continue;
            }

            if ($this->sendToToken($token, $title, $body, $data)) {
                $results['success']++;
            } else {
                $results['failed']++;
            }
        }

        return $results;
    }

    /**
     * إرسال إشعار لجميع العملاء
     */
    public function sendToAllClients(string $title, string $body, array $data = []): array
    {
        $clients = Client::whereNotNull('fcm_token')
            ->where('is_active', true)
            ->get();

        $totalActive = Client::where('is_active', true)->count();
        $skipped = $totalActive - $clients->count();

        $results = $this->sendToClients($clients, $title, $body, $data);
        $results['skipped'] += $skipped;

        return $results;
    }

    /**
     * إرسال إشعار باستخدام token مباشرة مع بيانات غنية
     */
    public function sendToToken(string $token, string $title, string $body, array $data = []): bool
    {
        try {
            $notification = Notification::create($title, $body);

            // تحويل كل القيم إلى string (متطلبات FCM)
            $stringData = [];
            foreach ($data as $key => $value) {
                if ($value !== null && $value !== '') {
                    $stringData[(string) $key] = (string) $value;
                }
            }

            $message = CloudMessage::withTarget('token', $token)
                ->withNotification($notification);

            if (!empty($stringData)) {
                $message = $message->withData($stringData);
            }

            // إعدادات Android
            $message = $message->withAndroidConfig(
                AndroidConfig::fromArray([
                    'priority' => 'high',
                    'notification' => [
                        'title' => $title,
                        'body' => $body,
                        'sound' => 'default',
                        'click_action' => $data['action_url'] ?? null,
                        'channel_id' => 'default_channel',
                    ],
                ])
            );

            // إعدادات iOS
            $message = $message->withApnsConfig(
                ApnsConfig::fromArray([
                    'payload' => [
                        'aps' => [
                            'alert' => [
                                'title' => $title,
                                'body' => $body,
                            ],
                            'sound' => 'default',
                            'badge' => 1,
                        ],
                    ],
                ])
            );

            $this->messaging->send($message);

            Log::info("FCM notification sent successfully", [
                'token' => substr($token, 0, 20) . '...',
                'title' => $title,
                'data_keys' => array_keys($stringData),
            ]);

            return true;
        } catch (\Exception $e) {
            Log::error("Failed to send FCM notification: " . $e->getMessage(), [
                'token' => substr($token, 0, 20) . '...',
                'title' => $title,
            ]);
            return false;
        }
    }
}
