37243-vm/api/weather.php
2026-01-11 01:28:40 +00:00

71 lines
3.0 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/../db/config.php';
header('Content-Type: application/json');
$apiKey = get_api_key();
if (!$apiKey) {
error_log('API key is missing or not configured.');
http_response_code(500);
echo json_encode(['error' => 'API key is not configured.']);
exit;
}
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (strpos($authHeader, 'Bearer ') !== 0) {
http_response_code(401);
echo json_encode(['error' => 'Authorization header missing or invalid.']);
exit;
}
$token = substr($authHeader, 7);
if ($token !== $apiKey) {
http_response_code(401);
echo json_encode(['error' => 'Invalid API key.']);
exit;
}
log_api_request('weather');
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
try {
$pdo = db();
$stmt = $pdo->prepare(
"INSERT INTO weather (location_name, zip_code, observation_time, weather_condition, weather_description, weather_icon, temperature_f, feels_like_f, temp_min_f, temp_max_f, humidity_pct, wind_speed_mph, is_extreme_heat, is_extreme_cold, is_severe_weather, weather_alerts)
VALUES (:location_name, :zip_code, :observation_time, :weather_condition, :weather_description, :weather_icon, :temperature_f, :feels_like_f, :temp_min_f, :temp_max_f, :humidity_pct, :wind_speed_mph, :is_extreme_heat, :is_extreme_cold, :is_severe_weather, :weather_alerts)"
);
$stmt->execute([
':location_name' => $data['location_name'] ?? null,
':zip_code' => $data['zip_code'] ?? null,
':observation_time' => $data['observation_time'] ?? null,
':weather_condition' => $data['weather_condition'] ?? null,
':weather_description' => $data['weather_description'] ?? null,
':weather_icon' => $data['weather_icon'] ?? null,
':temperature_f' => $data['temperature_f'] ?? null,
':feels_like_f' => $data['feels_like_f'] ?? null,
':temp_min_f' => $data['temp_min_f'] ?? null,
':temp_max_f' => $data['temp_max_f'] ?? null,
':humidity_pct' => $data['humidity_pct'] ?? null,
':wind_speed_mph' => $data['wind_speed_mph'] ?? null,
':is_extreme_heat' => $data['is_extreme_heat'] ?? 0,
':is_extreme_cold' => $data['is_extreme_cold'] ?? 0,
':is_severe_weather' => $data['is_severe_weather'] ?? 0,
':weather_alerts' => isset($data['weather_alerts']) ? json_encode($data['weather_alerts']) : null,
]);
http_response_code(201);
echo json_encode(['success' => true, 'message' => 'Weather data created successfully.']);
} catch (PDOException $e) {
error_log("DB Error: " . $e->getMessage());
http_response_code(500);
echo json_encode(['error' => 'Database error.']);
}
} else {
http_response_code(405); // Method Not Allowed
echo json_encode(['error' => 'Only POST method is accepted.']);
}