<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Promo;
use Illuminate\Http\Request;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;

class PromoController extends Controller
{
    public function index()
    {
        $promos = Promo::orderBy('id', 'DESC')->get();
        return view('admin.promo.index', compact('promos'));
    }

    public function store(Request $request)
    {
        $data = $request->all();
        Promo::create($data);
        $this->sendNotificationToUser($data['user_id'], 'Promo Baru : ' . $request->deskripsi);
        return redirect('/admin/promo');
    }

    public function update(Request $request, $id)
    {
        $data = $request->all();
        Promo::findOrFail($id)->update($data);
        return redirect('/admin/promo');
    }

    public function destroy($id)
    {
        Promo::findOrFail($id)->delete();
        return  redirect('/admin/promo');
    }

    public function sendNotificationToUser($userId, $message)
    {
        // Dapatkan FCM token user dari tabel 'users'
        $user = User::find($userId);
        $token = $user->fcm_id;
        // Kirim notifikasi ke perangkat Android
        $messaging = app('firebase.messaging');
        $notification = Notification::create('Paket Dikirim', $message);

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

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