-
Notifications
You must be signed in to change notification settings - Fork 0
/
TrainingController.php
62 lines (48 loc) · 1.95 KB
/
TrainingController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Statamic\Facades\GlobalSet;
use DateTime;
use App\Jobs\RefreshCacheJob;
class TrainingController extends Controller
{
public function update(Request $request)
{
// Check if API_TOKEN is set in config
if (!config('services.api.token')) {
return response()->json(['error' => 'API token not set'], 500);
}
// Check if the request has the correct token
$token = $request->header('Authorization');
if ($token !== 'Bearer ' . config('services.api.token')) {
return response()->json(['error' => 'Unauthorized'], 401);
}
// Validate the request body
$validated = $request->validate([
'data' => 'required|array',
]);
$activityGlobal = GlobalSet::findByHandle('activity');
if (!$activityGlobal) {
return response()->json(['error' => 'Global set not found'], 404);
}
$originalTrainingsData = $activityGlobal->inDefaultSite()->get('trainings', []);
$trainingsData = $originalTrainingsData;
foreach ($validated['data'] as $date => $uuid) {
$dateTime = new DateTime($date);
// Adjust for late-night trainings
if ((int)$dateTime->format('G') < 4) {
$dateTime->modify('-1 day');
$dateTime->setTime(23, 59, 59);
}
$trainingsData[$dateTime->format('Y-m-d\TH:i:sP')] = $uuid;
}
ksort($trainingsData);
$dataHasChanged = $originalTrainingsData !== $trainingsData;
if ($dataHasChanged) {
$activityGlobal->inDefaultSite()->set('trainings', $trainingsData)->save();
RefreshCacheJob::dispatch(['/activity-graph-component']);
RefreshCacheJob::dispatch(['/training-data-from-ios-to-statamic']);
}
return response()->json(['success' => 'Trainings updated successfully.']);
}
}