"Parámetro 'ciudad' es requerido."]); exit(); // Stop script execution } if (!empty($fecha) && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $fecha)) { http_response_code(400); // Bad Request echo json_encode(["error" => "Parámetro 'fecha' debe tener el formato YYYY-MM-DD."]); exit(); } // Optional: Further sanitize/validate the city name if needed (e.g., alphanumeric only) // if (!preg_match('/^[a-zA-Z\s]+$/', $ciudad)) { // http_response_code(400); // echo json_encode(["error" => "El nombre de la ciudad contiene caracteres inválidos."]); // exit(); // } // --- 3. Database Connection --- $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if ($conn->connect_error) { http_response_code(500); // Internal Server Error echo json_encode(["error" => "Error de conexión a la base de datos: " . $conn->connect_error]); exit(); } // --- 4. Prepare and Execute Query --- $stmt = $conn->prepare(" SELECT DATE(fecha) AS dia, MIN(fecha) AS primera_fecha_del_dia, MIN(amanecer) AS amanecer, MAX(anochecer) AS anochecer, MAX(temp_max) AS temp_max, MIN(temp_min) AS temp_min, AVG(humedad) AS humedad, SUM(lluvia) AS lluvia, AVG(nubes) AS nubes, AVG(viento_velocidad) AS viento_velocidad, AVG(viento_direccion) AS viento_direccion FROM weather WHERE DATE(fecha) >= '2024-10-01' AND ciudad LIKE CONCAT('%', ?, '%') AND DATE(fecha) LIKE CONCAT('%', ?, '%') GROUP BY DATE(fecha) ORDER BY DATE(fecha); "); if (!$stmt) { http_response_code(500); // Internal Server Error echo json_encode(["error" => "Error al preparar la consulta: " . $conn->error]); $conn->close(); exit(); } $stmt->bind_param("ss", $ciudad, $fecha); $stmt->execute(); $result = $stmt->get_result(); $datos = []; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $datos[] = $row; } http_response_code(200); // OK echo json_encode($datos); } else { http_response_code(200); echo json_encode([]); // array vacío } // --- 5. Close Resources --- $stmt->close(); $conn->close(); ?>