<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Notification;
use App\Models\User;
use App\Services\FirebaseNotificationService;
use Exception;
use Illuminate\Http\Request;
// use Kreait\Firebase\Exception\MessagingException;
// use Kreait\Firebase\Factory;
// use Kreait\Firebase\Messaging\CloudMessage;

class NotificationController extends Controller
{

    private $firebase;

    public function __construct(FirebaseNotificationService $firebase)
    {
        $this->firebase = $firebase;
    }

    public function create()
    {
        $users = User::get();
        return view('admin.notification.send-notification', compact('users'));
    }


    public function sendNotification(Request $request)
    {
        $attributes = $request->validate([
            'title' => 'nullable|string|max:255',
            'body' => 'nullable|string|max:255',
            'img' => 'nullable|string|max:255',
            'topic' => 'nullable|string|max:255',
        ]);

        $title = $request->title;
        $body =  $request->body;
        $topic =  $request->topic;
        $users_ids =  $request->users_ids;
        $data = $request->data ?? [];
        $img = $request->img;

        if ($request->type == "token"):
            $Tokens = User::whereNotNull('notification_id')
                ->whereIn('id', $users_ids)
                ->where('allow_notifications', true)
                ->pluck('notification_id', 'id')
                ->toArray();

            if (!empty($Tokens)):
                $this->firebase->sendToTokens(array_values($Tokens), $title, $body, $data, $img);
                $NotificationData = [];
                foreach ($Tokens as $userId => $id):
                    $attributes['user_id'] = $userId;
                    $attributes['created_at'] = now();
                    $attributes['updated_at'] = now();
                    unset($attributes['topic']);
                    $NotificationData[] = $attributes;
                endforeach;
                Notification::insert($NotificationData);
                return redirect('admin/notification/create')->with('success', 'Notification sent successfully to users');
            endif;
        endif;

        if ($request->type == "topic"):
            $this->firebase->sendToTopic($topic, $title, $body, $data, $img);
            $users = User::select('id')
                ->where('allow_notifications', true)
                ->get();

            $NotificationData = [];
            foreach ($users as $user):
                $attributes['user_id'] = $user->id;
                $attributes['created_at'] = now();
                $attributes['updated_at'] = now();
                unset($attributes['topic']);
                $NotificationData[] = $attributes;
            endforeach;

            if (!empty($NotificationData)):
                Notification::insert($NotificationData);
            endif;
            return redirect('admin/notification/create')->with('success', "Notification sent successfully to topic $topic");
        endif;


        return back()->with('error', 'error');
    }
}
