-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimpact-api.php
More file actions
89 lines (77 loc) · 2.73 KB
/
Copy pathimpact-api.php
File metadata and controls
89 lines (77 loc) · 2.73 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
/**
* Impact Tracker API — Feed Humanity
*
* Lightweight REST API backed by a flat JSON file.
* No database needed — works on any PHP shared hosting.
*
* Endpoints:
* GET ?action=stats — total meals, cities, posts
* GET ?action=map — lat/lng data for map markers
* POST ?action=track — add a new impact entry
*/
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
$DATA_FILE = __DIR__ . '/impact-data.json';
function loadData($file) {
if (!file_exists($file)) return ['entries' => []];
$data = json_decode(file_get_contents($file), true);
return $data ?: ['entries' => []];
}
function saveData($file, $data) {
file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT), LOCK_EX);
}
$action = $_GET['action'] ?? '';
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'stats') {
$data = loadData($DATA_FILE);
$entries = $data['entries'];
$totalMeals = array_sum(array_column($entries, 'meals_count'));
$cities = array_unique(array_column($entries, 'city'));
echo json_encode([
'total_meals' => $totalMeals,
'total_cities' => count($cities),
'total_posts' => count($entries),
]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $action === 'map') {
$data = loadData($DATA_FILE);
$markers = array_map(function($e) {
return [
'lat' => $e['lat'] ?? 0,
'lng' => $e['lng'] ?? 0,
'city' => $e['city'] ?? '',
'meals' => $e['meals_count'] ?? 0,
];
}, $data['entries']);
echo json_encode($markers);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action === 'track') {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['city']) || !isset($input['meals_count'])) {
http_response_code(400);
echo json_encode(['error' => 'Required: city, meals_count']);
exit;
}
$data = loadData($DATA_FILE);
$entry = [
'id' => count($data['entries']) + 1,
'meals_count' => (int)$input['meals_count'],
'city' => $input['city'],
'state' => $input['state'] ?? '',
'lat' => (float)($input['lat'] ?? 0),
'lng' => (float)($input['lng'] ?? 0),
'platform' => $input['platform'] ?? '',
'tracked_at' => date('c'),
];
$data['entries'][] = $entry;
saveData($DATA_FILE, $data);
echo json_encode($entry);
exit;
}
http_response_code(400);
echo json_encode(['error' => 'Invalid action. Use ?action=stats|map|track']);