78 lines
2.3 KiB
PHP
78 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Models\User;
|
|
use App\Models\Promo;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Log;
|
|
use App\Http\Controllers\Controller;
|
|
use Kreait\Firebase\Messaging\CloudMessage;
|
|
use Kreait\Firebase\Messaging\Notification;
|
|
|
|
class PromoApiController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$promo = Promo::all();
|
|
return response()->json([
|
|
'status' => 'success',
|
|
'data' => $promo
|
|
], 200);
|
|
}
|
|
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$request->validate([
|
|
'judul' => 'required',
|
|
'deskripsi' => 'required',
|
|
]);
|
|
|
|
// Create discount
|
|
$promo = Promo::create($request->all());
|
|
// Assuming $promo->user_id exists and is correct
|
|
$userId = $promo->first()->user_id;
|
|
// Check if user exists before sending notification
|
|
if ($userId) {
|
|
$this->sendNotificationToUserPromo($userId, $request->judul, $request->deskripsi);
|
|
}
|
|
|
|
return response()->json([
|
|
'status' => 'success',
|
|
'data' => $promo
|
|
], 201);
|
|
}
|
|
|
|
public function sendNotificationToUserPromo($userId, $judul, $message)
|
|
{
|
|
// Dapatkan FCM token user dari tabel 'users'
|
|
$user = User::find($userId);
|
|
|
|
// Check if user existPPs
|
|
if ($user) {
|
|
$token = $user->fcm_id;
|
|
|
|
// Check if user has a valid FCM token
|
|
if ($token) {
|
|
// Kirim notifikasi ke perangkat Android
|
|
$messaging = app('firebase.messaging');
|
|
$notification = Notification::create($judul, $message);
|
|
|
|
$message = CloudMessage::withTarget('token', $token)
|
|
->withNotification($notification);
|
|
|
|
$messaging->send($message);
|
|
} else {
|
|
// Handle case where user does not have an FCM token
|
|
// Log the issue or take appropriate action
|
|
Log::warning("User with ID $userId does not have an FCM token.");
|
|
}
|
|
} else {
|
|
// Handle case where user is not found
|
|
// Log the issue or take appropriate action
|
|
Log::warning("User with ID $userId not found.");
|
|
}
|
|
}
|
|
}
|