-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
825 lines (756 loc) · 40.5 KB
/
Copy pathapi.php
File metadata and controls
825 lines (756 loc) · 40.5 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
<?php
// JSON API — all endpoints. Called as api.php?action=<name> with a JSON body.
declare(strict_types=1);
error_reporting(E_ALL & ~E_DEPRECATED);
ini_set('display_errors', '0');
require __DIR__ . '/includes/db.php';
require __DIR__ . '/includes/auth.php';
require __DIR__ . '/includes/calc.php';
require __DIR__ . '/includes/ai.php';
require __DIR__ . '/includes/off.php';
require __DIR__ . '/includes/push.php';
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
$action = $_GET['action'] ?? '';
$in = json_decode(file_get_contents('php://input'), true) ?: [];
function out(array $data): never { echo json_encode($data); exit; }
function fail(string $msg, int $code = 400): never { http_response_code($code); out(['ok' => false, 'error' => $msg]); }
function today(): string { return $_GET['tzdate'] ?? date('Y-m-d'); }
function get_profile(int $uid): array {
$p = db()->prepare("SELECT * FROM profiles WHERE user_id=?");
$p->execute([$uid]);
return $p->fetch() ?: [];
}
function get_settings(int $uid): array {
$st = db()->prepare("SELECT key,value FROM settings WHERE user_id=?");
$st->execute([$uid]);
$out = [];
foreach ($st->fetchAll() as $r) $out[$r['key']] = $r['value'];
// never send secrets back to the client
unset($out['anthropic_key']);
return $out;
}
function public_user(array $u): array { return ['id' => $u['id'], 'name' => $u['name'], 'email' => $u['email']]; }
try {
switch ($action) {
// ── Auth ─────────────────────────────────────────────────────────────
case 'register': {
$name = trim((string)($in['name'] ?? ''));
$email = strtolower(trim((string)($in['email'] ?? '')));
$pass = (string)($in['password'] ?? '');
if ($name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) fail('Please enter a valid name and email');
if (strlen($pass) < 6) fail('Password must be at least 6 characters');
$st = db()->prepare("SELECT id FROM users WHERE email=?");
$st->execute([$email]);
if ($st->fetch()) fail('An account with this email already exists');
db()->prepare("INSERT INTO users (name,email,pass_hash) VALUES (?,?,?)")
->execute([$name, $email, password_hash($pass, PASSWORD_DEFAULT)]);
$uid = (int)db()->lastInsertId();
db()->prepare("INSERT INTO profiles (user_id) VALUES (?)")->execute([$uid]);
login_user($uid);
out(['ok' => true, 'user' => ['id' => $uid, 'name' => $name, 'email' => $email], 'profile' => get_profile($uid), 'settings' => []]);
}
case 'login': {
$email = strtolower(trim((string)($in['email'] ?? '')));
// Brute-force throttle: 5 failed tries per email → 15-minute lockout.
$lf = db()->prepare("SELECT fails, last FROM login_fails WHERE email=?");
$lf->execute([$email]);
$f = $lf->fetch();
if ($f && (int)$f['fails'] >= 5 && time() - (int)$f['last'] < 900) {
fail('Too many failed attempts — try again in 15 minutes, or use "Forgot your password?"', 429);
}
$st = db()->prepare("SELECT * FROM users WHERE email=?");
$st->execute([$email]);
$u = $st->fetch();
if (!$u || !password_verify((string)($in['password'] ?? ''), $u['pass_hash'])) {
db()->prepare("INSERT INTO login_fails (email,fails,last) VALUES (?,1,?)
ON CONFLICT(email) DO UPDATE SET
fails = CASE WHEN login_fails.last < ? - 900 THEN 1 ELSE login_fails.fails + 1 END,
last = ?")
->execute([$email, time(), time(), time()]);
fail('Wrong email or password', 401);
}
db()->prepare("DELETE FROM login_fails WHERE email=?")->execute([$email]);
login_user((int)$u['id']);
out(['ok' => true, 'user' => public_user($u), 'profile' => get_profile((int)$u['id']), 'settings' => get_settings((int)$u['id'])]);
}
case 'logout': logout_user(); out(['ok' => true]);
case 'change_password': {
$uid = require_user();
$st = db()->prepare("SELECT pass_hash FROM users WHERE id=?");
$st->execute([$uid]);
if (!password_verify((string)($in['current'] ?? ''), $st->fetch()['pass_hash'] ?? '')) {
fail('Current password is wrong');
}
if (strlen((string)($in['new'] ?? '')) < 6) fail('New password must be at least 6 characters');
db()->prepare("UPDATE users SET pass_hash=? WHERE id=?")
->execute([password_hash((string)$in['new'], PASSWORD_DEFAULT), $uid]);
revoke_remember_tokens($uid, true); // sign out other devices, keep this one
out(['ok' => true]);
}
case 'request_reset': {
$email = strtolower(trim((string)($in['email'] ?? '')));
$generic = 'If that email is registered, a reset link is on its way. Check spam too.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) out(['ok' => true, 'message' => $generic]);
$st = db()->prepare("SELECT id, reset_requested FROM users WHERE email=?");
$st->execute([$email]);
$u = $st->fetch();
if (!$u) out(['ok' => true, 'message' => $generic]);
if ((int)($u['reset_requested'] ?? 0) > time() - 120) out(['ok' => true, 'message' => $generic]); // throttle
$token = bin2hex(random_bytes(32));
db()->prepare("UPDATE users SET reset_token=?, reset_expires=?, reset_requested=? WHERE id=?")
->execute([hash('sha256', $token), time() + 3600, time(), $u['id']]);
// Never build the reset link from HTTP_HOST — a spoofed Host header would
// put an attacker's domain in the victim's email (token theft on click).
// Localhost is allowed through for development only.
$reqHost = $_SERVER['HTTP_HOST'] ?? 'localhost';
$isLocal = (bool)preg_match('/^(localhost|127\.0\.0\.1)(:\d+)?$/', $reqHost);
$host = $isLocal ? $reqHost : 'health.mobasheri.us';
$scheme = $isLocal && empty($_SERVER['HTTPS']) ? 'http' : 'https';
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
$link = $scheme . '://' . $host . $dir . '/index.php?reset=' . $token;
$mailHost = preg_replace('/:\d+$/', '', $host);
$sent = @mail(
$email,
'Thrive password reset',
"Someone requested a password reset for your Thrive account.\n\n"
. "Reset link (valid for 1 hour):\n$link\n\n"
. "If this wasn't you, you can ignore this email.",
"From: Thrive <noreply@$mailHost>\r\nContent-Type: text/plain; charset=UTF-8"
);
// Same generic reply whether or not the account exists or mail worked —
// a distinct error here would confirm which emails are registered.
if (!$sent) error_log('Thrive: password-reset mail failed for a registered account');
out(['ok' => true, 'message' => $generic]);
}
case 'reset_password': {
$token = (string)($in['token'] ?? '');
$pass = (string)($in['password'] ?? '');
if (strlen($pass) < 6) fail('Password must be at least 6 characters');
if (strlen($token) !== 64 || !ctype_xdigit($token)) fail('Invalid or expired reset link — request a new one');
$st = db()->prepare("SELECT id FROM users WHERE reset_token=? AND reset_expires > ?");
$st->execute([hash('sha256', $token), time()]);
$u = $st->fetch();
if (!$u) fail('Invalid or expired reset link — request a new one');
db()->prepare("UPDATE users SET pass_hash=?, reset_token=NULL, reset_expires=NULL WHERE id=?")
->execute([password_hash($pass, PASSWORD_DEFAULT), $u['id']]);
revoke_remember_tokens((int)$u['id']); // a reset signs out every device
out(['ok' => true]);
}
case 'me': {
$uid = current_user_id();
if (!$uid) out(['ok' => true, 'user' => null]);
$st = db()->prepare("SELECT * FROM users WHERE id=?");
$st->execute([$uid]);
$u = $st->fetch();
if (!$u) { logout_user(); out(['ok' => true, 'user' => null]); }
out(['ok' => true, 'user' => public_user($u), 'profile' => get_profile($uid), 'settings' => get_settings($uid)]);
}
// ── Profile & plan ───────────────────────────────────────────────────
case 'save_profile': {
$uid = require_user();
$p = get_profile($uid);
foreach (['sex','diet','fasting_plan','units'] as $k) if (isset($in[$k])) $p[$k] = substr((string)$in[$k], 0, 30);
foreach (['birth_year'] as $k) if (isset($in[$k])) $p[$k] = (int)$in[$k];
foreach (['height_cm','activity','start_weight_kg','goal_weight_kg','body_fat','weekly_rate'] as $k) {
if (isset($in[$k])) $p[$k] = (float)$in[$k];
}
if (isset($in['health_issues']) && is_array($in['health_issues'])) {
$p['health_issues'] = json_encode(array_slice(array_map('strval', $in['health_issues']), 0, 20));
}
$t = compute_targets($p);
db()->prepare("UPDATE profiles SET sex=?,birth_year=?,height_cm=?,activity=?,start_weight_kg=?,goal_weight_kg=?,
body_fat=?,diet=?,fasting_plan=?,health_issues=?,units=?,weekly_rate=?,
kcal_target=?,protein_g=?,carbs_g=?,fat_g=?,water_ml=?,onboarded=1 WHERE user_id=?")
->execute([$p['sex'],$p['birth_year'],$p['height_cm'],$p['activity'],$p['start_weight_kg'],$p['goal_weight_kg'],
$p['body_fat'],$p['diet'],$p['fasting_plan'],$p['health_issues'],$p['units'],$p['weekly_rate'],
$t['kcal_target'],$t['protein_g'],$t['carbs_g'],$t['fat_g'],$t['water_ml'],$uid]);
// Log starting weight if provided and no entry today
if (!empty($p['start_weight_kg'])) {
db()->prepare("INSERT INTO weights (user_id,date,weight_kg,body_fat) VALUES (?,?,?,?)
ON CONFLICT(user_id,date) DO UPDATE SET weight_kg=excluded.weight_kg, body_fat=excluded.body_fat")
->execute([$uid, today(), $p['start_weight_kg'], $p['body_fat'] ?: null]);
}
out(['ok' => true, 'profile' => get_profile($uid), 'targets' => $t]);
}
// ── Weight ───────────────────────────────────────────────────────────
case 'log_weight': {
$uid = require_user();
$w = (float)($in['weight_kg'] ?? 0);
if ($w < 20 || $w > 400) fail('Please enter a valid weight');
$date = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($in['date'] ?? '')) ? $in['date'] : today();
$bf = isset($in['body_fat']) && $in['body_fat'] !== '' ? (float)$in['body_fat'] : null;
db()->prepare("INSERT INTO weights (user_id,date,weight_kg,body_fat) VALUES (?,?,?,?)
ON CONFLICT(user_id,date) DO UPDATE SET weight_kg=excluded.weight_kg, body_fat=excluded.body_fat")
->execute([$uid, $date, $w, $bf]);
out(['ok' => true]);
}
case 'weights': {
$uid = require_user();
$st = db()->prepare("SELECT id, date, weight_kg, body_fat FROM weights WHERE user_id=? ORDER BY date");
$st->execute([$uid]);
out(['ok' => true, 'weights' => $st->fetchAll()]);
}
case 'del_weight': {
$uid = require_user();
db()->prepare("DELETE FROM weights WHERE id=? AND user_id=?")->execute([(int)($in['id'] ?? 0), $uid]);
out(['ok' => true]);
}
// ── Day summary (dashboard) ─────────────────────────────────────────
case 'day': {
$uid = require_user();
$date = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($in['date'] ?? '')) ? $in['date'] : today();
$st = db()->prepare("SELECT * FROM diary WHERE user_id=? AND date=? ORDER BY id");
$st->execute([$uid, $date]);
$entries = $st->fetchAll();
$st = db()->prepare("SELECT ml FROM water WHERE user_id=? AND date=?");
$st->execute([$uid, $date]);
$water = (int)($st->fetch()['ml'] ?? 0);
$st = db()->prepare("SELECT * FROM workouts WHERE user_id=? AND date=? ORDER BY id");
$st->execute([$uid, $date]);
$workouts = $st->fetchAll();
$st = db()->prepare("SELECT * FROM fasts WHERE user_id=? AND end_ts IS NULL ORDER BY id DESC LIMIT 1");
$st->execute([$uid]);
$activeFast = $st->fetch() ?: null;
$st = db()->prepare("SELECT weight_kg FROM weights WHERE user_id=? ORDER BY date DESC LIMIT 1");
$st->execute([$uid]);
$lastWeight = $st->fetch()['weight_kg'] ?? null;
// Today's biometrics (steps, sleep, rhr…) — Health Connect sync fills these.
$st = db()->prepare("SELECT type, v1, v2 FROM biometrics WHERE user_id=? AND date=? ORDER BY id");
$st->execute([$uid, $date]);
$bio = [];
foreach ($st->fetchAll() as $b) $bio[$b['type']] = ['v1' => $b['v1'], 'v2' => $b['v2']];
out(['ok' => true, 'date' => $date, 'entries' => $entries, 'water' => $water,
'workouts' => $workouts, 'active_fast' => $activeFast, 'last_weight' => $lastWeight, 'bio' => $bio]);
}
// ── Food & diary ─────────────────────────────────────────────────────
case 'foods': {
$uid = require_user();
$q = trim((string)($in['q'] ?? ''));
if ($q === '') {
// curated starter foods first (they have the lowest ids)
$st = db()->prepare("SELECT * FROM foods WHERE user_id IS NULL OR user_id=?
ORDER BY (user_id IS NOT NULL) DESC, id LIMIT 60");
$st->execute([$uid]);
} else {
$esc = str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $q);
// rank: my foods → name starts with query → shorter (simpler) names
$st = db()->prepare("SELECT * FROM foods WHERE (user_id IS NULL OR user_id=?)
AND name LIKE ? ESCAPE '\\'
ORDER BY (user_id IS NOT NULL) DESC,
CASE WHEN name LIKE ? ESCAPE '\\' THEN 0 ELSE 1 END,
LENGTH(name) LIMIT 60");
$st->execute([$uid, "%$esc%", "$esc%"]);
}
out(['ok' => true, 'foods' => $st->fetchAll()]);
}
case 'add_food': {
$uid = require_user();
$name = trim((string)($in['name'] ?? ''));
if ($name === '') fail('Food name is required');
$keto = ((float)($in['carbs'] ?? 0) - (float)($in['fiber'] ?? 0)) <= 8 ? 1 : 0;
$st = db()->prepare("SELECT id FROM foods WHERE user_id=? AND name=?");
$st->execute([$uid, substr($name,0,80)]);
if ($ex = $st->fetch()) {
db()->prepare("UPDATE foods SET kcal=?,protein=?,carbs=?,fat=?,fiber=?,keto=? WHERE id=?")
->execute([(float)($in['kcal'] ?? 0), (float)($in['protein'] ?? 0), (float)($in['carbs'] ?? 0),
(float)($in['fat'] ?? 0), (float)($in['fiber'] ?? 0), $keto, $ex['id']]);
out(['ok' => true, 'id' => (int)$ex['id']]);
}
db()->prepare("INSERT INTO foods (user_id,name,kcal,protein,carbs,fat,fiber,keto) VALUES (?,?,?,?,?,?,?,?)")
->execute([$uid, substr($name,0,80), (float)($in['kcal'] ?? 0), (float)($in['protein'] ?? 0),
(float)($in['carbs'] ?? 0), (float)($in['fat'] ?? 0), (float)($in['fiber'] ?? 0), $keto]);
out(['ok' => true, 'id' => (int)db()->lastInsertId()]);
}
case 'recent_foods': {
$uid = require_user();
// most recently logged distinct foods (values from the latest entry of each)
$st = db()->prepare("SELECT name, grams, kcal, protein, carbs, fat, fiber, sugar, sodium, satfat, MAX(id) mid
FROM diary WHERE user_id=? GROUP BY name ORDER BY mid DESC LIMIT 10");
$st->execute([$uid]);
$recent = $st->fetchAll();
// most frequently logged
$st = db()->prepare("SELECT name, grams, kcal, protein, carbs, fat, fiber, sugar, sodium, satfat, COUNT(*) c, MAX(id) mid
FROM diary WHERE user_id=? GROUP BY name HAVING c >= 2 ORDER BY c DESC LIMIT 10");
$st->execute([$uid]);
$frequent = $st->fetchAll();
out(['ok' => true, 'recent' => $recent, 'frequent' => $frequent]);
}
case 'barcode': {
require_user();
$code = preg_replace('/\D/', '', (string)($in['code'] ?? ''));
if (strlen($code) < 6 || strlen($code) > 14) fail('That doesn\'t look like a product barcode');
$f = off_lookup($code);
if (!$f) fail('Product not found in the Open Food Facts database — try Photo scan or add it as Custom');
out(['ok' => true, 'food' => $f]);
}
case 'off_search': {
require_user();
$q = trim((string)($in['q'] ?? ''));
if (strlen($q) < 2) fail('Type at least 2 characters');
out(['ok' => true, 'foods' => off_search($q)]);
}
case 'log_food': {
$uid = require_user();
$date = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($in['date'] ?? '')) ? $in['date'] : today();
$meal = in_array($in['meal'] ?? '', ['breakfast','lunch','dinner','snacks']) ? $in['meal'] : 'snacks';
$name = trim((string)($in['name'] ?? ''));
if ($name === '') fail('Missing food name');
db()->prepare("INSERT INTO diary (user_id,date,meal,name,grams,kcal,protein,carbs,fat,fiber,sugar,sodium,satfat) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)")
->execute([$uid, $date, $meal, substr($name,0,100), (float)($in['grams'] ?? 100),
round((float)($in['kcal'] ?? 0),1), round((float)($in['protein'] ?? 0),1),
round((float)($in['carbs'] ?? 0),1), round((float)($in['fat'] ?? 0),1), round((float)($in['fiber'] ?? 0),1),
round((float)($in['sugar'] ?? 0),1), round((float)($in['sodium'] ?? 0)), round((float)($in['satfat'] ?? 0),1)]);
out(['ok' => true, 'id' => (int)db()->lastInsertId()]);
}
// ── Saved meals (log your usual meals in one tap) ────────────────────
case 'save_meal': {
$uid = require_user();
$name = trim((string)($in['name'] ?? ''));
$items = $in['items'] ?? [];
if ($name === '' || !is_array($items) || !count($items)) fail('Meal needs a name and at least one food');
$clean = [];
foreach (array_slice($items, 0, 30) as $it) {
$clean[] = [
'name' => substr((string)($it['name'] ?? 'Item'), 0, 100),
'grams' => (float)($it['grams'] ?? 100),
'kcal' => (float)($it['kcal'] ?? 0), 'protein' => (float)($it['protein'] ?? 0),
'carbs' => (float)($it['carbs'] ?? 0), 'fat' => (float)($it['fat'] ?? 0),
'fiber' => (float)($it['fiber'] ?? 0), 'sugar' => (float)($it['sugar'] ?? 0),
'sodium' => (float)($it['sodium'] ?? 0), 'satfat' => (float)($it['satfat'] ?? 0),
];
}
db()->prepare("INSERT INTO meals (user_id,name,items) VALUES (?,?,?)")
->execute([$uid, substr($name,0,60), json_encode($clean)]);
out(['ok' => true, 'id' => (int)db()->lastInsertId()]);
}
case 'meals': {
$uid = require_user();
$st = db()->prepare("SELECT * FROM meals WHERE user_id=? ORDER BY name");
$st->execute([$uid]);
$rows = array_map(fn($m) => ['id' => $m['id'], 'name' => $m['name'], 'items' => json_decode($m['items'], true)], $st->fetchAll());
out(['ok' => true, 'meals' => $rows]);
}
case 'del_meal': {
$uid = require_user();
db()->prepare("DELETE FROM meals WHERE id=? AND user_id=?")->execute([(int)($in['id'] ?? 0), $uid]);
out(['ok' => true]);
}
// ── Biometrics (blood pressure, glucose, ketones, sleep, steps…) ────
case 'log_bio': {
$uid = require_user();
$types = ['bp','glucose','ketones','rhr','sleep','steps','hr','spo2','bodyfat'];
$type = in_array($in['type'] ?? '', $types, true) ? $in['type'] : null;
if (!$type) fail('Unknown metric type');
$v1 = (float)($in['v1'] ?? 0);
if ($v1 <= 0) fail('Enter a value');
$v2 = isset($in['v2']) && $in['v2'] !== '' ? (float)$in['v2'] : null;
$date = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($in['date'] ?? '')) ? $in['date'] : today();
db()->prepare("INSERT INTO biometrics (user_id,date,type,v1,v2) VALUES (?,?,?,?,?)")
->execute([$uid, $date, $type, $v1, $v2]);
out(['ok' => true, 'id' => (int)db()->lastInsertId()]);
}
case 'bios': {
$uid = require_user();
$st = db()->prepare("SELECT * FROM biometrics WHERE user_id=? ORDER BY date, id");
$st->execute([$uid]);
out(['ok' => true, 'bios' => $st->fetchAll()]);
}
case 'del_bio': {
$uid = require_user();
db()->prepare("DELETE FROM biometrics WHERE id=? AND user_id=?")->execute([(int)($in['id'] ?? 0), $uid]);
out(['ok' => true]);
}
// ── Health-platform sync (Health Connect, Apple Health, rings…) ──────
// A single, source-agnostic ingestion endpoint. Any connector — the Health
// Connect Android companion, a future HealthKit app, an Oura puller — POSTs
// the same normalized shape here. Idempotent: re-syncing a day replaces its
// values rather than duplicating them.
case 'sync_health': {
$uid = require_user();
$source = preg_replace('/[^a-z0-9_]/', '', strtolower((string)($in['source'] ?? 'health_connect'))) ?: 'health_connect';
$types = ['bp','glucose','ketones','rhr','sleep','steps','hr','spo2','bodyfat'];
$metrics = is_array($in['metrics'] ?? null) ? $in['metrics'] : [];
$workouts = is_array($in['workouts'] ?? null) ? $in['workouts'] : [];
$isDate = fn($d) => preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)$d);
$pdo = db();
$pdo->beginTransaction();
$mCount = 0; $wCount = 0;
$delBio = $pdo->prepare("DELETE FROM biometrics WHERE user_id=? AND date=? AND type=? AND source=?");
$insBio = $pdo->prepare("INSERT INTO biometrics (user_id,date,type,v1,v2,source) VALUES (?,?,?,?,?,?)");
$upsWeight = $pdo->prepare("INSERT INTO weights (user_id,date,weight_kg,body_fat) VALUES (?,?,?,?)
ON CONFLICT(user_id,date) DO UPDATE SET weight_kg=excluded.weight_kg");
foreach (array_slice($metrics, 0, 2000) as $m) {
$date = $m['date'] ?? '';
if (!$isDate($date)) continue;
$type = strtolower((string)($m['type'] ?? ''));
$v1 = (float)($m['value'] ?? $m['v1'] ?? 0);
if ($type === 'weight') { if ($v1 > 0) { $upsWeight->execute([$uid, $date, round($v1, 2), null]); $mCount++; } continue; }
if (!in_array($type, $types, true) || $v1 <= 0) continue;
$v2 = isset($m['value2']) && $m['value2'] !== '' ? (float)$m['value2'] : (isset($m['v2']) && $m['v2'] !== '' ? (float)$m['v2'] : null);
// one synced value per (day,type,source) — replace on re-sync
$delBio->execute([$uid, $date, $type, $source]);
$insBio->execute([$uid, $date, $type, round($v1, 2), $v2, $source]);
$mCount++;
}
$insWork = $pdo->prepare("INSERT INTO workouts (user_id,date,name,minutes,kcal,source,ext_id) VALUES (?,?,?,?,?,?,?)");
$findWork = $pdo->prepare("SELECT id FROM workouts WHERE user_id=? AND source=? AND ext_id=?");
foreach (array_slice($workouts, 0, 500) as $w) {
$date = $w['date'] ?? '';
if (!$isDate($date)) continue;
$ext = isset($w['ext_id']) ? substr((string)$w['ext_id'], 0, 80) : null;
if ($ext !== null) { $findWork->execute([$uid, $source, $ext]); if ($findWork->fetch()) continue; } // already imported
$insWork->execute([$uid, $date, substr((string)($w['name'] ?? 'Activity'), 0, 80),
round((float)($w['minutes'] ?? 0), 1), round((float)($w['kcal'] ?? 0)), $source, $ext]);
$wCount++;
}
$pdo->prepare("INSERT INTO settings (user_id,key,value) VALUES (?,?,?)
ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value")
->execute([$uid, 'sync_last_' . $source, gmdate('c')]);
$pdo->commit();
out(['ok' => true, 'metrics_synced' => $mCount, 'workouts_synced' => $wCount]);
}
case 'sync_status': {
$uid = require_user();
$st = db()->prepare("SELECT key, value FROM settings WHERE user_id=? AND key LIKE 'sync_last_%'");
$st->execute([$uid]);
$sources = [];
foreach ($st->fetchAll() as $r) $sources[substr($r['key'], 10)] = $r['value'];
$st = db()->prepare("SELECT COUNT(*) c FROM biometrics WHERE user_id=? AND source != 'manual'");
$st->execute([$uid]);
$syncedMetrics = (int)$st->fetch()['c'];
out(['ok' => true, 'sources' => $sources, 'synced_metrics' => $syncedMetrics]);
}
// ── Daily lessons (drip course) ──────────────────────────────────────
case 'lessons': {
$uid = require_user();
$lessons = db()->query("SELECT id,ord,emoji,category,title,body FROM lessons ORDER BY ord")->fetchAll();
$st = db()->prepare("SELECT lesson_id, date FROM lesson_reads WHERE user_id=?");
$st->execute([$uid]);
$reads = [];
foreach ($st->fetchAll() as $r) $reads[$r['lesson_id']] = $r['date'];
out(['ok' => true, 'lessons' => $lessons, 'reads' => $reads, 'today' => today()]);
}
case 'lesson_read': {
$uid = require_user();
$id = (int)($in['id'] ?? 0);
// Drip rule: only one NEW lesson per day
$st = db()->prepare("SELECT COUNT(*) c FROM lesson_reads WHERE user_id=? AND date=?");
$st->execute([$uid, today()]);
$alreadyToday = (int)$st->fetch()['c'] > 0;
$st = db()->prepare("SELECT COUNT(*) c FROM lesson_reads WHERE user_id=? AND lesson_id=?");
$st->execute([$uid, $id]);
if ((int)$st->fetch()['c'] === 0) {
if ($alreadyToday) fail('One new lesson per day — come back tomorrow! 🌱');
db()->prepare("INSERT INTO lesson_reads (user_id,lesson_id,date) VALUES (?,?,?)")->execute([$uid, $id, today()]);
}
out(['ok' => true]);
}
case 'del_food_entry': {
$uid = require_user();
db()->prepare("DELETE FROM diary WHERE id=? AND user_id=?")->execute([(int)($in['id'] ?? 0), $uid]);
out(['ok' => true]);
}
case 'update_food_entry': {
$uid = require_user();
$id = (int)($in['id'] ?? 0);
$grams = (float)($in['grams'] ?? 0);
if ($grams <= 0 || $grams > 5000) fail('Enter a valid portion');
$st = db()->prepare("SELECT * FROM diary WHERE id=? AND user_id=?");
$st->execute([$id, $uid]);
$e = $st->fetch();
if (!$e) fail('Entry not found');
// rescale nutrition from the stored portion (server-side so values stay honest)
$k = ($e['grams'] > 0) ? $grams / (float)$e['grams'] : 1;
db()->prepare("UPDATE diary SET grams=?, kcal=?, protein=?, carbs=?, fat=?, fiber=?, sugar=?, sodium=?, satfat=? WHERE id=?")
->execute([round($grams, 1),
round($e['kcal'] * $k, 1), round($e['protein'] * $k, 1), round($e['carbs'] * $k, 1),
round($e['fat'] * $k, 1), round($e['fiber'] * $k, 1), round($e['sugar'] * $k, 1),
round($e['sodium'] * $k), round($e['satfat'] * $k, 1), $id]);
out(['ok' => true]);
}
case 'export_data': {
$uid = require_user();
$pull = function (string $sql) use ($uid) {
$st = db()->prepare($sql);
$st->execute([$uid]);
return $st->fetchAll();
};
out(['ok' => true, 'export' => [
'app' => 'Thrive', 'exported_at' => gmdate('c'),
'profile' => get_profile($uid),
'diary' => $pull("SELECT date,meal,name,grams,kcal,protein,carbs,fat,fiber,sugar,sodium,satfat FROM diary WHERE user_id=? ORDER BY date,id"),
'weights' => $pull("SELECT date,weight_kg,body_fat FROM weights WHERE user_id=? ORDER BY date"),
'water' => $pull("SELECT date,ml FROM water WHERE user_id=? ORDER BY date"),
'workouts'=> $pull("SELECT date,name,minutes,kcal FROM workouts WHERE user_id=? ORDER BY date,id"),
'fasts' => $pull("SELECT start_ts,end_ts,target_hours FROM fasts WHERE user_id=? ORDER BY id"),
'biometrics' => $pull("SELECT date,type,v1,v2 FROM biometrics WHERE user_id=? ORDER BY date,id"),
]]);
}
// ── Water ────────────────────────────────────────────────────────────
case 'water': {
$uid = require_user();
$date = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($in['date'] ?? '')) ? $in['date'] : today();
$delta = (int)($in['delta'] ?? 0);
db()->prepare("INSERT INTO water (user_id,date,ml) VALUES (?,?,MAX(0,?))
ON CONFLICT(user_id,date) DO UPDATE SET ml=MAX(0, ml + ?)")
->execute([$uid, $date, $delta, $delta]);
$st = db()->prepare("SELECT ml FROM water WHERE user_id=? AND date=?");
$st->execute([$uid, $date]);
out(['ok' => true, 'ml' => (int)$st->fetch()['ml']]);
}
// ── Fasting ──────────────────────────────────────────────────────────
case 'fast_start': {
$uid = require_user();
db()->prepare("UPDATE fasts SET end_ts=datetime('now') WHERE user_id=? AND end_ts IS NULL")->execute([$uid]);
$hours = max(8, min(72, (float)($in['target_hours'] ?? 16)));
// Optional: the fast actually started this many minutes ago (the user forgot
// to hit start). Clamp 0…72h; the client sends the local-time delta so this
// stays timezone-safe.
$ago = max(0, min(72 * 60, (int)($in['start_min_ago'] ?? 0)));
db()->prepare("INSERT INTO fasts (user_id,start_ts,target_hours) VALUES (?,datetime('now',?),?)")
->execute([$uid, '-' . $ago . ' minutes', $hours]);
out(['ok' => true, 'id' => (int)db()->lastInsertId()]);
}
case 'fast_end': {
$uid = require_user();
db()->prepare("UPDATE fasts SET end_ts=datetime('now') WHERE user_id=? AND end_ts IS NULL")->execute([$uid]);
out(['ok' => true]);
}
// Correct the start time of the current, still-running fast.
case 'fast_adjust': {
$uid = require_user();
$ago = max(0, min(72 * 60, (int)($in['start_min_ago'] ?? 0)));
$st = db()->prepare("UPDATE fasts SET start_ts=datetime('now',?) WHERE user_id=? AND end_ts IS NULL");
$st->execute(['-' . $ago . ' minutes', $uid]);
out(['ok' => $st->rowCount() > 0]);
}
case 'fasts': {
$uid = require_user();
$st = db()->prepare("SELECT * FROM fasts WHERE user_id=? ORDER BY id DESC LIMIT 30");
$st->execute([$uid]);
out(['ok' => true, 'fasts' => $st->fetchAll(), 'server_now' => gmdate('Y-m-d H:i:s')]);
}
// ── Recipes & workouts ──────────────────────────────────────────────
case 'recipes': {
$uid = require_user();
$st = db()->prepare("SELECT name FROM recipe_favs WHERE user_id=?");
$st->execute([$uid]);
out(['ok' => true,
'recipes' => db()->query("SELECT * FROM recipes ORDER BY tag, name")->fetchAll(),
'favs' => array_column($st->fetchAll(), 'name')]);
}
case 'fav_recipe': {
$uid = require_user();
$name = substr(trim((string)($in['name'] ?? '')), 0, 120);
if ($name === '') fail('Missing recipe name');
if (!empty($in['on'])) {
db()->prepare("INSERT OR IGNORE INTO recipe_favs (user_id, name) VALUES (?,?)")->execute([$uid, $name]);
} else {
db()->prepare("DELETE FROM recipe_favs WHERE user_id=? AND name=?")->execute([$uid, $name]);
}
out(['ok' => true]);
}
// ── Kitchen: weekly meal plan + shopping list ───────────────────────
case 'meal_plan': {
$uid = require_user();
$st = db()->prepare("SELECT date, meal, recipe_id, cooked FROM meal_plans WHERE user_id=? ORDER BY date, meal");
$st->execute([$uid]);
out(['ok' => true, 'plan' => $st->fetchAll()]);
}
case 'save_plan': {
$uid = require_user();
$items = is_array($in['plan'] ?? null) ? $in['plan'] : [];
$pdo = db();
$pdo->beginTransaction();
$pdo->prepare("DELETE FROM meal_plans WHERE user_id=?")->execute([$uid]);
$st = $pdo->prepare("INSERT OR REPLACE INTO meal_plans (user_id,date,meal,recipe_id,cooked) VALUES (?,?,?,?,0)");
foreach (array_slice($items, 0, 60) as $it) {
$date = $it['date'] ?? '';
$meal = in_array($it['meal'] ?? '', ['breakfast','lunch','dinner','snacks'], true) ? $it['meal'] : null;
$rid = (int)($it['recipe_id'] ?? 0);
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) || !$meal || !$rid) continue;
$st->execute([$uid, $date, $meal, $rid]);
}
$pdo->commit();
out(['ok' => true]);
}
case 'set_meal': {
$uid = require_user();
$date = (string)($in['date'] ?? '');
$meal = in_array($in['meal'] ?? '', ['breakfast','lunch','dinner','snacks'], true) ? $in['meal'] : null;
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) || !$meal) fail('Bad slot');
if (!empty($in['clear'])) {
db()->prepare("DELETE FROM meal_plans WHERE user_id=? AND date=? AND meal=?")->execute([$uid, $date, $meal]);
out(['ok' => true]);
}
$rid = (int)($in['recipe_id'] ?? 0);
if (!$rid) fail('Missing recipe');
db()->prepare("INSERT OR REPLACE INTO meal_plans (user_id,date,meal,recipe_id,cooked)
VALUES (?,?,?,?,COALESCE((SELECT cooked FROM meal_plans WHERE user_id=? AND date=? AND meal=?),0))")
->execute([$uid, $date, $meal, $rid, $uid, $date, $meal]);
out(['ok' => true]);
}
case 'mark_cooked': {
$uid = require_user();
$date = (string)($in['date'] ?? '');
$meal = (string)($in['meal'] ?? '');
db()->prepare("UPDATE meal_plans SET cooked=1 WHERE user_id=? AND date=? AND meal=?")->execute([$uid, $date, $meal]);
out(['ok' => true]);
}
case 'shopping_state': {
$uid = require_user();
$st = db()->prepare("SELECT item FROM shopping_checked WHERE user_id=?");
$st->execute([$uid]);
out(['ok' => true, 'checked' => array_column($st->fetchAll(), 'item')]);
}
case 'shopping_toggle': {
$uid = require_user();
$item = substr(trim((string)($in['item'] ?? '')), 0, 120);
if ($item === '') fail('Missing item');
if (!empty($in['on'])) db()->prepare("INSERT OR IGNORE INTO shopping_checked (user_id,item) VALUES (?,?)")->execute([$uid, $item]);
else db()->prepare("DELETE FROM shopping_checked WHERE user_id=? AND item=?")->execute([$uid, $item]);
out(['ok' => true]);
}
case 'shopping_clear': {
$uid = require_user();
db()->prepare("DELETE FROM shopping_checked WHERE user_id=?")->execute([$uid]);
out(['ok' => true]);
}
case 'exercises': {
require_user();
out(['ok' => true, 'exercises' => db()->query("SELECT * FROM exercises ORDER BY category, name")->fetchAll()]);
}
case 'log_workout': {
$uid = require_user();
$date = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($in['date'] ?? '')) ? $in['date'] : today();
$name = trim((string)($in['name'] ?? ''));
if ($name === '') fail('Missing workout name');
db()->prepare("INSERT INTO workouts (user_id,date,name,minutes,kcal) VALUES (?,?,?,?,?)")
->execute([$uid, $date, substr($name,0,80), (float)($in['minutes'] ?? 30), round((float)($in['kcal'] ?? 0))]);
out(['ok' => true, 'id' => (int)db()->lastInsertId()]);
}
case 'del_workout': {
$uid = require_user();
db()->prepare("DELETE FROM workouts WHERE id=? AND user_id=?")->execute([(int)($in['id'] ?? 0), $uid]);
out(['ok' => true]);
}
// ── Progress ─────────────────────────────────────────────────────────
case 'progress': {
$uid = require_user();
$st = db()->prepare("SELECT id, date, weight_kg, body_fat FROM weights WHERE user_id=? ORDER BY date");
$st->execute([$uid]);
$weights = $st->fetchAll();
$days = max(7, min(3650, (int)($in['days'] ?? 30)));
$since = date('Y-m-d', strtotime("-$days days"));
$st = db()->prepare("SELECT date, ROUND(SUM(kcal)) kcal, ROUND(SUM(protein),1) protein,
ROUND(SUM(carbs-fiber),1) netcarbs FROM diary WHERE user_id=? AND date>=? GROUP BY date ORDER BY date");
$st->execute([$uid, $since]);
$daily = $st->fetchAll();
$st = db()->prepare("SELECT date, ml FROM water WHERE user_id=? AND date>=? ORDER BY date");
$st->execute([$uid, $since]);
$water = $st->fetchAll();
$st = db()->prepare("SELECT COUNT(DISTINCT date) c FROM diary WHERE user_id=?");
$st->execute([$uid]);
$daysLogged = (int)$st->fetch()['c'];
// Logging streak: consecutive days with diary entries ending today/yesterday
$st = db()->prepare("SELECT DISTINCT date FROM diary WHERE user_id=? ORDER BY date DESC LIMIT 120");
$st->execute([$uid]);
$dates = array_column($st->fetchAll(), 'date');
$streak = 0;
$cursor = today();
if ($dates && $dates[0] !== $cursor) $cursor = date('Y-m-d', strtotime($cursor . ' -1 day'));
foreach ($dates as $d) {
if ($d === $cursor) { $streak++; $cursor = date('Y-m-d', strtotime($cursor . ' -1 day')); }
else break;
}
out(['ok' => true, 'weights' => $weights, 'daily' => $daily, 'water' => $water,
'days_logged' => $daysLogged, 'streak' => $streak]);
}
// ── Settings ─────────────────────────────────────────────────────────
case 'save_settings': {
$uid = require_user();
$allowed = ['anthropic_key','reminders_water','reminders_meals','reminders_weight','theme','water_glass_ml','cook_time','veg_plan',
'meal_breakfast','meal_lunch','meal_dinner','weigh_time','water_start','water_end','water_every',
'kcal_override','water_override',
'meal_breakfast_on','meal_lunch_on','meal_dinner_on','meals_skip_fasting'];
$st = db()->prepare("INSERT INTO settings (user_id,key,value) VALUES (?,?,?)
ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value");
foreach ($in as $k => $v) {
if (in_array($k, $allowed, true)) $st->execute([$uid, $k, substr((string)$v, 0, 300)]);
}
out(['ok' => true, 'settings' => get_settings($uid)]);
}
case 'has_api_key': {
$uid = require_user();
$st = db()->prepare("SELECT value FROM settings WHERE user_id=? AND key='anthropic_key'");
$st->execute([$uid]);
$v = $st->fetch()['value'] ?? '';
out(['ok' => true, 'has_key' => $v !== '']);
}
// ── Web Push (background notifications) ─────────────────────────────
case 'vapid_key': {
require_user();
out(['ok' => true, 'key' => vapid_public_key()]);
}
case 'push_subscribe': {
$uid = require_user();
$ep = (string)($in['endpoint'] ?? '');
if (!preg_match('#^https://#', $ep) || strlen($ep) > 600) fail('Bad subscription endpoint');
db()->prepare("INSERT INTO push_subs (user_id, endpoint, tz_offset) VALUES (?,?,?)
ON CONFLICT(endpoint) DO UPDATE SET user_id=excluded.user_id, tz_offset=excluded.tz_offset")
->execute([$uid, $ep, max(-840, min(840, (int)($in['tz_offset'] ?? 0)))]);
out(['ok' => true]);
}
case 'push_unsubscribe': {
$uid = require_user();
db()->prepare("DELETE FROM push_subs WHERE endpoint=? AND user_id=?")
->execute([(string)($in['endpoint'] ?? ''), $uid]);
out(['ok' => true]);
}
// Called by the service worker when a push wakes it: returns what to show.
case 'due_reminder': {
$uid = require_user();
$st = db()->prepare("SELECT value FROM settings WHERE user_id=? AND key='pending_push'");
$st->execute([$uid]);
$v = $st->fetch()['value'] ?? null;
if ($v) {
db()->prepare("DELETE FROM settings WHERE user_id=? AND key='pending_push'")->execute([$uid]);
$d = json_decode($v, true);
if (is_array($d) && !empty($d['title'])) out(['ok' => true, 'title' => $d['title'], 'body' => $d['body'] ?? '']);
}
out(['ok' => true, 'title' => 'Thrive', 'body' => 'Time for a healthy habit — log your day.']);
}
// Ready-to-paste URL for a free external cron pinger (cron-job.org etc.) to
// drive reminders when the host has no cron. Same key file cron.php uses.
case 'cron_url': {
// The cron token fires reminders for EVERY user, so only the site owner
// (first account) may see it. Other users' Settings simply hide the help.
if (require_user() !== 1) fail('Only the site owner can view the cron URL', 403);
$keyFile = __DIR__ . '/data/cron.key';
if (!is_file($keyFile)) { file_put_contents($keyFile, bin2hex(random_bytes(16))); @chmod($keyFile, 0600); }
$key = trim((string)file_get_contents($keyFile));
$scheme = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$dir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/'));
$base = rtrim($scheme . '://' . $host . $dir, '/');
out(['ok' => true, 'url' => $base . '/cron.php?token=' . $key]);
}
// ── AI photo scan ────────────────────────────────────────────────────
case 'analyze_photo': {
$uid = require_user();
$st = db()->prepare("SELECT value FROM settings WHERE user_id=? AND key='anthropic_key'");
$st->execute([$uid]);
$key = trim((string)($st->fetch()['value'] ?? ''));
if ($key === '') fail('Add an API key in Settings first (Settings → AI Photo Scan) — Ollama Cloud (free), Anthropic, or OpenAI');
$result = analyze_food_photo($key, (string)($in['image'] ?? ''));
out($result['ok'] ? ['ok' => true, 'items' => $result['items'], 'notes' => $result['notes']] : ['ok' => false, 'error' => $result['error']]);
}
default: fail('Unknown action', 404);
}
} catch (Throwable $e) {
// Log the detail server-side; never echo internals (paths, SQL) to clients.
error_log('Thrive API error [' . ($action ?? '?') . ']: ' . $e->getMessage());
http_response_code(500);
out(['ok' => false, 'error' => 'Server error — please try again']);
}