<?php

namespace App\Services;

use App\Models\User;
use App\Models\Notification;
use Illuminate\Support\Facades\Http;
use Firebase\JWT\JWT;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class NotificationService
{
    public function sendNotification($data, $saveToDb = false)
    {
        try {
            $title = $data['title'] ?? "Valo";
            $msg = $data['message'];

            $admin = User::where('user_type', 0)->first();
            $userData = User::find($data['receiverID']);
            // return $userData; 
             Log::info($userData);
            if (!$userData) {
                throw new \Exception("User not found.");
            }

            // Save notification in the database if required
            if ($saveToDb) {
                $notifyData = [
                    'title' => $title,
                    'message' => $msg,
                    'booking_id' => $data['booking_id'],
                    'sender_id' => $data['sender_id'] ?? $admin->id,
                    'receiver_id' => $data['receiverID'],
                    'type' => $data['type'],
                    'created_at' => Carbon::now()->utc(), 
                    'updated_at' => Carbon::now()->utc(),
                ];
                Notification::create($notifyData);
            }

            // Prepare FCM payload
            $payload = [
                'title' => $title,
                'body' => $msg,
                'sender_id' => (string) $admin->id,
                'receiver_id' => (string) $data['receiverID'],
                'type' => (string) $data['type'],
            ];

            $deviceType = $userData->device_type ?? "web";
            $deviceToken = $userData->device_token;
            
            
              Log::info($deviceToken);
              
            if (empty($deviceToken)) {
                throw new \Exception("Device token is missing for the user.");
            }

            // Build the FCM message payload
            $message = $this->buildMessage($deviceType, $deviceToken, $title, $msg, $payload);

            // Generate Firebase JWT
            $serviceAccountPath = storage_path('app/fcm/valo-app-firebase.json');
            $serviceAccount = json_decode(file_get_contents($serviceAccountPath), true);

            $jwt = $this->generateJWT($serviceAccount);

            // Send the FCM Notification
            $url = "https://fcm.googleapis.com/v1/projects/{$serviceAccount['project_id']}/messages:send";
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $jwt,
                'Content-Type' => 'application/json',
            ])->post($url, ['message' => $message]);

            if ($response->successful()) {
                return [
                    'status' => 'success',
                    'message' => 'Notification sent successfully.',
                    'response' => $response->json(),
                ];
            }

            throw new \Exception("Failed to send notification: " . $response->body());
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage(),
            ];
        }
    }

    private function buildMessage($deviceType, $deviceToken, $title, $msg, $payload)
    {
        if ($deviceType === "web") {
            return [
                'token' => $deviceToken,
                'notification' => [
                    'title' => $title,
                    'body' => $msg,
                ],
                'data' => $payload,
            ];
        } elseif ($deviceType === "ios") {
            return [
                'token' => $deviceToken,
                // 'notification' => [
                //     'title' => $title,
                //     'body' => $msg,
                // ],
                'data' => $payload,
            ];
        } else {
            return [
                'token' => $deviceToken,
                // 'notification' => [
                //     'title' => $title,
                //     'body' => $msg,
                // ],
                'data' => $payload,
            ];
        }
    }

    private function generateJWT($serviceAccount)
    {
        $token = [
            'iss' => $serviceAccount['client_email'],
            'sub' => $serviceAccount['client_email'],
            'aud' => 'https://fcm.googleapis.com/',
            'iat' => time(),
            'exp' => time() + 3600,
        ];

        return JWT::encode($token, $serviceAccount['private_key'], 'RS256');
    }
}
