query("SELECT goal_key, goal_value FROM user_goals"); $goals = []; while ($row = $stmt->fetch()) { $goals[$row['goal_key']] = (float)$row['goal_value']; } // Get today's nutrition logs $stmt = $pdo->prepare("SELECT SUM(calories) as calories, SUM(protein) as protein, SUM(creatine) as creatine FROM nutrition_logs WHERE DATE(created_at) = ?"); $stmt->execute([$today]); $stats = $stmt->fetch(); // Get today's water $stmtW = $pdo->prepare("SELECT SUM(amount) as amount FROM water_logs WHERE logged_at = ?"); $stmtW->execute([$today]); $waterStats = $stmtW->fetch(); $consumed = [ 'calories' => (int)($stats['calories'] ?? 0), 'protein' => (int)($stats['protein'] ?? 0), 'creatine' => (float)($stats['creatine'] ?? 0), 'water' => (float)($waterStats['amount'] ?? 0) ]; echo json_encode([ 'goals' => $goals, 'consumed' => $consumed, 'remaining' => [ 'calories' => max(0, ($goals['calories'] ?? 0) - $consumed['calories']), 'protein' => max(0, ($goals['protein'] ?? 0) - $consumed['protein']), 'creatine' => max(0, ($goals['creatine'] ?? 0) - $consumed['creatine']), 'water' => max(0, ($goals['water'] ?? 0) - $consumed['water']) ] ]); exit; } if ($action === 'add_log') { $input = json_decode(file_get_contents('php://input'), true); if (empty($input['entry_name'])) { echo json_encode(['error' => 'Name is required']); http_response_code(400); exit; } $stmt = $pdo->prepare("INSERT INTO nutrition_logs (entry_name, calories, protein, creatine) VALUES (?, ?, ?, ?)"); $stmt->execute([ $input['entry_name'], (int)($input['calories'] ?? 0), (int)($input['protein'] ?? 0), (float)($input['creatine'] ?? 0) ]); echo json_encode(['success' => true]); exit; } if ($action === 'get_recent') { $stmt = $pdo->query("SELECT * FROM nutrition_logs ORDER BY created_at DESC LIMIT 10"); echo json_encode($stmt->fetchAll()); exit; } if ($action === 'update_goals') { $input = json_decode(file_get_contents('php://input'), true); $stmt = $pdo->prepare("INSERT INTO user_goals (goal_key, goal_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE goal_value = VALUES(goal_value)"); $allowedKeys = ['calories', 'protein', 'creatine', 'water', 'weight']; foreach ($input as $key => $value) { if (in_array($key, $allowedKeys)) { $stmt->execute([$key, (float)$value]); } } echo json_encode(['success' => true]); exit; }