<?php

namespace App\Services;

use Google\Client as GoogleClient;
use Google\Exception as GoogleException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Exception;

class FCMService
{
    protected $serverKey;
    protected $projectId;

    public function __construct()
    {
        $this->serverKey = config('services.firebase.server_key');
        $this->projectId = config('services.firebase.project_id');
    }

    /**
     * Send push notification to a single device
     */
    public function sendToDevice($deviceToken, $title, $body, $data = [], $imageUrl = null)
    {
        try {
            $notification = [
                'title' => $title,
                'body' => $body,
            ];

            if ($imageUrl) {
                $notification['image'] = $imageUrl;
            }

            $message = [
                'to' => $deviceToken,
                'notification' => $notification,
                'data' => $data,
                'priority' => 'high',
                'content_available' => true,
            ];

            return $this->sendMessage($message);
        } catch (Exception $e) {
            Log::error("FCM send to device error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Send push notification to multiple devices
     */
    public function sendToDevices($deviceTokens, $title, $body, $data = [], $imageUrl = null)
    {
        try {
            $notification = [
                'title' => $title,
                'body' => $body,
            ];

            if ($imageUrl) {
                $notification['image'] = $imageUrl;
            }

            $message = [
                'registration_ids' => $deviceTokens,
                'notification' => $notification,
                'data' => $data,
                'priority' => 'high',
                'content_available' => true,
            ];

            return $this->sendMessage($message);
        } catch (Exception $e) {
            Log::error("FCM send to devices error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Send push notification to a topic
     */
    public function sendToTopic($topic, $title, $body, $data = [], $imageUrl = null)
    {
        try {
            $notification = [
                'title' => $title,
                'body' => $body,
            ];

            if ($imageUrl) {
                $notification['image'] = $imageUrl;
            }

            $message = [
                'to' => '/topics/' . $topic,
                'notification' => $notification,
                'data' => $data,
                'priority' => 'high',
                'content_available' => true,
            ];

            return $this->sendMessage($message);
        } catch (Exception $e) {
            Log::error("FCM send to topic error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Subscribe device to topic
     */
    public function subscribeToTopic($deviceTokens, $topic)
    {
        try {
            if (!is_array($deviceTokens)) {
                $deviceTokens = [$deviceTokens];
            }

            $response = Http::withHeaders([
                'Authorization' => 'key=' . $this->serverKey,
                'Content-Type' => 'application/json',
            ])->post('https://iid.googleapis.com/iid/v1:batchAdd', [
                'to' => '/topics/' . $topic,
                'registration_tokens' => $deviceTokens,
            ]);

            return $response->successful();
        } catch (Exception $e) {
            Log::error("FCM subscribe to topic error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Unsubscribe device from topic
     */
    public function unsubscribeFromTopic($deviceTokens, $topic)
    {
        try {
            if (!is_array($deviceTokens)) {
                $deviceTokens = [$deviceTokens];
            }

            $response = Http::withHeaders([
                'Authorization' => 'key=' . $this->serverKey,
                'Content-Type' => 'application/json',
            ])->post('https://iid.googleapis.com/iid/v1:batchRemove', [
                'to' => '/topics/' . $topic,
                'registration_tokens' => $deviceTokens,
            ]);

            return $response->successful();
        } catch (Exception $e) {
            Log::error("FCM unsubscribe from topic error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Send notification with custom data
     */
    public function sendDataMessage($deviceToken, $data)
    {
        try {
            $message = [
                'to' => $deviceToken,
                'data' => $data,
                'priority' => 'high',
                'content_available' => true,
            ];

            return $this->sendMessage($message);
        } catch (Exception $e) {
            Log::error("FCM send data message error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Send the actual message via FCM
     */
    protected function sendMessage($message)
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'key=' . $this->serverKey,
                'Content-Type' => 'application/json',
            ])->post('https://fcm.googleapis.com/fcm/send', $message);

            if ($response->successful()) {
                $result = $response->json();
                Log::info("FCM message sent successfully", ['response' => $result]);
                return $result;
            } else {
                Log::error("FCM send failed", [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                return false;
            }
        } catch (Exception $e) {
            Log::error("FCM send message error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * Validate device token
     */
    public function validateToken($deviceToken)
    {
        try {
            $message = [
                'registration_ids' => [$deviceToken],
                'dry_run' => true,
                'data' => ['test' => 'test'],
            ];

            $response = $this->sendMessage($message);

            if ($response && isset($response['success']) && $response['success'] > 0) {
                return true;
            }

            return false;
        } catch (Exception $e) {
            Log::error("FCM validate token error: " . $e->getMessage());
            return false;
        }
    }
}
