<?php

namespace App\Http\Controllers\Dashboard\Notification;

use App\Models\Notification;
use App\Models\NotificationAvailable;
use Illuminate\Http\Request;

use App\Api\Firebase;
//use App\Models\Firebase as Model;
use App\Http\Controllers\Controller as ExController;
use App\Services\Dashboard\Notification\NotificationService;

class Controller extends ExController
{
    protected $firebase;

    public function __construct()
    {
        // $this->firebase = new Firebase();
    }

    public function index()
    {
        $notifications = Notification::latest('id')->paginate(20);
        return view('dashboard.notifications.index', compact('notifications'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $lang = $request->lang;
        $request->validate([
            'title' => 'required',
            'body' => 'required',
            'lang' => 'required|in:uz,ru',
        ]);

        Notification::create([
            'title' => $request->title,
            'body' => $request->body,
            'language' => $request->lang
        ]);

        // Example usage
        $topic = $request->lang; // Topic name (you need all devices to subscribe to this topic)
        $title = $request->title;
        $body = $request->body;

        // Send notification to multiple devices
        $service = new NotificationService();
        $response = $service->sendNotificationToTopic($topic, $title, $body);

        // Output response
        dd($response);

        return redirect()->back()->with(trans('admin.messages.created'));
    }

    public function notification_available()
    {
        $notifications = NotificationAvailable::groupBy('product_id')->select('product_id')->with('product')->selectRaw('count(id) as count')->get();

        return view('dashboard.notifications.alertNotification', compact('notifications'));
    }

    public function notification_available_view($id)
    {
        $notifications = NotificationAvailable::where('product_id', $id)->get();

        return view('dashboard.notifications.alertView', compact('notifications'));
    }
}
