<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Reminder;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class PushNotificationsController extends Controller
{
public function send(): JsonResponse|bool|string
{
$day = Carbon::now()->dayOfWeek;
$reminders = Reminder::all();
$devices = [];
for ($counter = 0; $counter < count($reminders); $counter++) {
if (in_array($day, json_decode($reminders[$counter]->days))) {
$devices[] = $reminders[$counter];
}
}
if (count($devices) > 0) {
for ($counter = 0; $counter < count($devices); $counter++) {
$hour = substr($devices[$counter]->start_time, 0, strpos($devices[$counter]->start_time, ':'));
if (Carbon::createFromTime(Carbon::now()->hour, Carbon::now()->minute)->diffInMinutes(Carbon::createFromTime($hour, '00')) == 5) {
$headers = array(
'Authorization: key= AAAAfflulQQ:APA91bGZB2T4BfhTE5xVCAiNEwuvkuYkYrhZ55PiH1Vb47mHpq8LCumUmC7YOsHqIO7vDVGTAZ36CKyXQAvqkkv31G7RJ9pettC1FyDKZqDes5WlaPe3Z6dDJWbnwV6V2z4BXrMjDXly',
'Content-Type: application/json'
);
$fields = array(
'to' => $devices[$counter]->push_token,
'notification' => ['body' => $devices[$counter]->show_name . ' will start in 5 minutes time. Tune in to listen.', 'title' => $devices[$counter]->show_name],
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
}
return error_api_processor('No reminders found at this time', 200, []);
}
}